@aifight/aifight 0.1.0-alpha.3 → 0.1.0-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -0
- package/README.md +29 -4
- package/dist/bin.mjs +151 -127
- package/dist/index.mjs +1 -1
- package/dist/types/bridge/auto-update.d.ts +53 -0
- package/dist/types/cli/commands/bridge-update.d.ts +2 -0
- package/dist/types/index.d.ts +1 -1
- package/package.json +2 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "module"; const require = createRequire(import.meta.url);
|
|
3
|
-
var _p=Object.create;var $c=Object.defineProperty;var wp=Object.getOwnPropertyDescriptor;var vp=Object.getOwnPropertyNames;var bp=Object.getPrototypeOf,Sp=Object.prototype.hasOwnProperty;var Z=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ep=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vp(e))!Sp.call(t,o)&&o!==n&&$c(t,o,{get:()=>e[o],enumerable:!(r=wp(e,o))||r.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?_p(bp(t)):{},Ep(e||!t||!t.__esModule?$c(n,"default",{value:t,enumerable:!0}):n,t));var cr=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var sr=class{};D._CodeOrName=sr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ut=class extends sr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=Ut;var xe=class extends sr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ut&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=xe;D.nil=new xe("");function Bc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)vi(n,e[r]),n.push(t[++r]);return new xe(n)}D._=Bc;var wi=new xe("+");function qc(t,...e){let n=[ar(t[0])],r=0;for(;r<e.length;)n.push(wi),vi(n,e[r]),n.push(wi,ar(t[++r]));return jp(n),new xe(n)}D.str=qc;function vi(t,e){e instanceof xe?t.push(...e._items):e instanceof Ut?t.push(e):t.push(Bp(e))}D.addCodeArg=vi;function jp(t){let e=1;for(;e<t.length-1;){if(t[e]===wi){let n=Dp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Dp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ut||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ut))return`"${t}${e.slice(1)}`}function Fp(t,e){return e.emptyStr()?t:t.emptyStr()?e:qc`${t}${e}`}D.strConcat=Fp;function Bp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function qp(t){return new xe(ar(t))}D.stringify=qp;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=ar;function Up(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new xe(`.${t}`):Bc`[${t}]`}D.getProperty=Up;function Hp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new xe(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Hp;function Gp(t){return new xe(t.toString())}D.regexpCode=Gp});var Ei=_(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.ValueScope=we.ValueScopeName=we.Scope=we.varKinds=we.UsedValueState=void 0;var _e=cr(),bi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},oo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(oo||(we.UsedValueState=oo={}));we.varKinds={const:new _e.Name("const"),let:new _e.Name("let"),var:new _e.Name("var")};var io=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof _e.Name?e:this.name(e)}name(e){return new _e.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};we.Scope=io;var so=class extends _e.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,_e._)`.${new _e.Name(n)}[${r}]`}};we.ValueScopeName=so;var Wp=(0,_e._)`\n`,Si=class extends io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Wp:_e.nil}}get(){return this._scope}name(e){return new so(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,_e._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=_e.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,oo.Started);let u=n(l);if(u){let d=this.opts.es5?we.varKinds.var:we.varKinds.const;i=(0,_e._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,_e._)`${i}${u}${this.opts._n}`;else throw new bi(l);c.set(l,oo.Completed)})}return i}};we.ValueScope=Si});var A=_(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.or=x.and=x.not=x.CodeGen=x.operators=x.varKinds=x.ValueScopeName=x.ValueScope=x.Scope=x.Name=x.regexpCode=x.stringify=x.getProperty=x.nil=x.strConcat=x.str=x._=void 0;var N=cr(),je=Ei(),St=cr();Object.defineProperty(x,"_",{enumerable:!0,get:function(){return St._}});Object.defineProperty(x,"str",{enumerable:!0,get:function(){return St.str}});Object.defineProperty(x,"strConcat",{enumerable:!0,get:function(){return St.strConcat}});Object.defineProperty(x,"nil",{enumerable:!0,get:function(){return St.nil}});Object.defineProperty(x,"getProperty",{enumerable:!0,get:function(){return St.getProperty}});Object.defineProperty(x,"stringify",{enumerable:!0,get:function(){return St.stringify}});Object.defineProperty(x,"regexpCode",{enumerable:!0,get:function(){return St.regexpCode}});Object.defineProperty(x,"Name",{enumerable:!0,get:function(){return St.Name}});var uo=Ei();Object.defineProperty(x,"Scope",{enumerable:!0,get:function(){return uo.Scope}});Object.defineProperty(x,"ValueScope",{enumerable:!0,get:function(){return uo.ValueScope}});Object.defineProperty(x,"ValueScopeName",{enumerable:!0,get:function(){return uo.ValueScopeName}});Object.defineProperty(x,"varKinds",{enumerable:!0,get:function(){return uo.varKinds}});x.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},ki=class extends ct{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?je.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},ao=class extends ct{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return lo(e,this.rhs)}},$i=class extends ao{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ri=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Pi=class extends ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ti=class extends ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ai=class extends ct{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=bn(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},lr=class extends ct{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Vp(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wt(e,n.names),{})}},lt=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ci=class extends lr{},vn=class extends lt{};vn.kind="else";var Ht=class t extends lt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Uc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=bn(this.condition,e,n),this}get names(){let e=super.names;return lo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Ht.kind="if";var Gt=class extends lt{};Gt.kind="for";var xi=class extends Gt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=bn(this.iteration,e,n),this}get names(){return Wt(super.names,this.iteration.names)}},Ii=class extends Gt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?je.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=lo(super.names,this.from);return lo(e,this.to)}},co=class extends Gt{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=bn(this.iterable,e,n),this}get names(){return Wt(super.names,this.iterable.names)}},ur=class extends lt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ur.kind="func";var dr=class extends lr{render(e){return"return "+super.render(e)}};dr.kind="return";var Oi=class extends lt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Wt(e,this.catch.names),this.finally&&Wt(e,this.finally.names),e}},fr=class extends lt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var mr=class extends lt{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Ni=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
4
|
-
`:""},this._extScope=e,this._scope=new je.Scope({parent:e}),this._nodes=[new Ci]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new ki(e,i,r)),i}const(e,n,r){return this._def(je.varKinds.const,e,n,r)}let(e,n,r){return this._def(je.varKinds.let,e,n,r)}var(e,n,r){return this._def(je.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new ao(e,n,r))}add(e,n){return this._leafNode(new $i(e,x.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ai(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Ht(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ht(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Ht,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new xi(e),n)}forRange(e,n,r,o,i=this.opts.es5?je.varKinds.var:je.varKinds.let){let s=this._scope.toName(e);return this._for(new Ii(i,s,n,r),()=>o(s))}forOf(e,n,r,o=je.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new co("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?je.varKinds.var:je.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new co("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Gt)}label(e){return this._leafNode(new Ri(e))}break(e){return this._leafNode(new Pi(e))}return(e){let n=new dr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Oi;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new fr(i),n(i)}return r&&(this._currNode=o.finally=new mr,this.code(r)),this._endBlockNode(fr,mr)}throw(e){return this._leafNode(new Ti(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new ur(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ur)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Ht))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};x.CodeGen=Ni;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function lo(t,e){return e instanceof N._CodeOrName?Wt(t,e.names):t}function bn(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Vp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Uc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${Mi(t)}`}x.not=Uc;var zp=Hc(x.operators.AND);function Kp(...t){return t.reduce(zp)}x.and=Kp;var Jp=Hc(x.operators.OR);function Yp(...t){return t.reduce(Jp)}x.or=Yp;function Hc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${Mi(e)} ${t} ${Mi(n)}`}function Mi(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var M=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=A(),Qp=cr();function Xp(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=Xp;function Zp(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vc(t,e),!zc(e,t.self.RULES.all))}I.alwaysValidSchema=Zp;function Vc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Yc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Vc;function zc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=zc;function eh(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=eh;function th({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=th;function nh(t){return Kc(decodeURIComponent(t))}I.unescapeFragment=nh;function rh(t){return encodeURIComponent(ji(t))}I.escapeFragment=rh;function ji(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=ji;function Kc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Kc;function oh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=oh;function Gc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),Di(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jc}),items:Gc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Di(t,n,e),n}I.evaluatedPropsToName=Jc;function Di(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Di;var Wc={};function ih(t,e){return t.scopeValue("func",{ref:e,code:Wc[e.code]||(Wc[e.code]=new Qp._Code(e.code))})}I.useFunc=ih;var Li;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Li||(I.Type=Li={}));function sh(t,e,n){if(t instanceof q.Name){let r=e===Li.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+ji(t)}I.getErrorPath=sh;function Yc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Yc});var ut=_(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});var le=A(),ah={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Fi.default=ah});var pr=_(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var L=A(),fo=M(),he=ut();ue.keywordError={message:({keyword:t})=>(0,L.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,L.str)`"${t}" keyword must be ${e} ($data)`:(0,L.str)`"${t}" keyword is invalid ($data)`};function ch(t,e=ue.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=Zc(t,e,n);r??(s||a)?Qc(i,c):Xc(o,(0,L._)`[${c}]`)}ue.reportError=ch;function lh(t,e=ue.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=Zc(t,e,n);Qc(o,a),i||s||Xc(r,he.default.vErrors)}ue.reportExtraError=lh;function uh(t,e){t.assign(he.default.errors,e),t.if((0,L._)`${he.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,L._)`${he.default.vErrors}.length`,e),()=>t.assign(he.default.vErrors,null)))}ue.resetErrorsCount=uh;function dh({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,he.default.errors,a=>{t.const(s,(0,L._)`${he.default.vErrors}[${a}]`),t.if((0,L._)`${s}.instancePath === undefined`,()=>t.assign((0,L._)`${s}.instancePath`,(0,L.strConcat)(he.default.instancePath,i.errorPath))),t.assign((0,L._)`${s}.schemaPath`,(0,L.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,L._)`${s}.schema`,n),t.assign((0,L._)`${s}.data`,r))})}ue.extendErrors=dh;function Qc(t,e){let n=t.const("err",e);t.if((0,L._)`${he.default.vErrors} === null`,()=>t.assign(he.default.vErrors,(0,L._)`[${n}]`),(0,L._)`${he.default.vErrors}.push(${n})`),t.code((0,L._)`${he.default.errors}++`)}function Xc(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,L._)`new ${t.ValidationError}(${e})`):(n.assign((0,L._)`${r}.errors`,e),n.return(!1))}var Vt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function Zc(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,L._)`{}`:fh(t,e,n)}function fh(t,e,n={}){let{gen:r,it:o}=t,i=[mh(o,n),ph(t,n)];return hh(t,e,i),r.object(...i)}function mh({errorPath:t},{instancePath:e}){let n=e?(0,L.str)`${t}${(0,fo.getErrorPath)(e,fo.Type.Str)}`:t;return[he.default.instancePath,(0,L.strConcat)(he.default.instancePath,n)]}function ph({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,L.str)`${e}/${t}`;return n&&(o=(0,L.str)`${o}${(0,fo.getErrorPath)(n,fo.Type.Str)}`),[Vt.schemaPath,o]}function hh(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([Vt.keyword,o],[Vt.params,typeof e=="function"?e(t):e||(0,L._)`{}`]),c.messages&&r.push([Vt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vt.schema,s],[Vt.parentSchema,(0,L._)`${u}${d}`],[he.default.data,i]),l&&r.push([Vt.propertyName,l])}});var tl=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var gh=pr(),yh=A(),_h=ut(),wh={message:"boolean schema is false"};function vh(t){let{gen:e,schema:n,validateName:r}=t;n===!1?el(t,!1):typeof n=="object"&&n.$async===!0?e.return(_h.default.data):(e.assign((0,yh._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=vh;function bh(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),el(t)):n.var(e,!0)}Sn.boolOrEmptySchema=bh;function el(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gh.reportError)(o,wh,void 0,e)}});var Bi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Sh=["string","number","integer","boolean","null","object","array"],Eh=new Set(Sh);function kh(t){return typeof t=="string"&&Eh.has(t)}En.isJSONType=kh;function $h(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}En.getRules=$h});var qi=_(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.shouldUseRule=Et.shouldUseGroup=Et.schemaHasRulesForType=void 0;function Rh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&nl(t,r)}Et.schemaHasRulesForType=Rh;function nl(t,e){return e.rules.some(n=>rl(t,n))}Et.shouldUseGroup=nl;function rl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Et.shouldUseRule=rl});var hr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.reportTypeError=de.checkDataTypes=de.checkDataType=de.coerceAndCheckDataType=de.getJSONTypes=de.getSchemaTypes=de.DataType=void 0;var Ph=Bi(),Th=qi(),Ah=pr(),T=A(),ol=M(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(de.DataType=kn={}));function Ch(t){let e=il(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}de.getSchemaTypes=Ch;function il(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Ph.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}de.getJSONTypes=il;function xh(t,e){let{gen:n,data:r,opts:o}=t,i=Ih(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Th.schemaHasRulesForType)(t,e[0]));if(s){let a=Hi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Oh(t,e,i):Gi(t)})}return s}de.coerceAndCheckDataType=xh;var sl=new Set(["string","number","integer","boolean","null"]);function Ih(t,e){return e?t.filter(n=>sl.has(n)||e==="array"&&n==="array"):[]}function Oh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,T._)`typeof ${o}`),a=r.let("coerced",(0,T._)`undefined`);i.coerceTypes==="array"&&r.if((0,T._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,T._)`${o}[0]`).assign(s,(0,T._)`typeof ${o}`).if(Hi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,T._)`${a} !== undefined`);for(let l of n)(sl.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Gi(t),r.endIf(),r.if((0,T._)`${a} !== undefined`,()=>{r.assign(o,a),Nh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,T._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,T._)`"" + ${o}`).elseIf((0,T._)`${o} === null`).assign(a,(0,T._)`""`);return;case"number":r.elseIf((0,T._)`${s} == "boolean" || ${o} === null
|
|
5
|
-
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,
|
|
6
|
-
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,
|
|
7
|
-
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,T._)`[${o}]`)}}}function Nh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,T._)`${e} !== undefined`,()=>t.assign((0,T._)`${e}[${n}]`,r))}function Ui(t,e,n,r=kn.Correct){let o=r===kn.Correct?T.operators.EQ:T.operators.NEQ,i;switch(t){case"null":return(0,T._)`${e} ${o} null`;case"array":i=(0,T._)`Array.isArray(${e})`;break;case"object":i=(0,T._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,T._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,T._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,T.not)(i);function s(a=T.nil){return(0,T.and)((0,T._)`typeof ${e} == "number"`,a,n?(0,T._)`isFinite(${e})`:T.nil)}}de.checkDataType=Ui;function Hi(t,e,n,r){if(t.length===1)return Ui(t[0],e,n,r);let o,i=(0,ol.toHash)(t);if(i.array&&i.object){let s=(0,T._)`typeof ${e} != "object"`;o=i.null?s:(0,T._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=T.nil;i.number&&delete i.integer;for(let s in i)o=(0,T.and)(o,Ui(s,e,n,r));return o}de.checkDataTypes=Hi;var Mh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,T._)`{type: ${t}}`:(0,T._)`{type: ${e}}`};function Gi(t){let e=Lh(t);(0,Ah.reportError)(e,Mh)}de.reportTypeError=Gi;function Lh(t){let{gen:e,data:n,schema:r}=t,o=(0,ol.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var cl=_(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.assignDefaults=void 0;var $n=A(),jh=M();function Dh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)al(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>al(t,i,o.default))}mo.assignDefaults=Dh;function al(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(o){(0,jh.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(n)}`)}});var Ie=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var H=A(),Wi=M(),kt=ut(),Fh=M();function Bh(t,e){let{gen:n,data:r,it:o}=t;n.if(zi(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,H._)`${e}`},!0),t.error()})}F.checkReportMissingProp=Bh;function qh({gen:t,data:e,it:{opts:n}},r,o){return(0,H.or)(...r.map(i=>(0,H.and)(zi(t,e,i,n.ownProperties),(0,H._)`${o} = ${i}`)))}F.checkMissingProp=qh;function Uh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Uh;function ll(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,H._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=ll;function Vi(t,e,n){return(0,H._)`${ll(t)}.call(${e}, ${n})`}F.isOwnProperty=Vi;function Hh(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} !== undefined`;return r?(0,H._)`${o} && ${Vi(t,e,n)}`:o}F.propertyInData=Hh;function zi(t,e,n,r){let o=(0,H._)`${e}${(0,H.getProperty)(n)} === undefined`;return r?(0,H.or)(o,(0,H.not)(Vi(t,e,n))):o}F.noPropertyInData=zi;function ul(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ul;function Gh(t,e){return ul(e).filter(n=>!(0,Wi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Gh;function Wh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,H._)`${t}, ${e}, ${r}${o}`:e,d=[[kt.default.instancePath,(0,H.strConcat)(kt.default.instancePath,i)],[kt.default.parentData,s.parentData],[kt.default.parentDataProperty,s.parentDataProperty],[kt.default.rootData,kt.default.rootData]];s.opts.dynamicRef&&d.push([kt.default.dynamicAnchors,kt.default.dynamicAnchors]);let h=(0,H._)`${u}, ${n.object(...d)}`;return c!==H.nil?(0,H._)`${a}.call(${c}, ${h})`:(0,H._)`${a}(${h})`}F.callValidateCode=Wh;var Vh=(0,H._)`new RegExp`;function zh({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,H._)`${o.code==="new RegExp"?Vh:(0,Fh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=zh;function Kh(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,H._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:Wi.Type.Num},i),e.if((0,H.not)(i),a)})}}F.validateArray=Kh;function Jh(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Wi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,H._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,H.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=Jh});var ml=_(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var ge=A(),zt=ut(),Yh=Ie(),Qh=pr();function Xh(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=fl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Je.macroKeywordCode=Xh;function Zh(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;tg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=fl(r,o,l),d=r.let("valid");t.block$data(d,h),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function h(){if(e.errors===!1)m(),e.modifying&&dl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&dl(t),g(()=>eg(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(d,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ge._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ge._)`${u}.errors`;return r.assign(y,null),m(ge.nil),y}function m(y=e.async?(0,ge._)`await `:ge.nil){let v=c.opts.passContext?zt.default.this:zt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ge._)`${y}${(0,Yh.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ge.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Je.funcKeywordCode=Zh;function dl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function eg(t,e){let{gen:n}=t;n.if((0,ge._)`Array.isArray(${e})`,()=>{n.assign(zt.default.vErrors,(0,ge._)`${zt.default.vErrors} === null ? ${e} : ${zt.default.vErrors}.concat(${e})`).assign(zt.default.errors,(0,ge._)`${zt.default.vErrors}.length`),(0,Qh.extendErrors)(t)},()=>t.error())}function tg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function fl(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function ng(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Je.validSchemaType=ng;function rg({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Je.validateKeywordUsage=rg});var hl=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.extendSubschemaMode=$t.extendSubschemaData=$t.getSubschema=void 0;var Ye=A(),pl=M();function og(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Ye._)`${t.schemaPath}${(0,Ye.getProperty)(e)}${(0,Ye.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pl.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}$t.getSubschema=og;function ig(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,h=a.let("data",(0,Ye._)`${e.data}${(0,Ye.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Ye.str)`${l}${(0,pl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ye._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ye.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}$t.extendSubschemaData=ig;function sg(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}$t.extendSubschemaMode=sg});var Ki=_((B$,gl)=>{"use strict";gl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var _l=_((q$,yl)=>{"use strict";var Rt=yl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};po(e,r,o,t,"",t)};Rt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rt.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(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in Rt.arrayKeywords)for(var h=0;h<d.length;h++)po(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in Rt.propsKeywords){if(d&&typeof d=="object")for(var p in d)po(t,e,n,d[p],o+"/"+u+"/"+ag(p),i,o,u,r,p)}else(u in Rt.keywords||t.allKeys&&!(u in Rt.skipKeywords))&&po(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function ag(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var cg=M(),lg=Ki(),ug=_l(),dg=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function fg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ji(t):e?wl(t)<=e:!1}ve.inlineRef=fg;var mg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ji(t){for(let e in t){if(mg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Ji)||typeof n=="object"&&Ji(n))return!0}return!1}function wl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!dg.has(n)&&(typeof t[n]=="object"&&(0,cg.eachItem)(t[n],r=>e+=wl(r)),e===1/0))return 1/0}return e}function vl(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return bl(t,r)}ve.getFullPath=vl;function bl(t,e){return t.serialize(e).split("#")[0]+"#"}ve._getFullPath=bl;var pg=/#\/?$/;function Rn(t){return t?t.replace(pg,""):""}ve.normalizeId=Rn;function hg(t,e,n){return n=Rn(n),t.resolve(e,n)}ve.resolveUrl=hg;var gg=/^[a-z_][-a-z0-9._]*$/i;function yg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=vl(r,o,!1),a={},c=new Set;return ug(t,{allKeys:!0},(d,h,p,f)=>{if(f===void 0)return;let m=s+h,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[h]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=Rn(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?l(d,$.schema,S):S!==Rn(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!gg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!lg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ve.getSchemaRefs=yg});var wr=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getData=Pt.KeywordCxt=Pt.validateFunctionCode=void 0;var Rl=tl(),Sl=hr(),Qi=qi(),ho=hr(),_g=cl(),_r=ml(),Yi=hl(),b=A(),P=ut(),wg=gr(),dt=M(),yr=pr();function vg(t){if(Al(t)&&(Cl(t),Tl(t))){Eg(t);return}Pl(t,()=>(0,Rl.topBoolOrEmptySchema)(t))}Pt.validateFunctionCode=vg;function Pl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${El(n,o)}`),Sg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${bg(o)}`,r.$async,()=>t.code(El(n,o)).code(i))}function bg(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function Sg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function Eg(t){let{schema:e,opts:n,gen:r}=t;Pl(t,()=>{n.$comment&&e.$comment&&Il(t),Tg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&kg(t),xl(t),xg(t)})}function kg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function El(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function $g(t,e){if(Al(t)&&(Cl(t),Tl(t))){Rg(t,e);return}(0,Rl.boolOrEmptySchema)(t,e)}function Tl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Al(t){return typeof t.schema!="boolean"}function Rg(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Il(t),Ag(t),Cg(t);let i=r.const("_errs",P.default.errors);xl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Cl(t){(0,dt.checkUnknownRules)(t),Pg(t)}function xl(t,e){if(t.opts.jtd)return kl(t,[],!1,e);let n=(0,Sl.getSchemaTypes)(t.schema),r=(0,Sl.coerceAndCheckDataType)(t,n);kl(t,n,!r,e)}function Pg(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,dt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Tg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,dt.checkStrictMode)(t,"default is ignored in the schema root")}function Ag(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Cg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Il({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function xg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Ig(t),e.return((0,b._)`${P.default.errors} === 0`))}function Ig({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function kl(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,dt.schemaHasRulesButRef)(i,u))){o.block(()=>Nl(t,"$ref",u.all.$ref.definition));return}c.jtd||Og(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Qi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,ho.checkDataType)(h.type,s,c.strictNumbers)),$l(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,ho.reportTypeError)(t)),o.endIf()):$l(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function $l(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,_g.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Qi.shouldUseRule)(r,i)&&Nl(t,i.keyword,i.definition,e.type)})}function Og(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ng(t,e),t.opts.allowUnionTypes||Mg(t,e),Lg(t,t.dataTypes))}function Ng(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ol(t.dataTypes,n)||Xi(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Dg(t,e)}}function Mg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Xi(t,"use allowUnionTypes to allow union type keyword")}function Lg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Qi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>jg(e,s))&&Xi(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function jg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ol(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Dg(t,e){let n=[];for(let r of t.dataTypes)Ol(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Xi(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,dt.checkStrictMode)(t,e,t.opts.strictTypes)}var go=class{constructor(e,n,r){if((0,_r.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,dt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Ml(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_r.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?yr.reportExtraError:yr.reportError)(this,this.def.error,n)}$dataError(){(0,yr.reportError)(this,this.def.$dataError||yr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,ho.checkDataTypes)(c,n,i.opts.strictNumbers,ho.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,Yi.getSubschema)(this.it,e);(0,Yi.extendSubschemaData)(r,this.it,e),(0,Yi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return $g(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=dt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=dt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Pt.KeywordCxt=go;function Nl(t,e,n,r){let o=new go(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,_r.funcKeywordCode)(o,n):"macro"in n?(0,_r.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,_r.funcKeywordCode)(o,n)}var Fg=/^\/(?:[^~]|~0|~1)*$/,Bg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ml(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Fg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=Bg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,dt.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Pt.getData=Ml});var yo=_(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Zi=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};es.default=Zi});var vr=_(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var ts=gr(),ns=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ts.resolveUrl)(e,n,r),this.missingSchema=(0,ts.normalizeId)((0,ts.getFullPath)(e,this.missingRef))}};rs.default=ns});var wo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var De=A(),qg=yo(),Kt=ut(),Fe=gr(),Ll=M(),Ug=wr(),Pn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Fe.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Oe.SchemaEnv=Pn;function is(t){let e=jl.call(this,t);if(e)return e;let n=(0,Fe.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new De.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:qg.default,code:(0,De._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Kt.default.data,parentData:Kt.default.parentData,parentDataProperty:Kt.default.parentDataProperty,dataNames:[Kt.default.data],dataPathArr:[De.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,De.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:De.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,De._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Ug.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Kt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Kt.default.self}`,`${Kt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;p.evaluated={props:f instanceof De.Name?void 0:f,items:m instanceof De.Name?void 0:m,dynamicProps:f instanceof De.Name,dynamicItems:m instanceof De.Name},p.source&&(p.source.evaluated=(0,De.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Oe.compileSchema=is;function Hg(t,e,n){var r;n=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Vg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new Pn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Gg.call(this,i)}Oe.resolveRef=Hg;function Gg(t){return(0,Fe.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:is.call(this,t)}function jl(t){for(let e of this._compilations)if(Wg(e,t))return e}Oe.getCompilingSchema=jl;function Wg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Vg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_o.call(this,t,e)}function _o(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Fe._getFullPath)(this.opts.uriResolver,n),o=(0,Fe.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return os.call(this,n,t);let i=(0,Fe.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=_o.call(this,t,s);return typeof a?.schema!="object"?void 0:os.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||is.call(this,s),i===(0,Fe.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Fe.resolveUrl)(this.opts.uriResolver,o,l)),new Pn({schema:a,schemaId:c,root:t,baseId:o})}return os.call(this,n,s)}}Oe.resolveSchema=_o;var zg=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function os(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Ll.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!zg.has(a)&&l&&(e=(0,Fe.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Ll.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Fe.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=_o.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new Pn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Dl=_((z$,Kg)=>{Kg.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 as=_((K$,Ul)=>{"use strict";var Jg=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Bl=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);function ss(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var Yg=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fl(t){return t.length=0,!0}function Qg(t,e,n){if(t.length){let r=ss(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Xg(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=Qg;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=Fl}else{o.push(l);continue}}return o.length&&(a===Fl?n.zone=o.join(""):s?r.push(o.join("")):r.push(ss(o))),n.address=r.join(""),n}function ql(t){if(Zg(t,":")<2)return{host:t,isIPV6:!1};let e=Xg(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Zg(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ey(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function ty(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ny(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Bl(n)){let r=ql(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Ul.exports={nonSimpleDomain:Yg,recomposeAuthority:ny,normalizeComponentEncoding:ty,removeDotSegments:ey,isIPv4:Bl,isUUID:Jg,normalizeIPv6:ql,stringArrayToHexStripped:ss}});var zl=_((J$,Vl)=>{"use strict";var{isUUID:ry}=as(),oy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,iy=["http","https","ws","wss","urn","urn:uuid"];function sy(t){return iy.indexOf(t)!==-1}function cs(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Hl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Gl(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function ay(t){return t.secure=cs(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function cy(t){if((t.port===(cs(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function ly(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(oy);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=ls(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function uy(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=ls(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function dy(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ry(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function fy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wl={scheme:"http",domainHost:!0,parse:Hl,serialize:Gl},my={scheme:"https",domainHost:Wl.domainHost,parse:Hl,serialize:Gl},vo={scheme:"ws",domainHost:!0,parse:ay,serialize:cy},py={scheme:"wss",domainHost:vo.domainHost,parse:vo.parse,serialize:vo.serialize},hy={scheme:"urn",parse:ly,serialize:uy,skipNormalize:!0},gy={scheme:"urn:uuid",parse:dy,serialize:fy,skipNormalize:!0},bo={http:Wl,https:my,ws:vo,wss:py,urn:hy,"urn:uuid":gy};Object.setPrototypeOf(bo,null);function ls(t){return t&&(bo[t]||bo[t.toLowerCase()])||void 0}Vl.exports={wsIsSecure:cs,SCHEMES:bo,isValidSchemeName:sy,getSchemeHandler:ls}});var Yl=_((Y$,Eo)=>{"use strict";var{normalizeIPv6:yy,removeDotSegments:br,recomposeAuthority:_y,normalizeComponentEncoding:So,isIPv4:wy,nonSimpleDomain:vy}=as(),{SCHEMES:by,getSchemeHandler:Kl}=zl();function Sy(t,e){return typeof t=="string"?t=Qe(ft(t,e),e):typeof t=="object"&&(t=ft(Qe(t,e),e)),t}function Ey(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Jl(ft(t,r),ft(e,r),r,!0);return r.skipEscape=!0,Qe(o,r)}function Jl(t,e,n,r){let o={};return r||(t=ft(Qe(t,n),n),e=ft(Qe(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=br(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ky(t,e,n){return typeof t=="string"?(t=unescape(t),t=Qe(So(ft(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Qe(So(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Qe(So(ft(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Qe(So(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Qe(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=Kl(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=_y(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=br(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var $y=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ft(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match($y);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(wy(r.host)===!1){let c=yy(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=Kl(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&vy(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var us={SCHEMES:by,normalize:Sy,resolve:Ey,resolveComponent:Jl,equal:ky,serialize:Qe,parse:ft};Eo.exports=us;Eo.exports.default=us;Eo.exports.fastUri=us});var Xl=_(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var Ql=Yl();Ql.code='require("ajv/dist/runtime/uri").default';ds.default=Ql});var su=_(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.CodeGen=se.Name=se.nil=se.stringify=se.str=se._=se.KeywordCxt=void 0;var Ry=wr();Object.defineProperty(se,"KeywordCxt",{enumerable:!0,get:function(){return Ry.KeywordCxt}});var Tn=A();Object.defineProperty(se,"_",{enumerable:!0,get:function(){return Tn._}});Object.defineProperty(se,"str",{enumerable:!0,get:function(){return Tn.str}});Object.defineProperty(se,"stringify",{enumerable:!0,get:function(){return Tn.stringify}});Object.defineProperty(se,"nil",{enumerable:!0,get:function(){return Tn.nil}});Object.defineProperty(se,"Name",{enumerable:!0,get:function(){return Tn.Name}});Object.defineProperty(se,"CodeGen",{enumerable:!0,get:function(){return Tn.CodeGen}});var Py=yo(),ru=vr(),Ty=Bi(),Sr=wo(),Ay=A(),Er=gr(),ko=hr(),ms=M(),Zl=Dl(),Cy=Xl(),ou=(t,e)=>new RegExp(t,e);ou.code="new RegExp";var xy=["removeAdditional","useDefaults","coerceTypes"],Iy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Oy={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."},Ny={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},eu=200;function My(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,$,z,Q,ie,ze;let it=t.strict,nr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ke=nr===!0||nr===void 0?1:nr||0,ne=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ou,Bt=(o=t.uriResolver)!==null&&o!==void 0?o:Cy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:it)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:it)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:it)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:it)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:it)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Ke,regExp:ne}:{optimize:Ke,regExp:ne},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:eu,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:eu,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(z=t.validateSchema)!==null&&z!==void 0?z:!0,validateFormats:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(ie=t.unicodeRegExp)!==null&&ie!==void 0?ie:!0,int32range:(ze=t.int32range)!==null&&ze!==void 0?ze:!0,uriResolver:Bt}}var kr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...My(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Ay.ValueScope({scope:{},prefixes:Iy,es5:n,lines:r}),this.logger=qy(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ty.getRules)(),tu.call(this,Oy,e,"NOT SUPPORTED"),tu.call(this,Ny,e,"DEPRECATED","warn"),this._metaOpts=Fy.call(this),e.formats&&jy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Dy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ly.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=Zl;r==="id"&&(o={...Zl},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}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 ru.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,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Er.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=nu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Sr.SchemaEnv({schema:{},schemaId:r});if(n=Sr.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=nu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Er.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Hy.call(this,r,n),!n)return(0,ms.eachItem)(r,i=>fs.call(this,i)),this;Wy.call(this,n);let o={...n,type:(0,ko.getJSONTypes)(n.type),schemaType:(0,ko.getJSONTypes)(n.schemaType)};return(0,ms.eachItem)(r,o.type.length===0?i=>fs.call(this,i,o):i=>o.type.forEach(s=>fs.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=iu(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,Er.normalizeId)(s||r);let l=Er.getSchemaRefs.call(this,e,r);return c=new Sr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Sr.compileSchema.call(this,e)}finally{this.opts=n}}};kr.ValidationError=Py.default;kr.MissingRefError=ru.default;se.default=kr;function tu(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function nu(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ly(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function jy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Dy(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Fy(){let t={...this.opts};for(let e of xy)delete t[e];return t}var By={log(){},warn(){},error(){}};function qy(t){if(t===!1)return By;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Uy=/^[a-z_$][a-z0-9_$:-]*$/i;function Hy(t,e){let{RULES:n}=this;if((0,ms.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Uy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function fs(t,e,n){var r;let o=e?.post;if(n&&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===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ko.getJSONTypes)(e.type),schemaType:(0,ko.getJSONTypes)(e.schemaType)}};e.before?Gy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function Gy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Wy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=iu(e)),t.validateSchema=this.compile(e,!0))}var Vy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function iu(t){return{anyOf:[t,Vy]}}});var au=_(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var zy={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ps.default=zy});var du=_(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.callRef=Jt.getValidate=void 0;var Ky=vr(),cu=Ie(),be=A(),An=ut(),lu=wo(),$o=M(),Jy={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=lu.resolveRef.call(c,l,o,n);if(u===void 0)throw new Ky.default(r.opts.uriResolver,o,n);if(u instanceof lu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Ro(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Ro(t,(0,be._)`${f}.validate`,l,l.$async)}function h(f){let m=uu(t,f);Ro(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,be.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:be.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function uu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,be._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Jt.getValidate=uu;function Ro(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?An.default.this:be.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,be._)`await ${(0,cu.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,be._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,cu.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,be._)`${f}.errors`;o.assign(An.default.vErrors,(0,be._)`${An.default.vErrors} === null ? ${m} : ${An.default.vErrors}.concat(${m})`),o.assign(An.default.errors,(0,be._)`${An.default.vErrors}.length`)}function p(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=$o.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,be._)`${f}.evaluated.props`);i.props=$o.mergeEvaluated.props(o,y,i.props,be.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=$o.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,be._)`${f}.evaluated.items`);i.items=$o.mergeEvaluated.items(o,y,i.items,be.Name)}}}Jt.callRef=Ro;Jt.default=Jy});var fu=_(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var Yy=au(),Qy=du(),Xy=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Yy.default,Qy.default];hs.default=Xy});var mu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var Po=A(),Tt=Po.operators,To={maximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},minimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},exclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},exclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},Zy={message:({keyword:t,schemaCode:e})=>(0,Po.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Po._)`{comparison: ${To[t].okStr}, limit: ${e}}`},e_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:Zy,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Po._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};gs.default=e_});var pu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var $r=A(),t_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},n_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:t_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,$r._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$r._)`${s} !== parseInt(${s})`;t.fail$data((0,$r._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};ys.default=n_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});function hu(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}_s.default=hu;hu.code='require("ajv/dist/runtime/ucs2length").default'});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var Yt=A(),r_=M(),o_=gu(),i_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Yt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Yt._)`{limit: ${t}}`},s_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Yt.operators.GT:Yt.operators.LT,s=o.opts.unicode===!1?(0,Yt._)`${n}.length`:(0,Yt._)`${(0,r_.useFunc)(t.gen,o_.default)}(${n})`;t.fail$data((0,Yt._)`${s} ${i} ${r}`)}};ws.default=s_});var _u=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var a_=Ie(),c_=M(),Cn=A(),l_={message:({schemaCode:t})=>(0,Cn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cn._)`{pattern: ${t}}`},u_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:l_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,Cn._)`new RegExp`:(0,c_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Cn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Cn._)`!${u}`)}else{let c=(0,a_.usePattern)(t,o);t.fail$data((0,Cn._)`!${c}.test(${n})`)}}};vs.default=u_});var wu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Rr=A(),d_={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Rr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Rr._)`{limit: ${t}}`},f_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:d_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Rr.operators.GT:Rr.operators.LT;t.fail$data((0,Rr._)`Object.keys(${n}).length ${o} ${r}`)}};bs.default=f_});var vu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var Pr=Ie(),Tr=A(),m_=M(),p_={message:({params:{missingProperty:t}})=>(0,Tr.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Tr._)`{missingProperty: ${t}}`},h_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:p_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(p?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,m_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Tr.nil,d);else for(let p of n)(0,Pr.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>h(p,f)),t.ok(f)}else e.if((0,Pr.checkMissingProp)(t,n,p)),(0,Pr.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Pr.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Pr.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Tr.not)(f),()=>{t.error(),e.break()})},Tr.nil)}}};Ss.default=h_});var bu=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Ar=A(),g_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ar.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ar._)`{limit: ${t}}`},y_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:g_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ar.operators.GT:Ar.operators.LT;t.fail$data((0,Ar._)`${n}.length ${o} ${r}`)}};Es.default=y_});var Ao=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Su=Ki();Su.code='require("ajv/dist/runtime/equal").default';ks.default=Su});var Eu=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $s=hr(),ae=A(),__=M(),w_=Ao(),v_={message:({params:{i:t,j:e}})=>(0,ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ae._)`{i: ${t}, j: ${e}}`},b_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:v_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,$s.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,ae._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,ae._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,ae._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,$s.checkDataTypes)(l,g,a.opts.strictNumbers,$s.DataType.Wrong),v=e.const("indices",(0,ae._)`{}`);e.for((0,ae._)`;${f}--;`,()=>{e.let(g,(0,ae._)`${n}[${f}]`),e.if(y,(0,ae._)`continue`),l.length>1&&e.if((0,ae._)`typeof ${g} == "string"`,(0,ae._)`${g} += "_"`),e.if((0,ae._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,ae._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,ae._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,__.useFunc)(e,w_.default),y=e.name("outer");e.label(y).for((0,ae._)`;${f}--;`,()=>e.for((0,ae._)`${m} = ${f}; ${m}--;`,()=>e.if((0,ae._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Rs.default=b_});var ku=_(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var Ps=A(),S_=M(),E_=Ao(),k_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ps._)`{allowedValue: ${t}}`},$_={keyword:"const",$data:!0,error:k_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ps._)`!${(0,S_.useFunc)(e,E_.default)}(${n}, ${o})`):t.fail((0,Ps._)`${i} !== ${n}`)}};Ts.default=$_});var $u=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Cr=A(),R_=M(),P_=Ao(),T_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Cr._)`{allowedValues: ${t}}`},A_={keyword:"enum",schemaType:"array",$data:!0,error:T_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,R_.useFunc)(e,P_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Cr.or)(...o.map((f,m)=>h(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Cr._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,Cr._)`${l()}(${n}, ${p}[${f}])`:(0,Cr._)`${n} === ${m}`}}};As.default=A_});var Ru=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var C_=mu(),x_=pu(),I_=yu(),O_=_u(),N_=wu(),M_=vu(),L_=bu(),j_=Eu(),D_=ku(),F_=$u(),B_=[C_.default,x_.default,I_.default,O_.default,N_.default,M_.default,L_.default,j_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},D_.default,F_.default];Cs.default=B_});var Is=_(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateAdditionalItems=void 0;var Qt=A(),xs=M(),q_={message:({params:{len:t}})=>(0,Qt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qt._)`{limit: ${t}}`},U_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:q_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,xs.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Pu(t,r)}};function Pu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Qt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Qt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,xs.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Qt._)`${a} <= ${e.length}`);n.if((0,Qt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:xs.Type.Num},l),s.allErrors||n.if((0,Qt.not)(l),()=>n.break())})}}xr.validateAdditionalItems=Pu;xr.default=U_});var Os=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var Tu=A(),Co=M(),H_=Ie(),G_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Au(t,"additionalItems",e);n.items=!0,!(0,Co.alwaysValidSchema)(n,e)&&t.ok((0,H_.validateArray)(t))}};function Au(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Co.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Tu._)`${i}.length`);n.forEach((d,h)=>{(0,Co.alwaysValidSchema)(a,d)||(r.if((0,Tu._)`${l} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function u(d){let{opts:h,errSchemaPath:p}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(h.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Co.checkStrictMode)(a,g,h.strictTuples)}}}Ir.validateTuple=Au;Ir.default=G_});var Cu=_(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var W_=Os(),V_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,W_.validateTuple)(t,"items")};Ns.default=V_});var Iu=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var xu=A(),z_=M(),K_=Ie(),J_=Is(),Y_={message:({params:{len:t}})=>(0,xu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xu._)`{limit: ${t}}`},Q_={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Y_,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,z_.alwaysValidSchema)(r,e)&&(o?(0,J_.validateAdditionalItems)(t,o):t.ok((0,K_.validateArray)(t)))}};Ms.default=Q_});var Ou=_(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Ne=A(),xo=M(),X_={message:({params:{min:t,max:e}})=>e===void 0?(0,Ne.str)`must contain at least ${t} valid item(s)`:(0,Ne.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ne._)`{minContains: ${t}}`:(0,Ne._)`{minContains: ${t}, maxContains: ${e}}`},Z_={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:X_,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Ne._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,xo.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,xo.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,xo.alwaysValidSchema)(i,n)){let m=(0,Ne._)`${u} >= ${s}`;a!==void 0&&(m=(0,Ne._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Ne._)`${o}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>f(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:xo.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Ne._)`${m}++`),a===void 0?e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Ne._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Ls.default=Z_});var Lu=_(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var js=A(),ew=M(),Or=Ie();Xe.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,js.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,js._)`{property: ${t},
|
|
3
|
+
var $p=Object.create;var Ac=Object.defineProperty;var Rp=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,Tp=Object.prototype.hasOwnProperty;var ee=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var xp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pp(e))!Tp.call(t,o)&&o!==n&&Ac(t,o,{get:()=>e[o],enumerable:!(r=Rp(e,o))||r.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?$p(Ap(t)):{},xp(e||!t||!t.__esModule?Ac(n,"default",{value:t,enumerable:!0}):n,t));var cr=_(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.regexpCode=D.getEsmExportName=D.getProperty=D.safeStringify=D.stringify=D.strConcat=D.addCodeArg=D.str=D._=D.nil=D._Code=D.Name=D.IDENTIFIER=D._CodeOrName=void 0;var sr=class{};D._CodeOrName=sr;D.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ht=class extends sr{constructor(e){if(super(),!D.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};D.Name=Ht;var Ce=class extends sr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Ht&&(n[r.str]=(n[r.str]||0)+1),n),{})}};D._Code=Ce;D.nil=new Ce("");function Hc(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Si(n,e[r]),n.push(t[++r]);return new Ce(n)}D._=Hc;var bi=new Ce("+");function Gc(t,...e){let n=[ar(t[0])],r=0;for(;r<e.length;)n.push(bi),Si(n,e[r]),n.push(bi,ar(t[++r]));return Gp(n),new Ce(n)}D.str=Gc;function Si(t,e){e instanceof Ce?t.push(...e._items):e instanceof Ht?t.push(e):t.push(zp(e))}D.addCodeArg=Si;function Gp(t){let e=1;for(;e<t.length-1;){if(t[e]===bi){let n=Vp(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Vp(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ht||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ht))return`"${t}${e.slice(1)}`}function Wp(t,e){return e.emptyStr()?t:t.emptyStr()?e:Gc`${t}${e}`}D.strConcat=Wp;function zp(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ar(Array.isArray(t)?t.join(","):t)}function Kp(t){return new Ce(ar(t))}D.stringify=Kp;function ar(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}D.safeStringify=ar;function Jp(t){return typeof t=="string"&&D.IDENTIFIER.test(t)?new Ce(`.${t}`):Hc`[${t}]`}D.getProperty=Jp;function Yp(t){if(typeof t=="string"&&D.IDENTIFIER.test(t))return new Ce(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}D.getEsmExportName=Yp;function Qp(t){return new Ce(t.toString())}D.regexpCode=Qp});var $i=_(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.ValueScope=ve.ValueScopeName=ve.Scope=ve.varKinds=ve.UsedValueState=void 0;var we=cr(),Ei=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},io;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(io||(ve.UsedValueState=io={}));ve.varKinds={const:new we.Name("const"),let:new we.Name("let"),var:new we.Name("var")};var so=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof we.Name?e:this.name(e)}name(e){return new we.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ve.Scope=so;var ao=class extends we.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,we._)`.${new we.Name(n)}[${r}]`}};ve.ValueScopeName=ao;var Xp=(0,we._)`\n`,ki=class extends so{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Xp:we.nil}}get(){return this._scope}name(e){return new ao(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:i,itemIndex:l}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,we._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let i=we.nil;for(let s in e){let a=e[s];if(!a)continue;let c=r[s]=r[s]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,io.Started);let u=n(l);if(u){let d=this.opts.es5?ve.varKinds.var:ve.varKinds.const;i=(0,we._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))i=(0,we._)`${i}${u}${this.opts._n}`;else throw new Ei(l);c.set(l,io.Completed)})}return i}};ve.ValueScope=ki});var T=_(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.or=C.and=C.not=C.CodeGen=C.operators=C.varKinds=C.ValueScopeName=C.ValueScope=C.Scope=C.Name=C.regexpCode=C.stringify=C.getProperty=C.nil=C.strConcat=C.str=C._=void 0;var N=cr(),De=$i(),kt=cr();Object.defineProperty(C,"_",{enumerable:!0,get:function(){return kt._}});Object.defineProperty(C,"str",{enumerable:!0,get:function(){return kt.str}});Object.defineProperty(C,"strConcat",{enumerable:!0,get:function(){return kt.strConcat}});Object.defineProperty(C,"nil",{enumerable:!0,get:function(){return kt.nil}});Object.defineProperty(C,"getProperty",{enumerable:!0,get:function(){return kt.getProperty}});Object.defineProperty(C,"stringify",{enumerable:!0,get:function(){return kt.stringify}});Object.defineProperty(C,"regexpCode",{enumerable:!0,get:function(){return kt.regexpCode}});Object.defineProperty(C,"Name",{enumerable:!0,get:function(){return kt.Name}});var fo=$i();Object.defineProperty(C,"Scope",{enumerable:!0,get:function(){return fo.Scope}});Object.defineProperty(C,"ValueScope",{enumerable:!0,get:function(){return fo.ValueScope}});Object.defineProperty(C,"ValueScopeName",{enumerable:!0,get:function(){return fo.ValueScopeName}});Object.defineProperty(C,"varKinds",{enumerable:!0,get:function(){return fo.varKinds}});C.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};var lt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ri=class extends lt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?De.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=bn(this.rhs,e,n)),this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}},co=class extends lt{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return uo(e,this.rhs)}},Pi=class extends co{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ai=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ti=class extends lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},xi=class extends lt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ci=class extends lt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=bn(this.code,e,n),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}},lr=class extends lt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let i=r[o];i.optimizeNames(e,n)||(Zp(e,i.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wt(e,n.names),{})}},ut=class extends lr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ii=class extends lr{},vn=class extends ut{};vn.kind="else";var Gt=class t extends ut{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Vc(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=bn(this.condition,e,n),this}get names(){let e=super.names;return uo(e,this.condition),this.else&&Wt(e,this.else.names),e}};Gt.kind="if";var Vt=class extends ut{};Vt.kind="for";var Oi=class extends Vt{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=bn(this.iteration,e,n),this}get names(){return Wt(super.names,this.iteration.names)}},Ni=class extends Vt{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?De.varKinds.var:this.varKind,{name:r,from:o,to:i}=this;return`for(${n} ${r}=${o}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=uo(super.names,this.from);return uo(e,this.to)}},lo=class extends Vt{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=bn(this.iterable,e,n),this}get names(){return Wt(super.names,this.iterable.names)}},ur=class extends ut{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ur.kind="func";var dr=class extends lr{render(e){return"return "+super.render(e)}};dr.kind="return";var Li=class extends ut{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Wt(e,this.catch.names),this.finally&&Wt(e,this.finally.names),e}},fr=class extends ut{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fr.kind="catch";var mr=class extends ut{render(e){return"finally"+super.render(e)}};mr.kind="finally";var Mi=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
4
|
+
`:""},this._extScope=e,this._scope=new De.Scope({parent:e}),this._nodes=[new Ii]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let i=this._scope.toName(n);return r!==void 0&&o&&(this._constants[i.str]=r),this._leafNode(new Ri(e,i,r)),i}const(e,n,r){return this._def(De.varKinds.const,e,n,r)}let(e,n,r){return this._def(De.varKinds.let,e,n,r)}var(e,n,r){return this._def(De.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new co(e,n,r))}add(e,n){return this._leafNode(new Pi(e,C.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==N.nil&&this._leafNode(new Ci(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,N.addCodeArg)(n,o));return n.push("}"),new N._Code(n)}if(e,n,r){if(this._blockNode(new Gt(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Gt(e))}else(){return this._elseNode(new vn)}endIf(){return this._endBlockNode(Gt,vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Oi(e),n)}forRange(e,n,r,o,i=this.opts.es5?De.varKinds.var:De.varKinds.let){let s=this._scope.toName(e);return this._for(new Ni(i,s,n,r),()=>o(s))}forOf(e,n,r,o=De.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=n instanceof N.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,N._)`${s}.length`,a=>{this.var(i,(0,N._)`${s}[${a}]`),r(i)})}return this._for(new lo("of",o,i,n),()=>r(i))}forIn(e,n,r,o=this.opts.es5?De.varKinds.var:De.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,N._)`Object.keys(${n})`,r);let i=this._scope.toName(e);return this._for(new lo("in",o,i,n),()=>r(i))}endFor(){return this._endBlockNode(Vt)}label(e){return this._leafNode(new Ai(e))}break(e){return this._leafNode(new Ti(e))}return(e){let n=new dr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(dr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Li;if(this._blockNode(o),this.code(e),n){let i=this.name("e");this._currNode=o.catch=new fr(i),n(i)}return r&&(this._currNode=o.finally=new mr,this.code(r)),this._endBlockNode(fr,mr)}throw(e){return this._leafNode(new xi(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=N.nil,r,o){return this._blockNode(new ur(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ur)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Gt))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};C.CodeGen=Mi;function Wt(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function uo(t,e){return e instanceof N._CodeOrName?Wt(t,e.names):t}function bn(t,e,n){if(t instanceof N.Name)return r(t);if(!o(t))return t;return new N._Code(t._items.reduce((i,s)=>(s instanceof N.Name&&(s=r(s)),s instanceof N._Code?i.push(...s._items):i.push(s),i),[]));function r(i){let s=n[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof N._Code&&i._items.some(s=>s instanceof N.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function Zp(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Vc(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,N._)`!${ji(t)}`}C.not=Vc;var eh=Wc(C.operators.AND);function th(...t){return t.reduce(eh)}C.and=th;var nh=Wc(C.operators.OR);function rh(...t){return t.reduce(nh)}C.or=rh;function Wc(t){return(e,n)=>e===N.nil?n:n===N.nil?e:(0,N._)`${ji(e)} ${t} ${ji(n)}`}function ji(t){return t instanceof N.Name?t:(0,N._)`(${t})`}});var L=_(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.checkStrictMode=I.getErrorPath=I.Type=I.useFunc=I.setEvaluated=I.evaluatedPropsToName=I.mergeEvaluated=I.eachItem=I.unescapeJsonPointer=I.escapeJsonPointer=I.escapeFragment=I.unescapeFragment=I.schemaRefOrVal=I.schemaHasRulesButRef=I.schemaHasRules=I.checkUnknownRules=I.alwaysValidSchema=I.toHash=void 0;var q=T(),oh=cr();function ih(t){let e={};for(let n of t)e[n]=!0;return e}I.toHash=ih;function sh(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Jc(t,e),!Yc(e,t.self.RULES.all))}I.alwaysValidSchema=sh;function Jc(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let i in e)o[i]||Zc(t,`unknown keyword: "${i}"`)}I.checkUnknownRules=Jc;function Yc(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}I.schemaHasRules=Yc;function ah(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}I.schemaHasRulesButRef=ah;function ch({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,q._)`${n}`}return(0,q._)`${t}${e}${(0,q.getProperty)(r)}`}I.schemaRefOrVal=ch;function lh(t){return Qc(decodeURIComponent(t))}I.unescapeFragment=lh;function uh(t){return encodeURIComponent(Fi(t))}I.escapeFragment=uh;function Fi(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}I.escapeJsonPointer=Fi;function Qc(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}I.unescapeJsonPointer=Qc;function dh(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}I.eachItem=dh;function zc({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof q.Name?(i instanceof q.Name?t(o,i,s):e(o,i,s),s):i instanceof q.Name?(e(o,s,i),i):n(i,s);return a===q.Name&&!(c instanceof q.Name)?r(o,c):c}}I.mergeEvaluated={props:zc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,q._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,q._)`${n} || {}`).code((0,q._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,q._)`${n} || {}`),Bi(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Xc}),items:zc({mergeNames:(t,e,n)=>t.if((0,q._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,q._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,q._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,q._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Xc(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,q._)`{}`);return e!==void 0&&Bi(t,n,e),n}I.evaluatedPropsToName=Xc;function Bi(t,e,n){Object.keys(n).forEach(r=>t.assign((0,q._)`${e}${(0,q.getProperty)(r)}`,!0))}I.setEvaluated=Bi;var Kc={};function fh(t,e){return t.scopeValue("func",{ref:e,code:Kc[e.code]||(Kc[e.code]=new oh._Code(e.code))})}I.useFunc=fh;var Di;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Di||(I.Type=Di={}));function mh(t,e,n){if(t instanceof q.Name){let r=e===Di.Num;return n?r?(0,q._)`"[" + ${t} + "]"`:(0,q._)`"['" + ${t} + "']"`:r?(0,q._)`"/" + ${t}`:(0,q._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,q.getProperty)(t).toString():"/"+Fi(t)}I.getErrorPath=mh;function Zc(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}I.checkStrictMode=Zc});var dt=_(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});var ue=T(),ph={data:new ue.Name("data"),valCxt:new ue.Name("valCxt"),instancePath:new ue.Name("instancePath"),parentData:new ue.Name("parentData"),parentDataProperty:new ue.Name("parentDataProperty"),rootData:new ue.Name("rootData"),dynamicAnchors:new ue.Name("dynamicAnchors"),vErrors:new ue.Name("vErrors"),errors:new ue.Name("errors"),this:new ue.Name("this"),self:new ue.Name("self"),scope:new ue.Name("scope"),json:new ue.Name("json"),jsonPos:new ue.Name("jsonPos"),jsonLen:new ue.Name("jsonLen"),jsonPart:new ue.Name("jsonPart")};Ui.default=ph});var pr=_(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.extendErrors=de.resetErrorsCount=de.reportExtraError=de.reportError=de.keyword$DataError=de.keywordError=void 0;var M=T(),mo=L(),ge=dt();de.keywordError={message:({keyword:t})=>(0,M.str)`must pass "${t}" keyword validation`};de.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,M.str)`"${t}" keyword must be ${e} ($data)`:(0,M.str)`"${t}" keyword is invalid ($data)`};function hh(t,e=de.keywordError,n,r){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=nl(t,e,n);r??(s||a)?el(i,c):tl(o,(0,M._)`[${c}]`)}de.reportError=hh;function gh(t,e=de.keywordError,n){let{it:r}=t,{gen:o,compositeRule:i,allErrors:s}=r,a=nl(t,e,n);el(o,a),i||s||tl(r,ge.default.vErrors)}de.reportExtraError=gh;function yh(t,e){t.assign(ge.default.errors,e),t.if((0,M._)`${ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,M._)`${ge.default.vErrors}.length`,e),()=>t.assign(ge.default.vErrors,null)))}de.resetErrorsCount=yh;function _h({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,ge.default.errors,a=>{t.const(s,(0,M._)`${ge.default.vErrors}[${a}]`),t.if((0,M._)`${s}.instancePath === undefined`,()=>t.assign((0,M._)`${s}.instancePath`,(0,M.strConcat)(ge.default.instancePath,i.errorPath))),t.assign((0,M._)`${s}.schemaPath`,(0,M.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,M._)`${s}.schema`,n),t.assign((0,M._)`${s}.data`,r))})}de.extendErrors=_h;function el(t,e){let n=t.const("err",e);t.if((0,M._)`${ge.default.vErrors} === null`,()=>t.assign(ge.default.vErrors,(0,M._)`[${n}]`),(0,M._)`${ge.default.vErrors}.push(${n})`),t.code((0,M._)`${ge.default.errors}++`)}function tl(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,M._)`new ${t.ValidationError}(${e})`):(n.assign((0,M._)`${r}.errors`,e),n.return(!1))}var zt={keyword:new M.Name("keyword"),schemaPath:new M.Name("schemaPath"),params:new M.Name("params"),propertyName:new M.Name("propertyName"),message:new M.Name("message"),schema:new M.Name("schema"),parentSchema:new M.Name("parentSchema")};function nl(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,M._)`{}`:wh(t,e,n)}function wh(t,e,n={}){let{gen:r,it:o}=t,i=[vh(o,n),bh(t,n)];return Sh(t,e,i),r.object(...i)}function vh({errorPath:t},{instancePath:e}){let n=e?(0,M.str)`${t}${(0,mo.getErrorPath)(e,mo.Type.Str)}`:t;return[ge.default.instancePath,(0,M.strConcat)(ge.default.instancePath,n)]}function bh({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,M.str)`${e}/${t}`;return n&&(o=(0,M.str)`${o}${(0,mo.getErrorPath)(n,mo.Type.Str)}`),[zt.schemaPath,o]}function Sh(t,{params:e,message:n},r){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;r.push([zt.keyword,o],[zt.params,typeof e=="function"?e(t):e||(0,M._)`{}`]),c.messages&&r.push([zt.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([zt.schema,s],[zt.parentSchema,(0,M._)`${u}${d}`],[ge.default.data,i]),l&&r.push([zt.propertyName,l])}});var ol=_(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.boolOrEmptySchema=Sn.topBoolOrEmptySchema=void 0;var Eh=pr(),kh=T(),$h=dt(),Rh={message:"boolean schema is false"};function Ph(t){let{gen:e,schema:n,validateName:r}=t;n===!1?rl(t,!1):typeof n=="object"&&n.$async===!0?e.return($h.default.data):(e.assign((0,kh._)`${r}.errors`,null),e.return(!0))}Sn.topBoolOrEmptySchema=Ph;function Ah(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),rl(t)):n.var(e,!0)}Sn.boolOrEmptySchema=Ah;function rl(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Eh.reportError)(o,Rh,void 0,e)}});var qi=_(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.getRules=En.isJSONType=void 0;var Th=["string","number","integer","boolean","null","object","array"],xh=new Set(Th);function Ch(t){return typeof t=="string"&&xh.has(t)}En.isJSONType=Ch;function Ih(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}En.getRules=Ih});var Hi=_($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function Oh({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&il(t,r)}$t.schemaHasRulesForType=Oh;function il(t,e){return e.rules.some(n=>sl(t,n))}$t.shouldUseGroup=il;function sl(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}$t.shouldUseRule=sl});var hr=_(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.reportTypeError=fe.checkDataTypes=fe.checkDataType=fe.coerceAndCheckDataType=fe.getJSONTypes=fe.getSchemaTypes=fe.DataType=void 0;var Nh=qi(),Lh=Hi(),Mh=pr(),A=T(),al=L(),kn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(kn||(fe.DataType=kn={}));function jh(t){let e=cl(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}fe.getSchemaTypes=jh;function cl(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Nh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}fe.getJSONTypes=cl;function Dh(t,e){let{gen:n,data:r,opts:o}=t,i=Fh(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,Lh.schemaHasRulesForType)(t,e[0]));if(s){let a=Vi(e,r,o.strictNumbers,kn.Wrong);n.if(a,()=>{i.length?Bh(t,e,i):Wi(t)})}return s}fe.coerceAndCheckDataType=Dh;var ll=new Set(["string","number","integer","boolean","null"]);function Fh(t,e){return e?t.filter(n=>ll.has(n)||e==="array"&&n==="array"):[]}function Bh(t,e,n){let{gen:r,data:o,opts:i}=t,s=r.let("dataType",(0,A._)`typeof ${o}`),a=r.let("coerced",(0,A._)`undefined`);i.coerceTypes==="array"&&r.if((0,A._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,A._)`${o}[0]`).assign(s,(0,A._)`typeof ${o}`).if(Vi(e,o,i.strictNumbers),()=>r.assign(a,o))),r.if((0,A._)`${a} !== undefined`);for(let l of n)(ll.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);r.else(),Wi(t),r.endIf(),r.if((0,A._)`${a} !== undefined`,()=>{r.assign(o,a),Uh(t,a)});function c(l){switch(l){case"string":r.elseIf((0,A._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,A._)`"" + ${o}`).elseIf((0,A._)`${o} === null`).assign(a,(0,A._)`""`);return;case"number":r.elseIf((0,A._)`${s} == "boolean" || ${o} === null
|
|
5
|
+
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,A._)`+${o}`);return;case"integer":r.elseIf((0,A._)`${s} === "boolean" || ${o} === null
|
|
6
|
+
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,A._)`+${o}`);return;case"boolean":r.elseIf((0,A._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,A._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,A._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,A._)`${s} === "string" || ${s} === "number"
|
|
7
|
+
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,A._)`[${o}]`)}}}function Uh({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,A._)`${e} !== undefined`,()=>t.assign((0,A._)`${e}[${n}]`,r))}function Gi(t,e,n,r=kn.Correct){let o=r===kn.Correct?A.operators.EQ:A.operators.NEQ,i;switch(t){case"null":return(0,A._)`${e} ${o} null`;case"array":i=(0,A._)`Array.isArray(${e})`;break;case"object":i=(0,A._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,A._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,A._)`typeof ${e} ${o} ${t}`}return r===kn.Correct?i:(0,A.not)(i);function s(a=A.nil){return(0,A.and)((0,A._)`typeof ${e} == "number"`,a,n?(0,A._)`isFinite(${e})`:A.nil)}}fe.checkDataType=Gi;function Vi(t,e,n,r){if(t.length===1)return Gi(t[0],e,n,r);let o,i=(0,al.toHash)(t);if(i.array&&i.object){let s=(0,A._)`typeof ${e} != "object"`;o=i.null?s:(0,A._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=A.nil;i.number&&delete i.integer;for(let s in i)o=(0,A.and)(o,Gi(s,e,n,r));return o}fe.checkDataTypes=Vi;var qh={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,A._)`{type: ${t}}`:(0,A._)`{type: ${e}}`};function Wi(t){let e=Hh(t);(0,Mh.reportError)(e,qh)}fe.reportTypeError=Wi;function Hh(t){let{gen:e,data:n,schema:r}=t,o=(0,al.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var dl=_(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.assignDefaults=void 0;var $n=T(),Gh=L();function Vh(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)ul(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,i)=>ul(t,i,o.default))}po.assignDefaults=Vh;function ul(t,e,n){let{gen:r,compositeRule:o,data:i,opts:s}=t;if(n===void 0)return;let a=(0,$n._)`${i}${(0,$n.getProperty)(e)}`;if(o){(0,Gh.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,$n._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,$n._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,$n._)`${a} = ${(0,$n.stringify)(n)}`)}});var Ie=_(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.validateUnion=F.validateArray=F.usePattern=F.callValidateCode=F.schemaProperties=F.allSchemaProperties=F.noPropertyInData=F.propertyInData=F.isOwnProperty=F.hasPropFunc=F.reportMissingProp=F.checkMissingProp=F.checkReportMissingProp=void 0;var G=T(),zi=L(),Rt=dt(),Wh=L();function zh(t,e){let{gen:n,data:r,it:o}=t;n.if(Ji(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,G._)`${e}`},!0),t.error()})}F.checkReportMissingProp=zh;function Kh({gen:t,data:e,it:{opts:n}},r,o){return(0,G.or)(...r.map(i=>(0,G.and)(Ji(t,e,i,n.ownProperties),(0,G._)`${o} = ${i}`)))}F.checkMissingProp=Kh;function Jh(t,e){t.setParams({missingProperty:e},!0),t.error()}F.reportMissingProp=Jh;function fl(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,G._)`Object.prototype.hasOwnProperty`})}F.hasPropFunc=fl;function Ki(t,e,n){return(0,G._)`${fl(t)}.call(${e}, ${n})`}F.isOwnProperty=Ki;function Yh(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} !== undefined`;return r?(0,G._)`${o} && ${Ki(t,e,n)}`:o}F.propertyInData=Yh;function Ji(t,e,n,r){let o=(0,G._)`${e}${(0,G.getProperty)(n)} === undefined`;return r?(0,G.or)(o,(0,G.not)(Ki(t,e,n))):o}F.noPropertyInData=Ji;function ml(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}F.allSchemaProperties=ml;function Qh(t,e){return ml(e).filter(n=>!(0,zi.alwaysValidSchema)(t,e[n]))}F.schemaProperties=Qh;function Xh({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:i},it:s},a,c,l){let u=l?(0,G._)`${t}, ${e}, ${r}${o}`:e,d=[[Rt.default.instancePath,(0,G.strConcat)(Rt.default.instancePath,i)],[Rt.default.parentData,s.parentData],[Rt.default.parentDataProperty,s.parentDataProperty],[Rt.default.rootData,Rt.default.rootData]];s.opts.dynamicRef&&d.push([Rt.default.dynamicAnchors,Rt.default.dynamicAnchors]);let h=(0,G._)`${u}, ${n.object(...d)}`;return c!==G.nil?(0,G._)`${a}.call(${c}, ${h})`:(0,G._)`${a}(${h})`}F.callValidateCode=Xh;var Zh=(0,G._)`new RegExp`;function eg({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(n,r);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,G._)`${o.code==="new RegExp"?Zh:(0,Wh.useFunc)(t,o)}(${n}, ${r})`})}F.usePattern=eg;function tg(t){let{gen:e,data:n,keyword:r,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,G._)`${n}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:r,dataProp:l,dataPropType:zi.Type.Num},i),e.if((0,G.not)(i),a)})}}F.validateArray=tg;function ng(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,zi.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,l)=>{let u=t.subschema({keyword:r,schemaProp:l,compositeRule:!0},a);e.assign(s,(0,G._)`${s} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,G.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}F.validateUnion=ng});var gl=_(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.validateKeywordUsage=Ye.validSchemaType=Ye.funcKeywordCode=Ye.macroKeywordCode=void 0;var ye=T(),Kt=dt(),rg=Ie(),og=pr();function ig(t,e){let{gen:n,keyword:r,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=hl(n,r,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let l=n.name("valid");t.subschema({schema:a,schemaPath:ye.nil,errSchemaPath:`${s.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Ye.macroKeywordCode=ig;function sg(t,e){var n;let{gen:r,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;cg(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,u=hl(r,o,l),d=r.let("valid");t.block$data(d,h),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function h(){if(e.errors===!1)m(),e.modifying&&pl(t),g(()=>t.error());else{let y=e.async?p():f();e.modifying&&pl(t),g(()=>ag(t,y))}}function p(){let y=r.let("ruleErrs",null);return r.try(()=>m((0,ye._)`await `),v=>r.assign(d,!1).if((0,ye._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,ye._)`${v}.errors`),()=>r.throw(v))),y}function f(){let y=(0,ye._)`${u}.errors`;return r.assign(y,null),m(ye.nil),y}function m(y=e.async?(0,ye._)`await `:ye.nil){let v=c.opts.passContext?Kt.default.this:Kt.default.self,S=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,ye._)`${y}${(0,rg.callValidateCode)(t,u,v,S)}`,e.modifying)}function g(y){var v;r.if((0,ye.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}Ye.funcKeywordCode=sg;function pl(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,ye._)`${r.parentData}[${r.parentDataProperty}]`))}function ag(t,e){let{gen:n}=t;n.if((0,ye._)`Array.isArray(${e})`,()=>{n.assign(Kt.default.vErrors,(0,ye._)`${Kt.default.vErrors} === null ? ${e} : ${Kt.default.vErrors}.concat(${e})`).assign(Kt.default.errors,(0,ye._)`${Kt.default.vErrors}.length`),(0,og.extendErrors)(t)},()=>t.error())}function cg({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function hl(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ye.stringify)(n)})}function lg(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ye.validSchemaType=lg;function ug({schema:t,opts:e,self:n,errSchemaPath:r},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(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Ye.validateKeywordUsage=ug});var _l=_(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendSubschemaMode=Pt.extendSubschemaData=Pt.getSubschema=void 0;var Qe=T(),yl=L();function dg(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Qe._)`${t.schemaPath}${(0,Qe.getProperty)(e)}${(0,Qe.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,yl.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Pt.getSubschema=dg;function fg(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,h=a.let("data",(0,Qe._)`${e.data}${(0,Qe.getProperty)(n)}`,!0);c(h),t.errorPath=(0,Qe.str)`${l}${(0,yl.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Qe._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Qe.Name?o:a.let("data",o,!0);c(l),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Pt.extendSubschemaData=fg;function mg(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:i}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=n}Pt.extendSubschemaMode=mg});var Yi=_((aR,wl)=>{"use strict";wl.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,i;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[o]))return!1;for(o=r;o--!==0;){var s=i[o];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var bl=_((cR,vl)=>{"use strict";var At=vl.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};ho(e,r,o,t,"",t)};At.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};At.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};At.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};At.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 ho(t,e,n,r,o,i,s,a,c,l){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,i,s,a,c,l);for(var u in r){var d=r[u];if(Array.isArray(d)){if(u in At.arrayKeywords)for(var h=0;h<d.length;h++)ho(t,e,n,d[h],o+"/"+u+"/"+h,i,o,u,r,h)}else if(u in At.propsKeywords){if(d&&typeof d=="object")for(var p in d)ho(t,e,n,d[p],o+"/"+u+"/"+pg(p),i,o,u,r,p)}else(u in At.keywords||t.allKeys&&!(u in At.skipKeywords))&&ho(t,e,n,d,o+"/"+u,i,o,u,r)}n(r,o,i,s,a,c,l)}}function pg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gr=_(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.getSchemaRefs=be.resolveUrl=be.normalizeId=be._getFullPath=be.getFullPath=be.inlineRef=void 0;var hg=L(),gg=Yi(),yg=bl(),_g=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wg(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qi(t):e?Sl(t)<=e:!1}be.inlineRef=wg;var vg=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qi(t){for(let e in t){if(vg.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Qi)||typeof n=="object"&&Qi(n))return!0}return!1}function Sl(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!_g.has(n)&&(typeof t[n]=="object"&&(0,hg.eachItem)(t[n],r=>e+=Sl(r)),e===1/0))return 1/0}return e}function El(t,e="",n){n!==!1&&(e=Rn(e));let r=t.parse(e);return kl(t,r)}be.getFullPath=El;function kl(t,e){return t.serialize(e).split("#")[0]+"#"}be._getFullPath=kl;var bg=/#\/?$/;function Rn(t){return t?t.replace(bg,""):""}be.normalizeId=Rn;function Sg(t,e,n){return n=Rn(n),t.resolve(e,n)}be.resolveUrl=Sg;var Eg=/^[a-z_][-a-z0-9._]*$/i;function kg(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Rn(t[n]||e),i={"":o},s=El(r,o,!1),a={},c=new Set;return yg(t,{allKeys:!0},(d,h,p,f)=>{if(f===void 0)return;let m=s+h,g=i[f];typeof d[n]=="string"&&(g=y.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),i[h]=g;function y(S){let R=this.opts.uriResolver.resolve;if(S=Rn(g?R(g,S):S),c.has(S))throw u(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?l(d,$.schema,S):S!==Rn(m)&&(S[0]==="#"?(l(d,a[S],S),a[S]=d):this.refs[S]=m),S}function v(S){if(typeof S=="string"){if(!Eg.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function l(d,h,p){if(h!==void 0&&!gg(d,h))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}be.getSchemaRefs=kg});var wr=_(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Tl=ol(),$l=hr(),Zi=Hi(),go=hr(),$g=dl(),_r=gl(),Xi=_l(),b=T(),P=dt(),Rg=gr(),ft=L(),yr=pr();function Pg(t){if(Il(t)&&(Ol(t),Cl(t))){xg(t);return}xl(t,()=>(0,Tl.topBoolOrEmptySchema)(t))}Tt.validateFunctionCode=Pg;function xl({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},i){o.code.es5?t.func(e,(0,b._)`${P.default.data}, ${P.default.valCxt}`,r.$async,()=>{t.code((0,b._)`"use strict"; ${Rl(n,o)}`),Tg(t,o),t.code(i)}):t.func(e,(0,b._)`${P.default.data}, ${Ag(o)}`,r.$async,()=>t.code(Rl(n,o)).code(i))}function Ag(t){return(0,b._)`{${P.default.instancePath}="", ${P.default.parentData}, ${P.default.parentDataProperty}, ${P.default.rootData}=${P.default.data}${t.dynamicRef?(0,b._)`, ${P.default.dynamicAnchors}={}`:b.nil}}={}`}function Tg(t,e){t.if(P.default.valCxt,()=>{t.var(P.default.instancePath,(0,b._)`${P.default.valCxt}.${P.default.instancePath}`),t.var(P.default.parentData,(0,b._)`${P.default.valCxt}.${P.default.parentData}`),t.var(P.default.parentDataProperty,(0,b._)`${P.default.valCxt}.${P.default.parentDataProperty}`),t.var(P.default.rootData,(0,b._)`${P.default.valCxt}.${P.default.rootData}`),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`${P.default.valCxt}.${P.default.dynamicAnchors}`)},()=>{t.var(P.default.instancePath,(0,b._)`""`),t.var(P.default.parentData,(0,b._)`undefined`),t.var(P.default.parentDataProperty,(0,b._)`undefined`),t.var(P.default.rootData,P.default.data),e.dynamicRef&&t.var(P.default.dynamicAnchors,(0,b._)`{}`)})}function xg(t){let{schema:e,opts:n,gen:r}=t;xl(t,()=>{n.$comment&&e.$comment&&Ll(t),Lg(t),r.let(P.default.vErrors,null),r.let(P.default.errors,0),n.unevaluated&&Cg(t),Nl(t),Dg(t)})}function Cg(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,b._)`${n}.evaluated`),e.if((0,b._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,b._)`${t.evaluated}.props`,(0,b._)`undefined`)),e.if((0,b._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,b._)`${t.evaluated}.items`,(0,b._)`undefined`))}function Rl(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,b._)`/*# sourceURL=${n} */`:b.nil}function Ig(t,e){if(Il(t)&&(Ol(t),Cl(t))){Og(t,e);return}(0,Tl.boolOrEmptySchema)(t,e)}function Cl({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Il(t){return typeof t.schema!="boolean"}function Og(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Ll(t),Mg(t),jg(t);let i=r.const("_errs",P.default.errors);Nl(t,i),r.var(e,(0,b._)`${i} === ${P.default.errors}`)}function Ol(t){(0,ft.checkUnknownRules)(t),Ng(t)}function Nl(t,e){if(t.opts.jtd)return Pl(t,[],!1,e);let n=(0,$l.getSchemaTypes)(t.schema),r=(0,$l.coerceAndCheckDataType)(t,n);Pl(t,n,!r,e)}function Ng(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,ft.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Lg(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,ft.checkStrictMode)(t,"default is ignored in the schema root")}function Mg(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Rg.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function jg(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ll({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let i=n.$comment;if(o.$comment===!0)t.code((0,b._)`${P.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,b.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,b._)`${P.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Dg(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:i}=t;n.$async?e.if((0,b._)`${P.default.errors} === 0`,()=>e.return(P.default.data),()=>e.throw((0,b._)`new ${o}(${P.default.vErrors})`)):(e.assign((0,b._)`${r}.errors`,P.default.vErrors),i.unevaluated&&Fg(t),e.return((0,b._)`${P.default.errors} === 0`))}function Fg({gen:t,evaluated:e,props:n,items:r}){n instanceof b.Name&&t.assign((0,b._)`${e}.props`,n),r instanceof b.Name&&t.assign((0,b._)`${e}.items`,r)}function Pl(t,e,n,r){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,ft.schemaHasRulesButRef)(i,u))){o.block(()=>jl(t,"$ref",u.all.$ref.definition));return}c.jtd||Bg(t,e),o.block(()=>{for(let h of u.rules)d(h);d(u.post)});function d(h){(0,Zi.shouldUseGroup)(i,h)&&(h.type?(o.if((0,go.checkDataType)(h.type,s,c.strictNumbers)),Al(t,h),e.length===1&&e[0]===h.type&&n&&(o.else(),(0,go.reportTypeError)(t)),o.endIf()):Al(t,h),a||o.if((0,b._)`${P.default.errors} === ${r||0}`))}}function Al(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,$g.assignDefaults)(t,e.type),n.block(()=>{for(let i of e.rules)(0,Zi.shouldUseRule)(r,i)&&jl(t,i.keyword,i.definition,e.type)})}function Bg(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Ug(t,e),t.opts.allowUnionTypes||qg(t,e),Hg(t,t.dataTypes))}function Ug(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Ml(t.dataTypes,n)||es(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Vg(t,e)}}function qg(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&es(t,"use allowUnionTypes to allow union type keyword")}function Hg(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,Zi.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>Gg(e,s))&&es(t,`missing type "${i.join(",")}" for keyword "${r}"`)}}}function Gg(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ml(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Vg(t,e){let n=[];for(let r of t.dataTypes)Ml(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function es(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,ft.checkStrictMode)(t,e,t.opts.strictTypes)}var yo=class{constructor(e,n,r){if((0,_r.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ft.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Dl(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_r.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",P.default.errors))}result(e,n,r){this.failResult((0,b.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,b.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,b._)`${n} !== undefined && (${(0,b.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?yr.reportExtraError:yr.reportError)(this,this.def.error,n)}$dataError(){(0,yr.reportError)(this,this.def.$dataError||yr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,yr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=b.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=b.nil,n=b.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:i,def:s}=this;r.if((0,b.or)((0,b._)`${o} === undefined`,n)),e!==b.nil&&r.assign(e,!0),(i.length||s.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==b.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:i}=this;return(0,b.or)(s(),a());function s(){if(r.length){if(!(n instanceof b.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,b._)`${(0,go.checkDataTypes)(c,n,i.opts.strictNumbers,go.DataType.Wrong)}`}return b.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,b._)`!${c}(${n})`}return b.nil}}subschema(e,n){let r=(0,Xi.getSubschema)(this.it,e);(0,Xi.extendSubschemaData)(r,this.it,e),(0,Xi.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return Ig(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=ft.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=ft.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,b.Name)),!0}};Tt.KeywordCxt=yo;function jl(t,e,n,r){let o=new yo(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,_r.funcKeywordCode)(o,n):"macro"in n?(0,_r.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,_r.funcKeywordCode)(o,n)}var Wg=/^\/(?:[^~]|~0|~1)*$/,zg=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Dl(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,i;if(t==="")return P.default.rootData;if(t[0]==="/"){if(!Wg.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=P.default.rootData}else{let l=zg.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return r[e-u]}if(u>e)throw new Error(c("data",u));if(i=n[e-u],!o)return i}let s=i,a=o.split("/");for(let l of a)l&&(i=(0,b._)`${i}${(0,b.getProperty)((0,ft.unescapeJsonPointer)(l))}`,s=(0,b._)`${s} && ${i}`);return s;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Tt.getData=Dl});var _o=_(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var ts=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ns.default=ts});var vr=_(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var rs=gr(),os=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,rs.resolveUrl)(e,n,r),this.missingSchema=(0,rs.normalizeId)((0,rs.getFullPath)(e,this.missingRef))}};is.default=os});var vo=_(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.resolveSchema=Oe.getCompilingSchema=Oe.resolveRef=Oe.compileSchema=Oe.SchemaEnv=void 0;var Fe=T(),Kg=_o(),Jt=dt(),Be=gr(),Fl=L(),Jg=wr(),Pn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Be.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Oe.SchemaEnv=Pn;function as(t){let e=Bl.call(this,t);if(e)return e;let n=(0,Be.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Fe.CodeGen(this.scope,{es5:r,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Kg.default,code:(0,Fe._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let l={gen:s,allErrors:this.opts.allErrors,data:Jt.default.data,parentData:Jt.default.parentData,parentDataProperty:Jt.default.parentDataProperty,dataNames:[Jt.default.data],dataPathArr:[Fe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Fe.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:Fe.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Fe._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Jg.validateFunctionCode)(l),s.optimize(this.opts.code.optimize);let d=s.toString();u=`${s.scopeRefs(Jt.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let p=new Function(`${Jt.default.self}`,`${Jt.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:f,items:m}=l;p.evaluated={props:f instanceof Fe.Name?void 0:f,items:m instanceof Fe.Name?void 0:m,dynamicProps:f instanceof Fe.Name,dynamicItems:m instanceof Fe.Name},p.source&&(p.source.evaluated=(0,Fe.stringify)(p.evaluated))}return t.validate=p,t}catch(d){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(t)}}Oe.compileSchema=as;function Yg(t,e,n){var r;n=(0,Be.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let i=Zg.call(this,t,n);if(i===void 0){let s=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;s&&(i=new Pn({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[n]=Qg.call(this,i)}Oe.resolveRef=Yg;function Qg(t){return(0,Be.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:as.call(this,t)}function Bl(t){for(let e of this._compilations)if(Xg(e,t))return e}Oe.getCompilingSchema=Bl;function Xg(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Zg(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||wo.call(this,t,e)}function wo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,Be._getFullPath)(this.opts.uriResolver,n),o=(0,Be.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return ss.call(this,n,t);let i=(0,Be.normalizeId)(r),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=wo.call(this,t,s);return typeof a?.schema!="object"?void 0:ss.call(this,n,a)}if(typeof s?.schema=="object"){if(s.validate||as.call(this,s),i===(0,Be.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Be.resolveUrl)(this.opts.uriResolver,o,l)),new Pn({schema:a,schemaId:c,root:t,baseId:o})}return ss.call(this,n,s)}}Oe.resolveSchema=wo;var ey=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ss(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let c=n[(0,Fl.unescapeFragment)(a)];if(c===void 0)return;n=c;let l=typeof n=="object"&&n[this.opts.schemaId];!ey.has(a)&&l&&(e=(0,Be.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof n!="boolean"&&n.$ref&&!(0,Fl.schemaHasRulesButRef)(n,this.RULES)){let a=(0,Be.resolveUrl)(this.opts.uriResolver,e,n.$ref);i=wo.call(this,r,a)}let{schemaId:s}=this.opts;if(i=i||new Pn({schema:n,schemaId:s,root:r,baseId:e}),i.schema!==i.root.schema)return i}});var Ul=_((pR,ty)=>{ty.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 ls=_((hR,Vl)=>{"use strict";var ny=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hl=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);function cs(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var ry=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ql(t){return t.length=0,!0}function oy(t,e,n){if(t.length){let r=cs(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function iy(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],i=!1,s=!1,a=oy;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(i===!0&&(s=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),r.push(":");continue}else if(l==="%"){if(!a(o,r,n))break;a=ql}else{o.push(l);continue}}return o.length&&(a===ql?n.zone=o.join(""):s?r.push(o.join("")):r.push(cs(o))),n.address=r.join(""),n}function Gl(t){if(sy(t,":")<2)return{host:t,isIPV6:!1};let e=iy(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function sy(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ay(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}function cy(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function ly(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Hl(n)){let r=Gl(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Vl.exports={nonSimpleDomain:ry,recomposeAuthority:ly,normalizeComponentEncoding:cy,removeDotSegments:ay,isIPv4:Hl,isUUID:ny,normalizeIPv6:Gl,stringArrayToHexStripped:cs}});var Yl=_((gR,Jl)=>{"use strict";var{isUUID:uy}=ls(),dy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fy=["http","https","ws","wss","urn","urn:uuid"];function my(t){return fy.indexOf(t)!==-1}function us(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Wl(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function zl(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function py(t){return t.secure=us(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function hy(t){if((t.port===(us(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function gy(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(dy);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,i=ds(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function yy(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,i=ds(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${r||e.nid}:${a}`,e.skipEscape=!0,s}function _y(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!uy(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function wy(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Kl={scheme:"http",domainHost:!0,parse:Wl,serialize:zl},vy={scheme:"https",domainHost:Kl.domainHost,parse:Wl,serialize:zl},bo={scheme:"ws",domainHost:!0,parse:py,serialize:hy},by={scheme:"wss",domainHost:bo.domainHost,parse:bo.parse,serialize:bo.serialize},Sy={scheme:"urn",parse:gy,serialize:yy,skipNormalize:!0},Ey={scheme:"urn:uuid",parse:_y,serialize:wy,skipNormalize:!0},So={http:Kl,https:vy,ws:bo,wss:by,urn:Sy,"urn:uuid":Ey};Object.setPrototypeOf(So,null);function ds(t){return t&&(So[t]||So[t.toLowerCase()])||void 0}Jl.exports={wsIsSecure:us,SCHEMES:So,isValidSchemeName:my,getSchemeHandler:ds}});var Zl=_((yR,ko)=>{"use strict";var{normalizeIPv6:ky,removeDotSegments:br,recomposeAuthority:$y,normalizeComponentEncoding:Eo,isIPv4:Ry,nonSimpleDomain:Py}=ls(),{SCHEMES:Ay,getSchemeHandler:Ql}=Yl();function Ty(t,e){return typeof t=="string"?t=Xe(mt(t,e),e):typeof t=="object"&&(t=mt(Xe(t,e),e)),t}function xy(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Xl(mt(t,r),mt(e,r),r,!0);return r.skipEscape=!0,Xe(o,r)}function Xl(t,e,n,r){let o={};return r||(t=mt(Xe(t,n),n),e=mt(Xe(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=br(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=br(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=br(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Cy(t,e,n){return typeof t=="string"?(t=unescape(t),t=Xe(Eo(mt(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=Xe(Eo(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Xe(Eo(mt(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=Xe(Eo(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Xe(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],i=Ql(r.scheme||n.scheme);i&&i.serialize&&i.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let s=$y(n);if(s!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(s),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!i||!i.absolutePath)&&(a=br(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var Iy=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mt(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(Iy);if(i){if(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5]),r.host)if(Ry(r.host)===!1){let c=ky(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let s=Ql(n.scheme||r.scheme);if(!n.unicodeSupport&&(!s||!s.unicodeSupport)&&r.host&&(n.domainHost||s&&s.domainHost)&&o===!1&&Py(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!s||s&&!s.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),s&&s.parse&&s.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var fs={SCHEMES:Ay,normalize:Ty,resolve:xy,resolveComponent:Xl,equal:Cy,serialize:Xe,parse:mt};ko.exports=fs;ko.exports.default=fs;ko.exports.fastUri=fs});var tu=_(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var eu=Zl();eu.code='require("ajv/dist/runtime/uri").default';ms.default=eu});var lu=_(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.CodeGen=ce.Name=ce.nil=ce.stringify=ce.str=ce._=ce.KeywordCxt=void 0;var Oy=wr();Object.defineProperty(ce,"KeywordCxt",{enumerable:!0,get:function(){return Oy.KeywordCxt}});var An=T();Object.defineProperty(ce,"_",{enumerable:!0,get:function(){return An._}});Object.defineProperty(ce,"str",{enumerable:!0,get:function(){return An.str}});Object.defineProperty(ce,"stringify",{enumerable:!0,get:function(){return An.stringify}});Object.defineProperty(ce,"nil",{enumerable:!0,get:function(){return An.nil}});Object.defineProperty(ce,"Name",{enumerable:!0,get:function(){return An.Name}});Object.defineProperty(ce,"CodeGen",{enumerable:!0,get:function(){return An.CodeGen}});var Ny=_o(),su=vr(),Ly=qi(),Sr=vo(),My=T(),Er=gr(),$o=hr(),hs=L(),nu=Ul(),jy=tu(),au=(t,e)=>new RegExp(t,e);au.code="new RegExp";var Dy=["removeAdditional","useDefaults","coerceTypes"],Fy=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),By={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."},Uy={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ru=200;function qy(t){var e,n,r,o,i,s,a,c,l,u,d,h,p,f,m,g,y,v,S,R,$,K,X,ae,Ke;let st=t.strict,nr=(e=t.code)===null||e===void 0?void 0:e.optimize,Je=nr===!0||nr===void 0?1:nr||0,re=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:au,Ut=(o=t.uriResolver)!==null&&o!==void 0?o:jy.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:st)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:st)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:st)!==null&&u!==void 0?u:"log",strictTuples:(h=(d=t.strictTuples)!==null&&d!==void 0?d:st)!==null&&h!==void 0?h:"log",strictRequired:(f=(p=t.strictRequired)!==null&&p!==void 0?p:st)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:Je,regExp:re}:{optimize:Je,regExp:re},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:ru,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:ru,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=t.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:($=t.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(K=t.validateSchema)!==null&&K!==void 0?K:!0,validateFormats:(X=t.validateFormats)!==null&&X!==void 0?X:!0,unicodeRegExp:(ae=t.unicodeRegExp)!==null&&ae!==void 0?ae:!0,int32range:(Ke=t.int32range)!==null&&Ke!==void 0?Ke:!0,uriResolver:Ut}}var kr=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...qy(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new My.ValueScope({scope:{},prefixes:Fy,es5:n,lines:r}),this.logger=Ky(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Ly.getRules)(),ou.call(this,By,e,"NOT SUPPORTED"),ou.call(this,Uy,e,"DEPRECATED","warn"),this._metaOpts=Wy.call(this),e.formats&&Gy.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Vy.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Hy.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=nu;r==="id"&&(o={...nu},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);async function o(u,d){await i.call(this,u.$schema);let h=this._addSchema(u,d);return h.validate||s.call(this,h)}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 su.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,n)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return n=(0,Er.normalizeId)(n||i),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let n;for(;typeof(n=iu.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new Sr.SchemaEnv({schema:{},schemaId:r});if(n=Sr.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=iu.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Er.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Yy.call(this,r,n),!n)return(0,hs.eachItem)(r,i=>ps.call(this,i)),this;Xy.call(this,n);let o={...n,type:(0,$o.getJSONTypes)(n.type),schemaType:(0,$o.getJSONTypes)(n.schemaType)};return(0,hs.eachItem)(r,o.type.length===0?i=>ps.call(this,i,o):i=>o.type.forEach(s=>ps.call(this,i,o,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(i=>i.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,i)=>o+n+i)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=s[a];l&&u&&(s[a]=cu(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;r=(0,Er.normalizeId)(s||r);let l=Er.getSchemaRefs.call(this,e,r);return c=new Sr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:l}),this._cache.set(c.schema,c),i&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Sr.compileSchema.call(this,e)}finally{this.opts=n}}};kr.ValidationError=Ny.default;kr.MissingRefError=su.default;ce.default=kr;function ou(t,e,n,r="error"){for(let o in t){let i=o;i in e&&this.logger[r](`${n}: option ${o}. ${t[i]}`)}}function iu(t){return t=(0,Er.normalizeId)(t),this.schemas[t]||this.refs[t]}function Hy(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Gy(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Vy(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function Wy(){let t={...this.opts};for(let e of Dy)delete t[e];return t}var zy={log(){},warn(){},error(){}};function Ky(t){if(t===!1)return zy;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Jy=/^[a-z_$][a-z0-9_$:-]*$/i;function Yy(t,e){let{RULES:n}=this;if((0,hs.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!Jy.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function ps(t,e,n){var r;let o=e?.post;if(n&&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===n);if(s||(s={type:n,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,$o.getJSONTypes)(e.type),schemaType:(0,$o.getJSONTypes)(e.schemaType)}};e.before?Qy.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function Qy(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Xy(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=cu(e)),t.validateSchema=this.compile(e,!0))}var Zy={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function cu(t){return{anyOf:[t,Zy]}}});var uu=_(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var e_={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gs.default=e_});var pu=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.callRef=Yt.getValidate=void 0;var t_=vr(),du=Ie(),Se=T(),Tn=dt(),fu=vo(),Ro=L(),n_={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=r,{root:l}=i;if((n==="#"||n==="#/")&&o===l.baseId)return d();let u=fu.resolveRef.call(c,l,o,n);if(u===void 0)throw new t_.default(r.opts.uriResolver,o,n);if(u instanceof fu.SchemaEnv)return h(u);return p(u);function d(){if(i===l)return Po(t,s,i,i.$async);let f=e.scopeValue("root",{ref:l});return Po(t,(0,Se._)`${f}.validate`,l,l.$async)}function h(f){let m=mu(t,f);Po(t,m,f,f.$async)}function p(f){let m=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Se.stringify)(f)}:{ref:f}),g=e.name("valid"),y=t.subschema({schema:f,dataTypes:[],schemaPath:Se.nil,topSchemaRef:m,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function mu(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Se._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Yt.getValidate=mu;function Po(t,e,n,r){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,l=c.passContext?Tn.default.this:Se.nil;r?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Se._)`await ${(0,du.callValidateCode)(t,e,l)}`),p(e),s||o.assign(f,!0)},m=>{o.if((0,Se._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),h(m),s||o.assign(f,!1)}),t.ok(f)}function d(){t.result((0,du.callValidateCode)(t,e,l),()=>p(e),()=>h(e))}function h(f){let m=(0,Se._)`${f}.errors`;o.assign(Tn.default.vErrors,(0,Se._)`${Tn.default.vErrors} === null ? ${m} : ${Tn.default.vErrors}.concat(${m})`),o.assign(Tn.default.errors,(0,Se._)`${Tn.default.vErrors}.length`)}function p(f){var m;if(!i.opts.unevaluated)return;let g=(m=n?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=Ro.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Se._)`${f}.evaluated.props`);i.props=Ro.mergeEvaluated.props(o,y,i.props,Se.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Ro.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Se._)`${f}.evaluated.items`);i.items=Ro.mergeEvaluated.items(o,y,i.items,Se.Name)}}}Yt.callRef=Po;Yt.default=n_});var hu=_(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var r_=uu(),o_=pu(),i_=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",r_.default,o_.default];ys.default=i_});var gu=_(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var Ao=T(),xt=Ao.operators,To={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}},s_={message:({keyword:t,schemaCode:e})=>(0,Ao.str)`must be ${To[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ao._)`{comparison: ${To[t].okStr}, limit: ${e}}`},a_={keyword:Object.keys(To),type:"number",schemaType:"number",$data:!0,error:s_,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Ao._)`${n} ${To[e].fail} ${r} || isNaN(${n})`)}};_s.default=a_});var yu=_(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var $r=T(),c_={message:({schemaCode:t})=>(0,$r.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,$r._)`{multipleOf: ${t}}`},l_={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:c_,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,$r._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,$r._)`${s} !== parseInt(${s})`;t.fail$data((0,$r._)`(${r} === 0 || (${s} = ${n}/${r}, ${a}))`)}};ws.default=l_});var wu=_(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});function _u(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}vs.default=_u;_u.code='require("ajv/dist/runtime/ucs2length").default'});var vu=_(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Qt=T(),u_=L(),d_=wu(),f_={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Qt.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Qt._)`{limit: ${t}}`},m_={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:f_,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,i=e==="maxLength"?Qt.operators.GT:Qt.operators.LT,s=o.opts.unicode===!1?(0,Qt._)`${n}.length`:(0,Qt._)`${(0,u_.useFunc)(t.gen,d_.default)}(${n})`;t.fail$data((0,Qt._)`${s} ${i} ${r}`)}};bs.default=m_});var bu=_(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var p_=Ie(),h_=L(),xn=T(),g_={message:({schemaCode:t})=>(0,xn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,xn._)`{pattern: ${t}}`},y_={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:g_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=s.opts.code,l=c.code==="new RegExp"?(0,xn._)`new RegExp`:(0,h_.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,xn._)`${l}(${i}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,xn._)`!${u}`)}else{let c=(0,p_.usePattern)(t,o);t.fail$data((0,xn._)`!${c}.test(${n})`)}}};Ss.default=y_});var Su=_(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Rr=T(),__={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Rr.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Rr._)`{limit: ${t}}`},w_={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:__,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Rr.operators.GT:Rr.operators.LT;t.fail$data((0,Rr._)`Object.keys(${n}).length ${o} ${r}`)}};Es.default=w_});var Eu=_(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Pr=Ie(),Ar=T(),v_=L(),b_={message:({params:{missingProperty:t}})=>(0,Ar.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ar._)`{missingProperty: ${t}}`},S_={keyword:"required",type:"object",schemaType:"array",$data:!0,error:b_,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&n.length===0)return;let c=n.length>=a.loopRequired;if(s.allErrors?l():u(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:f}=t.it;for(let m of n)if(p?.[m]===void 0&&!f.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,v_.checkStrictMode)(s,y,s.opts.strictRequired)}}function l(){if(c||i)t.block$data(Ar.nil,d);else for(let p of n)(0,Pr.checkReportMissingProp)(t,p)}function u(){let p=e.let("missing");if(c||i){let f=e.let("valid",!0);t.block$data(f,()=>h(p,f)),t.ok(f)}else e.if((0,Pr.checkMissingProp)(t,n,p)),(0,Pr.reportMissingProp)(t,p),e.else()}function d(){e.forOf("prop",r,p=>{t.setParams({missingProperty:p}),e.if((0,Pr.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function h(p,f){t.setParams({missingProperty:p}),e.forOf(p,r,()=>{e.assign(f,(0,Pr.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Ar.not)(f),()=>{t.error(),e.break()})},Ar.nil)}}};ks.default=S_});var ku=_($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var Tr=T(),E_={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Tr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Tr._)`{limit: ${t}}`},k_={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:E_,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Tr.operators.GT:Tr.operators.LT;t.fail$data((0,Tr._)`${n}.length ${o} ${r}`)}};$s.default=k_});var xo=_(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var $u=Yi();$u.code='require("ajv/dist/runtime/equal").default';Rs.default=$u});var Ru=_(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Ps=hr(),le=T(),$_=L(),R_=xo(),P_={message:({params:{i:t,j:e}})=>(0,le.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,le._)`{i: ${t}, j: ${e}}`},A_={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:P_,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),l=i.items?(0,Ps.getSchemaTypes)(i.items):[];t.block$data(c,u,(0,le._)`${s} === false`),t.ok(c);function u(){let f=e.let("i",(0,le._)`${n}.length`),m=e.let("j");t.setParams({i:f,j:m}),e.assign(c,!0),e.if((0,le._)`${f} > 1`,()=>(d()?h:p)(f,m))}function d(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function h(f,m){let g=e.name("item"),y=(0,Ps.checkDataTypes)(l,g,a.opts.strictNumbers,Ps.DataType.Wrong),v=e.const("indices",(0,le._)`{}`);e.for((0,le._)`;${f}--;`,()=>{e.let(g,(0,le._)`${n}[${f}]`),e.if(y,(0,le._)`continue`),l.length>1&&e.if((0,le._)`typeof ${g} == "string"`,(0,le._)`${g} += "_"`),e.if((0,le._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(m,(0,le._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,le._)`${v}[${g}] = ${f}`)})}function p(f,m){let g=(0,$_.useFunc)(e,R_.default),y=e.name("outer");e.label(y).for((0,le._)`;${f}--;`,()=>e.for((0,le._)`${m} = ${f}; ${m}--;`,()=>e.if((0,le._)`${g}(${n}[${f}], ${n}[${m}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};As.default=A_});var Pu=_(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var Ts=T(),T_=L(),x_=xo(),C_={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ts._)`{allowedValue: ${t}}`},I_={keyword:"const",$data:!0,error:C_,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:i}=t;r||i&&typeof i=="object"?t.fail$data((0,Ts._)`!${(0,T_.useFunc)(e,x_.default)}(${n}, ${o})`):t.fail((0,Ts._)`${i} !== ${n}`)}};xs.default=I_});var Au=_(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var xr=T(),O_=L(),N_=xo(),L_={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xr._)`{allowedValues: ${t}}`},M_={keyword:"enum",schemaType:"array",$data:!0,error:L_,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:i,it:s}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,l=()=>c??(c=(0,O_.useFunc)(e,N_.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,xr.or)(...o.map((f,m)=>h(p,m)))}t.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,xr._)`${l()}(${n}, ${p})`,()=>e.assign(u,!0).break()))}function h(p,f){let m=o[f];return typeof m=="object"&&m!==null?(0,xr._)`${l()}(${n}, ${p}[${f}])`:(0,xr._)`${n} === ${m}`}}};Cs.default=M_});var Tu=_(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var j_=gu(),D_=yu(),F_=vu(),B_=bu(),U_=Su(),q_=Eu(),H_=ku(),G_=Ru(),V_=Pu(),W_=Au(),z_=[j_.default,D_.default,F_.default,B_.default,U_.default,q_.default,H_.default,G_.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},V_.default,W_.default];Is.default=z_});var Ns=_(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.validateAdditionalItems=void 0;var Xt=T(),Os=L(),K_={message:({params:{len:t}})=>(0,Xt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xt._)`{limit: ${t}}`},J_={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:K_,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Os.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}xu(t,r)}};function xu(t,e){let{gen:n,schema:r,data:o,keyword:i,it:s}=t;s.items=!0;let a=n.const("len",(0,Xt._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xt._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Os.alwaysValidSchema)(s,r)){let l=n.var("valid",(0,Xt._)`${a} <= ${e.length}`);n.if((0,Xt.not)(l),()=>c(l)),t.ok(l)}function c(l){n.forRange("i",e.length,a,u=>{t.subschema({keyword:i,dataProp:u,dataPropType:Os.Type.Num},l),s.allErrors||n.if((0,Xt.not)(l),()=>n.break())})}}Cr.validateAdditionalItems=xu;Cr.default=J_});var Ls=_(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateTuple=void 0;var Cu=T(),Co=L(),Y_=Ie(),Q_={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Iu(t,"additionalItems",e);n.items=!0,!(0,Co.alwaysValidSchema)(n,e)&&t.ok((0,Y_.validateArray)(t))}};function Iu(t,e,n=t.schema){let{gen:r,parentSchema:o,data:i,keyword:s,it:a}=t;u(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Co.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),l=r.const("len",(0,Cu._)`${i}.length`);n.forEach((d,h)=>{(0,Co.alwaysValidSchema)(a,d)||(r.if((0,Cu._)`${l} > ${h}`,()=>t.subschema({keyword:s,schemaProp:h,dataProp:h},c)),t.ok(c))});function u(d){let{opts:h,errSchemaPath:p}=a,f=n.length,m=f===d.minItems&&(f===d.maxItems||d[e]===!1);if(h.strictTuples&&!m){let g=`"${s}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Co.checkStrictMode)(a,g,h.strictTuples)}}}Ir.validateTuple=Iu;Ir.default=Q_});var Ou=_(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var X_=Ls(),Z_={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,X_.validateTuple)(t,"items")};Ms.default=Z_});var Lu=_(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Nu=T(),ew=L(),tw=Ie(),nw=Ns(),rw={message:({params:{len:t}})=>(0,Nu.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nu._)`{limit: ${t}}`},ow={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rw,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,ew.alwaysValidSchema)(r,e)&&(o?(0,nw.validateAdditionalItems)(t,o):t.ok((0,tw.validateArray)(t)))}};js.default=ow});var Mu=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Ne=T(),Io=L(),iw={message:({params:{min:t,max:e}})=>e===void 0?(0,Ne.str)`must contain at least ${t} valid item(s)`:(0,Ne.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ne._)`{minContains: ${t}}`:(0,Ne._)`{minContains: ${t}, maxContains: ${e}}`},sw={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t,s,a,{minContains:c,maxContains:l}=r;i.opts.next?(s=c===void 0?1:c,a=l):s=1;let u=e.const("len",(0,Ne._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Io.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Io.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Io.alwaysValidSchema)(i,n)){let m=(0,Ne._)`${u} >= ${s}`;a!==void 0&&(m=(0,Ne._)`${m} && ${u} <= ${a}`),t.pass(m);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?p(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Ne._)`${o}.length > 0`,h)):(e.let(d,!1),h()),t.result(d,()=>t.reset());function h(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>f(g)))}function p(m,g){e.forRange("i",0,u,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Io.Type.Num,compositeRule:!0},m),g()})}function f(m){e.code((0,Ne._)`${m}++`),a===void 0?e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Ne._)`${m} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Ne._)`${m} >= ${s}`,()=>e.assign(d,!0)))}}};Ds.default=sw});var Fu=_(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateSchemaDeps=Ze.validatePropertyDeps=Ze.error=void 0;var Fs=T(),aw=L(),Or=Ie();Ze.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Fs.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Fs._)`{property: ${t},
|
|
8
8
|
missingProperty: ${r},
|
|
9
9
|
depsCount: ${e},
|
|
10
|
-
deps: ${n}}`};var tw={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(t){let[e,n]=nw(t);Nu(t,e),Mu(t,n)}};function nw({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Nu(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Or.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,Or.checkReportMissingProp)(t,l)}):(n.if((0,js._)`${c} && (${(0,Or.checkMissingProp)(t,a,i)})`),(0,Or.reportMissingProp)(t,i),n.else())}}Xe.validatePropertyDeps=Nu;function Mu(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,ew.alwaysValidSchema)(i,e[a])||(n.if((0,Or.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Xe.validateSchemaDeps=Mu;Xe.default=tw});var Du=_(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var ju=A(),rw=M(),ow={message:"property name must be valid",params:({params:t})=>(0,ju._)`{propertyName: ${t.propertyName}}`},iw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:ow,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,rw.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,ju.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Ds.default=iw});var Bs=_(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Io=Ie(),Be=A(),sw=ut(),Oo=M(),aw={message:"must NOT have additional properties",params:({params:t})=>(0,Be._)`{additionalProperty: ${t.additionalProperty}}`},cw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Oo.alwaysValidSchema)(s,n))return;let l=(0,Io.allSchemaProperties)(r.properties),u=(0,Io.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Be._)`${i} === ${sw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(l.length>8){let v=(0,Oo.schemaRefOrVal)(s,r.properties,"properties");y=(0,Io.isOwnProperty)(e,v,g)}else l.length?y=(0,Be.or)(...l.map(v=>(0,Be._)`${g} === ${v}`)):y=Be.nil;return u.length&&(y=(0,Be.or)(y,...u.map(v=>(0,Be._)`${(0,Io.usePattern)(t,v)}.test(${g})`))),(0,Be.not)(y)}function p(g){e.code((0,Be._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){p(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Oo.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Be.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Be.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Oo.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Fs.default=cw});var qu=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var lw=wr(),Fu=Ie(),qs=M(),Bu=Bs(),uw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Bu.default.code(new lw.KeywordCxt(i,Bu.default,"additionalProperties"));let s=(0,Fu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=qs.mergeEvaluated.props(e,(0,qs.toHash)(s),i.props));let a=s.filter(d=>!(0,qs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Fu.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Us.default=uw});var Wu=_(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var Uu=Ie(),No=A(),Hu=M(),Gu=M(),dw={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,Uu.allSchemaProperties)(n),c=a.filter(m=>(0,Hu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof No.Name)&&(i.props=(0,Gu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)l&&p(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,Hu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,No._)`${(0,Uu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:Gu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,No._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,No.not)(u),()=>e.break())})})}}};Hs.default=dw});var Vu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var fw=M(),mw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,fw.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Gs.default=mw});var zu=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var pw=Ie(),hw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pw.validateUnion,error:{message:"must match a schema in anyOf"}};Ws.default=hw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Mo=A(),gw=M(),yw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},_w={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:yw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let h;(0,gw.alwaysValidSchema)(o,u)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Mo.Name)})})}}};Vs.default=_w});var Ju=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var ww=M(),vw={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,ww.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};zs.default=vw});var Xu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Lo=A(),Qu=M(),bw={message:({params:t})=>(0,Lo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Lo._)`{failingKeyword: ${t.ifClause}}`},Sw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Qu.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Yu(r,"then"),i=Yu(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Lo.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,Lo._)`${u}`):t.setParams({ifClause:u})}}}};function Yu(t,e){let n=t.schema[e];return n!==void 0&&!(0,Qu.alwaysValidSchema)(t,n)}Ks.default=Sw});var Zu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Ew=M(),kw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,Ew.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Js.default=kw});var ed=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var $w=Is(),Rw=Cu(),Pw=Os(),Tw=Iu(),Aw=Ou(),Cw=Lu(),xw=Du(),Iw=Bs(),Ow=qu(),Nw=Wu(),Mw=Vu(),Lw=zu(),jw=Ku(),Dw=Ju(),Fw=Xu(),Bw=Zu();function qw(t=!1){let e=[Mw.default,Lw.default,jw.default,Dw.default,Fw.default,Bw.default,xw.default,Iw.default,Cw.default,Ow.default,Nw.default];return t?e.push(Rw.default,Tw.default):e.push($w.default,Pw.default),e.push(Aw.default),e}Ys.default=qw});var td=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Y=A(),Uw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Hw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Uw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?h():p();function h(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,$=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S($){let z=$ instanceof RegExp?(0,Y.regexpCode)($):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,Q=n.scopeValue("formats",{key:i,ref:$,code:z});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Y._)`${Q}.validate`]:["string",$,Q]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Qs.default=Hw});var nd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Gw=td(),Ww=[Gw.default];Xs.default=Ww});var rd=_(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.contentVocabulary=xn.metadataVocabulary=void 0;xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var id=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Vw=fu(),zw=Ru(),Kw=ed(),Jw=nd(),od=rd(),Yw=[Vw.default,zw.default,(0,Kw.default)(),Jw.default,od.metadataVocabulary,od.contentVocabulary];Zs.default=Yw});var ad=_(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.DiscrError=void 0;var sd;(function(t){t.Tag="tag",t.Mapping="mapping"})(sd||(jo.DiscrError=sd={}))});var ld=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var In=A(),ea=ad(),cd=wo(),Qw=vr(),Xw=M(),Zw={message:({params:{discrError:t,tagName:e}})=>t===ea.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,In._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},ev={keyword:"discriminator",type:"object",schemaType:"object",error:Zw,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,In._)`${n}${(0,In.getProperty)(a)}`);e.if((0,In._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:ea.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,In._)`${l} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:ea.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(m,In.Name),f}function h(){var p;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let $=s[R];if($?.$ref&&!(0,Xw.schemaHasRulesButRef)($,i.self.RULES)){let Q=$.$ref;if($=cd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Q),$ instanceof cd.SchemaEnv&&($=$.schema),$===void 0)throw new Qw.default(i.opts.uriResolver,i.baseId,Q)}let z=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(z,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,$){if(R.const)S(R.const,$);else if(R.enum)for(let z of R.enum)S(z,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,$){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=$}}}};ta.default=ev});var ud=_((DR,tv)=>{tv.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 Fo=_((G,na)=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.MissingRefError=G.ValidationError=G.CodeGen=G.Name=G.nil=G.stringify=G.str=G._=G.KeywordCxt=G.Ajv=void 0;var nv=su(),rv=id(),ov=ld(),dd=ud(),iv=["/properties"],Do="http://json-schema.org/draft-07/schema",On=class extends nv.default{_addVocabularies(){super._addVocabularies(),rv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ov.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dd,iv):dd;this.addMetaSchema(e,Do,!1),this.refs["http://json-schema.org/schema"]=Do}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Do)?Do:void 0)}};G.Ajv=On;na.exports=G=On;na.exports.Ajv=On;Object.defineProperty(G,"__esModule",{value:!0});G.default=On;var sv=wr();Object.defineProperty(G,"KeywordCxt",{enumerable:!0,get:function(){return sv.KeywordCxt}});var Nn=A();Object.defineProperty(G,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(G,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(G,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(G,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(G,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(G,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var av=yo();Object.defineProperty(G,"ValidationError",{enumerable:!0,get:function(){return av.default}});var cv=vr();Object.defineProperty(G,"MissingRefError",{enumerable:!0,get:function(){return cv.default}})});var wd=_(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(t,e){return{validate:t,compare:e}}et.fullFormats={date:Ze(hd,sa),time:Ze(oa(!0),aa),"date-time":Ze(fd(!0),yd),"iso-time":Ze(oa(),gd),"iso-date-time":Ze(fd(),_d),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pv,"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:bv,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:hv,int32:{type:"number",validate:_v},int64:{type:"number",validate:wv},float:{type:"number",validate:pd},double:{type:"number",validate:pd},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sa),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aa),"date-time":Ze(/^\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,yd),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gd),"iso-date-time":Ze(/^\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,_d),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};et.formatNames=Object.keys(et.fullFormats);function lv(t){return t%4===0&&(t%100!==0||t%400===0)}var uv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dv=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hd(t){let e=uv.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&lv(n)?29:dv[r])}function sa(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ra=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function oa(t){return function(n){let r=ra.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,h=o-l*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function aa(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function gd(t,e){if(!(t&&e))return;let n=ra.exec(t),r=ra.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var ia=/t|\s/i;function fd(t){let e=oa(t);return function(r){let o=r.split(ia);return o.length===2&&hd(o[0])&&e(o[1])}}function yd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function _d(t,e){if(!(t&&e))return;let[n,r]=t.split(ia),[o,i]=e.split(ia),s=sa(n,o);if(s!==void 0)return s||aa(r,i)}var fv=/\/|:/,mv=/^(?:[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 pv(t){return fv.test(t)&&mv.test(t)}var md=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function hv(t){return md.lastIndex=0,md.test(t)}var gv=-(2**31),yv=2**31-1;function _v(t){return Number.isInteger(t)&&t<=yv&&t>=gv}function wv(t){return Number.isInteger(t)}function pd(){return!0}var vv=/[^\\]\\Z/;function bv(t){if(vv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var vd=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.formatLimitDefinition=void 0;var Sv=Fo(),qe=A(),At=qe.operators,Bo={formatMaximum:{okStr:"<=",ok:At.LTE,fail:At.GT},formatMinimum:{okStr:">=",ok:At.GTE,fail:At.LT},formatExclusiveMaximum:{okStr:"<",ok:At.LT,fail:At.GTE},formatExclusiveMinimum:{okStr:">",ok:At.GT,fail:At.LTE}},Ev={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Bo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Bo[t].okStr}, limit: ${e}}`};Mn.formatLimitDefinition={keyword:Object.keys(Bo),type:"string",schemaType:"string",$data:!0,error:Ev,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Sv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let h=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,qe._)`${h}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${p} != "object"`,(0,qe._)`${p} instanceof RegExp`,(0,qe._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=c.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${h}" does not define "compare" function`);let f=e.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,qe._)`${s.code.formats}${(0,qe.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,qe._)`${h}.compare(${n}, ${r}) ${Bo[o].fail} 0`}},dependencies:["format"]};var kv=t=>(t.addKeyword(Mn.formatLimitDefinition),t);Mn.default=kv});var ua=_((Nr,Ed)=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});var Ln=wd(),$v=vd(),ca=A(),bd=new ca.Name("fullFormats"),Rv=new ca.Name("fastFormats"),la=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sd(t,e,Ln.fullFormats,bd),t;let[n,r]=e.mode==="fast"?[Ln.fastFormats,Rv]:[Ln.fullFormats,bd],o=e.formats||Ln.formatNames;return Sd(t,o,n,r),e.keywords&&(0,$v.default)(t),t};la.get=(t,e="full")=>{let r=(e==="fast"?Ln.fastFormats:Ln.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Sd(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ca._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Ed.exports=Nr=la;Object.defineProperty(Nr,"__esModule",{value:!0});Nr.default=la});var pt=_((aP,Id)=>{"use strict";var Cd=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Cd.push("blob");Id.exports={BINARY_TYPES:Cd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Mr=_((cP,qo)=>{"use strict";var{EMPTY_BUFFER:Dv}=pt(),fa=Buffer[Symbol.species];function Fv(t,e){if(t.length===0)return Dv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new fa(n.buffer,n.byteOffset,r):n}function Od(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function Nd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Bv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ma(t){if(ma.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new fa(t):ArrayBuffer.isView(t)?e=new fa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ma.readOnly=!1),e}qo.exports={concat:Fv,mask:Od,toArrayBuffer:Bv,toBuffer:ma,unmask:Nd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Od(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?Nd(e,n):t.unmask(e,n)}}catch{}});var jd=_((lP,Ld)=>{"use strict";var Md=Symbol("kDone"),pa=Symbol("kRun"),ha=class{constructor(e){this[Md]=()=>{this.pending--,this[pa]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[pa]()}[pa](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Md])}}};Ld.exports=ha});var qn=_((uP,qd)=>{"use strict";var Lr=Z("zlib"),Dd=Mr(),qv=jd(),{kStatusCode:Fd}=pt(),Uv=Buffer[Symbol.species],Hv=Buffer.from([0,0,255,255]),Ho=Symbol("permessage-deflate"),ht=Symbol("total-length"),Fn=Symbol("callback"),Ct=Symbol("buffers"),Bn=Symbol("error"),Uo,ga=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Uo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Uo=new qv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Fn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Uo.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Uo.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Lr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Ho]=this,this._inflate[ht]=0,this._inflate[Ct]=[],this._inflate.on("error",Wv),this._inflate.on("data",Bd)}this._inflate[Fn]=r,this._inflate.write(e),n&&this._inflate.write(Hv),this._inflate.flush(()=>{let i=this._inflate[Bn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Dd.concat(this._inflate[Ct],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Lr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Lr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[ht]=0,this._deflate[Ct]=[],this._deflate.on("data",Gv)}this._deflate[Fn]=r,this._deflate.write(e),this._deflate.flush(Lr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Dd.concat(this._deflate[Ct],this._deflate[ht]);n&&(i=new Uv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Fn]=null,this._deflate[ht]=0,this._deflate[Ct]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};qd.exports=ga;function Gv(t){this[Ct].push(t),this[ht]+=t.length}function Bd(t){if(this[ht]+=t.length,this[Ho]._maxPayload<1||this[ht]<=this[Ho]._maxPayload){this[Ct].push(t);return}this[Bn]=new RangeError("Max payload size exceeded"),this[Bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bn][Fd]=1009,this.removeListener("data",Bd),this.reset()}function Wv(t){if(this[Ho]._inflate=null,this[Bn]){this[Fn](this[Bn]);return}t[Fd]=1007,this[Fn](t)}});var Un=_((dP,Go)=>{"use strict";var{isUtf8:Ud}=Z("buffer"),{hasBlob:Vv}=pt(),zv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Kv(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ya(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function Jv(t){return Vv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Go.exports={isBlob:Jv,isValidStatusCode:Kv,isValidUTF8:ya,tokenChars:zv};if(Ud)Go.exports.isValidUTF8=function(t){return t.length<24?ya(t):Ud(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Go.exports.isValidUTF8=function(e){return e.length<32?ya(e):t(e)}}catch{}});var Sa=_((fP,Jd)=>{"use strict";var{Writable:Yv}=Z("stream"),Hd=qn(),{BINARY_TYPES:Qv,EMPTY_BUFFER:Gd,kStatusCode:Xv,kWebSocket:Zv}=pt(),{concat:_a,toArrayBuffer:eb,unmask:tb}=Mr(),{isValidStatusCode:nb,isValidUTF8:Wd}=Un(),Wo=Buffer[Symbol.species],Me=0,Vd=1,zd=2,Kd=3,wa=4,va=5,Vo=6,ba=class extends Yv{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Qv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Zv]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Me}_write(e,n,r){if(this._opcode===8&&this._state==Me)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e),new Wo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Me:this.getInfo(e);break;case Vd:this.getPayloadLength16(e);break;case zd:this.getPayloadLength64(e);break;case Kd:this.getMask();break;case wa:this.getData(e);break;case va:case Vo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Hd.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Vd:this._payloadLength===127?this._state=zd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Kd:this._state=wa}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wa}getData(e){let n=Gd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&tb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=va,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Hd.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Me&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Me;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=_a(r,n):this._binaryType==="arraybuffer"?o=eb(_a(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!0),this._state=Me,this.startLoop(e)}))}else{let o=_a(r,n);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===va||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit("message",o,!1),this._state=Me,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gd),this.end();else{let r=e.readUInt16BE(0);if(!nb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Me;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Me):(this._state=Vo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Me,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[Xv]=o,s}};Jd.exports=ba});var $a=_((pP,Xd)=>{"use strict";var{Duplex:mP}=Z("stream"),{randomFillSync:rb}=Z("crypto"),Yd=qn(),{EMPTY_BUFFER:ob,kWebSocket:ib,NOOP:sb}=pt(),{isBlob:Hn,isValidStatusCode:ab}=Un(),{mask:Qd,toBuffer:tn}=Mr(),Le=Symbol("kByteLength"),cb=Buffer.alloc(4),zo=8*1024,nn,Gn=zo,Ue=0,lb=1,ub=2,Ea=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ue,this.onerror=sb,this[ib]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||cb,n.generateMask?n.generateMask(r):(Gn===zo&&(nn===void 0&&(nn=Buffer.alloc(zo)),rb(nn,0,zo),Gn=0),r[0]=nn[Gn++],r[1]=nn[Gn++],r[2]=nn[Gn++],r[3]=nn[Gn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Le]!==void 0?a=n[Le]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(Qd(e,r,l,i,a),[l]):(Qd(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=ob;else{if(typeof e!="number"||!ab(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Le]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ue?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=tn(e),o=e.length,i=tn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Le]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Ue?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Yd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Hn(e)?(a=e.size,c=!1):(e=tn(e),a=e.length,c=tn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Le]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Hn(e)?this._state!==Ue?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ue?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Le],this._state=ub,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ka,this,a,o);return}this._bufferedBytes-=r[Le];let s=tn(i);n?this.dispatch(s,n,r,o):(this._state=Ue,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(db,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Yd.extensionName];this._bufferedBytes+=r[Le],this._state=lb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ka(this,c,o);return}this._bufferedBytes-=r[Le],this._state=Ue,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===Ue&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Le],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Xd.exports=Ea;function ka(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function db(t,e,n){ka(t,e,n),t.onerror(e)}});var cf=_((hP,af)=>{"use strict";var{kForOnEventAttribute:jr,kListener:Ra}=pt(),Zd=Symbol("kCode"),ef=Symbol("kData"),tf=Symbol("kError"),nf=Symbol("kMessage"),rf=Symbol("kReason"),Wn=Symbol("kTarget"),of=Symbol("kType"),sf=Symbol("kWasClean"),gt=class{constructor(e){this[Wn]=null,this[of]=e}get target(){return this[Wn]}get type(){return this[of]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var rn=class extends gt{constructor(e,n={}){super(e),this[Zd]=n.code===void 0?0:n.code,this[rf]=n.reason===void 0?"":n.reason,this[sf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Zd]}get reason(){return this[rf]}get wasClean(){return this[sf]}};Object.defineProperty(rn.prototype,"code",{enumerable:!0});Object.defineProperty(rn.prototype,"reason",{enumerable:!0});Object.defineProperty(rn.prototype,"wasClean",{enumerable:!0});var Vn=class extends gt{constructor(e,n={}){super(e),this[tf]=n.error===void 0?null:n.error,this[nf]=n.message===void 0?"":n.message}get error(){return this[tf]}get message(){return this[nf]}};Object.defineProperty(Vn.prototype,"error",{enumerable:!0});Object.defineProperty(Vn.prototype,"message",{enumerable:!0});var Dr=class extends gt{constructor(e,n={}){super(e),this[ef]=n.data===void 0?null:n.data}get data(){return this[ef]}};Object.defineProperty(Dr.prototype,"data",{enumerable:!0});var fb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[jr]&&o[Ra]===e&&!o[jr])return;let r;if(t==="message")r=function(i,s){let a=new Dr("message",{data:s?i:i.toString()});a[Wn]=this,Ko(e,this,a)};else if(t==="close")r=function(i,s){let a=new rn("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Wn]=this,Ko(e,this,a)};else if(t==="error")r=function(i){let s=new Vn("error",{error:i,message:i.message});s[Wn]=this,Ko(e,this,s)};else if(t==="open")r=function(){let i=new gt("open");i[Wn]=this,Ko(e,this,i)};else return;r[jr]=!!n[jr],r[Ra]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Ra]===e&&!n[jr]){this.removeListener(t,n);break}}};af.exports={CloseEvent:rn,ErrorEvent:Vn,Event:gt,EventTarget:fb,MessageEvent:Dr};function Ko(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Jo=_((gP,lf)=>{"use strict";var{tokenChars:Fr}=Un();function tt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function mb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);l===44?(tt(e,p,n),n=Object.create(null)):s=p,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),tt(n,t.slice(c,u),!0),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Fr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Fr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);r&&(p=p.replace(/\\/g,""),r=!1),tt(n,a,p),l===44&&(tt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let h=t.slice(c,u);return s===void 0?tt(e,h,n):(a===void 0?tt(n,h,!0):r?tt(n,a,h.replace(/\\/g,"")):tt(n,a,h),tt(e,s,n)),e}function pb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}lf.exports={format:pb,parse:mb}});var Zo=_((wP,bf)=>{"use strict";var hb=Z("events"),gb=Z("https"),yb=Z("http"),ff=Z("net"),_b=Z("tls"),{randomBytes:wb,createHash:vb}=Z("crypto"),{Duplex:yP,Readable:_P}=Z("stream"),{URL:Pa}=Z("url"),xt=qn(),bb=Sa(),Sb=$a(),{isBlob:Eb}=Un(),{BINARY_TYPES:uf,CLOSE_TIMEOUT:kb,EMPTY_BUFFER:Yo,GUID:$b,kForOnEventAttribute:Ta,kListener:Rb,kStatusCode:Pb,kWebSocket:oe,NOOP:mf}=pt(),{EventTarget:{addEventListener:Tb,removeEventListener:Ab}}=cf(),{format:Cb,parse:xb}=Jo(),{toBuffer:Ib}=Mr(),pf=Symbol("kAborted"),Aa=[8,13],yt=["CONNECTING","OPEN","CLOSING","CLOSED"],Ob=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends hb{constructor(e,n,r){super(),this._binaryType=uf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Yo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),hf(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new bb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Sb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[oe]=this,i[oe]=this,e[oe]=this,o.on("conclude",Lb),o.on("drain",jb),o.on("error",Db),o.on("message",Fb),o.on("ping",Bb),o.on("pong",qb),i.onerror=Ub,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",_f),e.on("data",Xo),e.on("end",wf),e.on("error",vf),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[xt.extensionName]&&this._extensions[xt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),yf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Yo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Yo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ca(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xt.extensionName]||(o.compress=!1),this._sender.send(e||Yo,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ta])return e[Rb];return null},set(e){for(let n of this.listeners(t))if(n[Ta]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ta]:!0})}})});V.prototype.addEventListener=Tb;V.prototype.removeEventListener=Ab;bf.exports=V;function hf(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kb,protocolVersion:Aa[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Aa.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Aa.join(", ")})`);let i;if(e instanceof Pa)i=e;else try{i=new Pa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Qo(t,m);return}let l=s?443:80,u=wb(16).toString("base64"),d=s?gb.request:yb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?Mb:Nb),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new xt({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=Cb({[xt.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Ob.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{$e(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[pf]||(f=t._req=null,Qo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){$e(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new Pa(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Qo(t,R);return}hf(t,v,n,r)}else t.emit("unexpected-response",f,m)||$e(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==V.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){$e(t,g,"Invalid Upgrade header");return}let S=vb("sha1").update(u+$b).digest("base64");if(m.headers["sec-websocket-accept"]!==S){$e(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],$;if(R!==void 0?h.size?h.has(R)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":h.size&&($="Server sent no subprotocol"),$){$e(t,g,$);return}R&&(t._protocol=R);let z=m.headers["sec-websocket-extensions"];if(z!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Q;try{Q=xb(z)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ie=Object.keys(Q);if(ie.length!==1||ie[0]!==xt.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(Q[xt.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xt.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Qo(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Nb(t){return t.path=t.socketPath,ff.connect(t)}function Mb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ff.isIP(t.host)?"":t.host),_b.connect(t)}function $e(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[pf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ca(t,e,n){if(e){let r=Eb(e)?e.size:Ib(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${yt[t.readyState]})`);process.nextTick(n,r)}}function Lb(t,e){let n=this[oe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[oe]!==void 0&&(n._socket.removeListener("data",Xo),process.nextTick(gf,n._socket),t===1005?n.close():n.close(t,e))}function jb(){let t=this[oe];t.isPaused||t._socket.resume()}function Db(t){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",Xo),process.nextTick(gf,e._socket),e.close(t[Pb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function df(){this[oe].emitClose()}function Fb(t,e){this[oe].emit("message",t,e)}function Bb(t){let e=this[oe];e._autoPong&&e.pong(t,!this._isServer,mf),e.emit("ping",t)}function qb(t){this[oe].emit("pong",t)}function gf(t){t.resume()}function Ub(t){let e=this[oe];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,yf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function yf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function _f(){let t=this[oe];if(this.removeListener("close",_f),this.removeListener("data",Xo),this.removeListener("end",wf),t._readyState=V.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[oe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",df),t._receiver.on("finish",df))}function Xo(t){this[oe]._receiver.write(t)||this.pause()}function wf(){let t=this[oe];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function vf(){let t=this[oe];this.removeListener("error",vf),this.on("error",mf),t&&(t._readyState=V.CLOSING,this.destroy())}});var $f=_((bP,kf)=>{"use strict";var vP=Zo(),{Duplex:Hb}=Z("stream");function Sf(t){t.emit("close")}function Gb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ef(t){this.removeListener("error",Ef),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wb(t,e){let n=!0,r=new Hb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick(Sf,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick(Sf,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",Gb),r.on("error",Ef),r}kf.exports=Wb});var xa=_((SP,Rf)=>{"use strict";var{tokenChars:Vb}=Un();function zb(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Vb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Rf.exports={parse:zb}});var Of=_((kP,If)=>{"use strict";var Kb=Z("events"),ei=Z("http"),{Duplex:EP}=Z("stream"),{createHash:Jb}=Z("crypto"),Pf=Jo(),on=qn(),Yb=xa(),Qb=Zo(),{CLOSE_TIMEOUT:Xb,GUID:Zb,kWebSocket:eS}=pt(),tS=/^[+/0-9A-Za-z]{22}==$/,Tf=0,Af=1,xf=2,Ia=class extends Kb{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Xb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Qb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ei.createServer((r,o)=>{let i=ei.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=nS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Tf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===xf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Br,this);return}if(e&&this.once("close",e),this._state!==Af)if(this._state=Af,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Br,this):process.nextTick(Br,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Br(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Cf);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){sn(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){sn(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!tS.test(i)){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){sn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){qr(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Yb.parse(c)}catch{sn(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new on({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Pf.parse(u);p[on.extensionName]&&(h.accept(p[on.extensionName]),d[on.extensionName]=h)}catch{sn(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,f,m,g)=>{if(!p)return qr(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return qr(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[eS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Tf)return qr(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Jb("sha1").update(n+Zb).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[on.extensionName]){let d=e[on.extensionName].params,h=Pf.format({[on.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
|
|
10
|
+
deps: ${n}}`};var cw={keyword:"dependencies",type:"object",schemaType:"object",error:Ze.error,code(t){let[e,n]=lw(t);ju(t,e),Du(t,n)}};function lw({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function ju(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let i=n.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Or.propertyInData)(n,r,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let l of a)(0,Or.checkReportMissingProp)(t,l)}):(n.if((0,Fs._)`${c} && (${(0,Or.checkMissingProp)(t,a,i)})`),(0,Or.reportMissingProp)(t,i),n.else())}}Ze.validatePropertyDeps=ju;function Du(t,e=t.schema){let{gen:n,data:r,keyword:o,it:i}=t,s=n.name("valid");for(let a in e)(0,aw.alwaysValidSchema)(i,e[a])||(n.if((0,Or.propertyInData)(n,r,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),t.ok(s))}Ze.validateSchemaDeps=Du;Ze.default=cw});var Uu=_(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var Bu=T(),uw=L(),dw={message:"property name must be valid",params:({params:t})=>(0,Bu._)`{propertyName: ${t.propertyName}}`},fw={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dw,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,uw.alwaysValidSchema)(o,n))return;let i=e.name("valid");e.forIn("key",r,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,Bu.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};Bs.default=fw});var qs=_(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Oo=Ie(),Ue=T(),mw=dt(),No=L(),pw={message:"must NOT have additional properties",params:({params:t})=>(0,Ue._)`{additionalProperty: ${t.additionalProperty}}`},hw={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:pw,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,No.alwaysValidSchema)(s,n))return;let l=(0,Oo.allSchemaProperties)(r.properties),u=(0,Oo.allSchemaProperties)(r.patternProperties);d(),t.ok((0,Ue._)`${i} === ${mw.default.errors}`);function d(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(h(g),()=>f(g))})}function h(g){let y;if(l.length>8){let v=(0,No.schemaRefOrVal)(s,r.properties,"properties");y=(0,Oo.isOwnProperty)(e,v,g)}else l.length?y=(0,Ue.or)(...l.map(v=>(0,Ue._)`${g} === ${v}`)):y=Ue.nil;return u.length&&(y=(0,Ue.or)(y,...u.map(v=>(0,Ue._)`${(0,Oo.usePattern)(t,v)}.test(${g})`))),(0,Ue.not)(y)}function p(g){e.code((0,Ue._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){p(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,No.alwaysValidSchema)(s,n)){let y=e.name("valid");c.removeAdditional==="failing"?(m(g,y,!1),e.if((0,Ue.not)(y),()=>{t.reset(),p(g)})):(m(g,y),a||e.if((0,Ue.not)(y),()=>e.break()))}}function m(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:No.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(S,y)}}};Us.default=hw});var Gu=_(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var gw=wr(),qu=Ie(),Hs=L(),Hu=qs(),yw={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:i}=t;i.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Hu.default.code(new gw.KeywordCxt(i,Hu.default,"additionalProperties"));let s=(0,qu.allSchemaProperties)(n);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Hs.mergeEvaluated.props(e,(0,Hs.toHash)(s),i.props));let a=s.filter(d=>!(0,Hs.alwaysValidSchema)(i,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,qu.propertyInData)(e,o,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&n[d].default!==void 0}function u(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Gs.default=yw});var Ku=_(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Vu=Ie(),Lo=T(),Wu=L(),zu=L(),_w={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,Vu.allSchemaProperties)(n),c=a.filter(m=>(0,Wu.alwaysValidSchema)(i,n[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&o.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof Lo.Name)&&(i.props=(0,zu.evaluatedPropsToName)(e,i.props));let{props:d}=i;h();function h(){for(let m of a)l&&p(m),i.allErrors?f(m):(e.var(u,!0),f(m),e.if(u))}function p(m){for(let g in l)new RegExp(m).test(g)&&(0,Wu.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){e.forIn("key",r,g=>{e.if((0,Lo._)`${(0,Vu.usePattern)(t,m)}.test(${g})`,()=>{let y=c.includes(m);y||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:zu.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,Lo._)`${d}[${g}]`,!0):!y&&!i.allErrors&&e.if((0,Lo.not)(u),()=>e.break())})})}}};Vs.default=_w});var Ju=_(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var ww=L(),vw={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,ww.alwaysValidSchema)(r,n)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ws.default=vw});var Yu=_(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var bw=Ie(),Sw={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bw.validateUnion,error:{message:"must match a schema in anyOf"}};zs.default=Sw});var Qu=_(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var Mo=T(),Ew=L(),kw={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Mo._)`{passingSchemas: ${t.passing}}`},$w={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kw,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let i=n,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(s,()=>t.reset(),()=>t.error(!0));function l(){i.forEach((u,d)=>{let h;(0,Ew.alwaysValidSchema)(o,u)?e.var(c,!0):h=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Mo._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Mo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),h&&t.mergeEvaluated(h,Mo.Name)})})}}};Ks.default=$w});var Xu=_(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Rw=L(),Pw={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((i,s)=>{if((0,Rw.alwaysValidSchema)(r,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Js.default=Pw});var td=_(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var jo=T(),ed=L(),Aw={message:({params:t})=>(0,jo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jo._)`{failingKeyword: ${t.ifClause}}`},Tw={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Aw,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,ed.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Zu(r,"then"),i=Zu(r,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,jo.not)(a),l("else"));t.pass(s,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,d){return()=>{let h=t.subschema({keyword:u},a);e.assign(s,a),t.mergeValidEvaluated(h,s),d?e.assign(d,(0,jo._)`${u}`):t.setParams({ifClause:u})}}}};function Zu(t,e){let n=t.schema[e];return n!==void 0&&!(0,ed.alwaysValidSchema)(t,n)}Ys.default=Tw});var nd=_(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var xw=L(),Cw={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,xw.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Qs.default=Cw});var rd=_(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Iw=Ns(),Ow=Ou(),Nw=Ls(),Lw=Lu(),Mw=Mu(),jw=Fu(),Dw=Uu(),Fw=qs(),Bw=Gu(),Uw=Ku(),qw=Ju(),Hw=Yu(),Gw=Qu(),Vw=Xu(),Ww=td(),zw=nd();function Kw(t=!1){let e=[qw.default,Hw.default,Gw.default,Vw.default,Ww.default,zw.default,Dw.default,Fw.default,jw.default,Bw.default,Uw.default];return t?e.push(Ow.default,Lw.default):e.push(Iw.default,Nw.default),e.push(Mw.default),e}Xs.default=Kw});var od=_(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Y=T(),Jw={message:({schemaCode:t})=>(0,Y.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Y._)`{format: ${t}}`},Yw={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Jw,code(t,e){let{gen:n,data:r,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;o?h():p();function h(){let f=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),m=n.const("fDef",(0,Y._)`${f}[${s}]`),g=n.let("fType"),y=n.let("format");n.if((0,Y._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(g,(0,Y._)`${m}.type || "string"`).assign(y,(0,Y._)`${m}.validate`),()=>n.assign(g,(0,Y._)`"string"`).assign(y,m)),t.fail$data((0,Y.or)(v(),S()));function v(){return c.strictSchema===!1?Y.nil:(0,Y._)`${s} && !${y}`}function S(){let R=u.$async?(0,Y._)`(${m}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Y._)`${y}(${r})`,$=(0,Y._)`(typeof ${y} == "function" ? ${R} : ${y}.test(${r}))`;return(0,Y._)`${y} && ${y} !== true && ${g} === ${e} && !${$}`}}function p(){let f=d.formats[i];if(!f){v();return}if(f===!0)return;let[m,g,y]=S(f);m===e&&t.pass(R());function v(){if(c.strictSchema===!1){d.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function S($){let K=$ instanceof RegExp?(0,Y.regexpCode)($):c.code.formats?(0,Y._)`${c.code.formats}${(0,Y.getProperty)(i)}`:void 0,X=n.scopeValue("formats",{key:i,ref:$,code:K});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,Y._)`${X}.validate`]:["string",$,X]}function R(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Y._)`await ${y}(${r})`}return typeof g=="function"?(0,Y._)`${y}(${r})`:(0,Y._)`${y}.test(${r})`}}}};Zs.default=Yw});var id=_(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var Qw=od(),Xw=[Qw.default];ea.default=Xw});var sd=_(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.contentVocabulary=Cn.metadataVocabulary=void 0;Cn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Cn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cd=_(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});var Zw=hu(),ev=Tu(),tv=rd(),nv=id(),ad=sd(),rv=[Zw.default,ev.default,(0,tv.default)(),nv.default,ad.metadataVocabulary,ad.contentVocabulary];ta.default=rv});var ud=_(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.DiscrError=void 0;var ld;(function(t){t.Tag="tag",t.Mapping="mapping"})(ld||(Do.DiscrError=ld={}))});var fd=_(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var In=T(),na=ud(),dd=vo(),ov=vr(),iv=L(),sv={message:({params:{discrError:t,tagName:e}})=>t===na.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,In._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},av={keyword:"discriminator",type:"object",schemaType:"object",error:sv,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,In._)`${n}${(0,In.getProperty)(a)}`);e.if((0,In._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:na.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let p=h();e.if(!1);for(let f in p)e.elseIf((0,In._)`${l} === ${f}`),e.assign(c,d(p[f]));e.else(),t.error(!1,{discrError:na.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let f=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},f);return t.mergeEvaluated(m,In.Name),f}function h(){var p;let f={},m=y(o),g=!0;for(let R=0;R<s.length;R++){let $=s[R];if($?.$ref&&!(0,iv.schemaHasRulesButRef)($,i.self.RULES)){let X=$.$ref;if($=dd.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,X),$ instanceof dd.SchemaEnv&&($=$.schema),$===void 0)throw new ov.default(i.opts.uriResolver,i.baseId,X)}let K=(p=$?.properties)===null||p===void 0?void 0:p[a];if(typeof K!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y($)),v(K,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function y({required:R}){return Array.isArray(R)&&R.includes(a)}function v(R,$){if(R.const)S(R.const,$);else if(R.enum)for(let K of R.enum)S(K,$);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function S(R,$){if(typeof R!="string"||R in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[R]=$}}}};ra.default=av});var md=_((iP,cv)=>{cv.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 Bo=_((V,oa)=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.MissingRefError=V.ValidationError=V.CodeGen=V.Name=V.nil=V.stringify=V.str=V._=V.KeywordCxt=V.Ajv=void 0;var lv=lu(),uv=cd(),dv=fd(),pd=md(),fv=["/properties"],Fo="http://json-schema.org/draft-07/schema",On=class extends lv.default{_addVocabularies(){super._addVocabularies(),uv.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(dv.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(pd,fv):pd;this.addMetaSchema(e,Fo,!1),this.refs["http://json-schema.org/schema"]=Fo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fo)?Fo:void 0)}};V.Ajv=On;oa.exports=V=On;oa.exports.Ajv=On;Object.defineProperty(V,"__esModule",{value:!0});V.default=On;var mv=wr();Object.defineProperty(V,"KeywordCxt",{enumerable:!0,get:function(){return mv.KeywordCxt}});var Nn=T();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Nn._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Nn.str}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Nn.stringify}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Nn.nil}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Nn.Name}});Object.defineProperty(V,"CodeGen",{enumerable:!0,get:function(){return Nn.CodeGen}});var pv=_o();Object.defineProperty(V,"ValidationError",{enumerable:!0,get:function(){return pv.default}});var hv=vr();Object.defineProperty(V,"MissingRefError",{enumerable:!0,get:function(){return hv.default}})});var Sd=_(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.formatNames=tt.fastFormats=tt.fullFormats=void 0;function et(t,e){return{validate:t,compare:e}}tt.fullFormats={date:et(_d,ca),time:et(sa(!0),la),"date-time":et(hd(!0),vd),"iso-time":et(sa(),wd),"iso-date-time":et(hd(),bd),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:bv,"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:Av,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:Sv,int32:{type:"number",validate:$v},int64:{type:"number",validate:Rv},float:{type:"number",validate:yd},double:{type:"number",validate:yd},password:!0,binary:!0};tt.fastFormats={...tt.fullFormats,date:et(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ca),time:et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,la),"date-time":et(/^\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,vd),"iso-time":et(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wd),"iso-date-time":et(/^\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,bd),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};tt.formatNames=Object.keys(tt.fullFormats);function gv(t){return t%4===0&&(t%100!==0||t%400===0)}var yv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_v=[0,31,28,31,30,31,30,31,31,30,31,30,31];function _d(t){let e=yv.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&gv(n)?29:_v[r])}function ca(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ia=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function sa(t){return function(n){let r=ia.exec(n);if(!r)return!1;let o=+r[1],i=+r[2],s=+r[3],a=r[4],c=r[5]==="-"?-1:1,l=+(r[6]||0),u=+(r[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let d=i-u*c,h=o-l*c-(d<0?1:0);return(h===23||h===-1)&&(d===59||d===-1)&&s<61}}function la(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function wd(t,e){if(!(t&&e))return;let n=ia.exec(t),r=ia.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var aa=/t|\s/i;function hd(t){let e=sa(t);return function(r){let o=r.split(aa);return o.length===2&&_d(o[0])&&e(o[1])}}function vd(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function bd(t,e){if(!(t&&e))return;let[n,r]=t.split(aa),[o,i]=e.split(aa),s=ca(n,o);if(s!==void 0)return s||la(r,i)}var wv=/\/|:/,vv=/^(?:[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 bv(t){return wv.test(t)&&vv.test(t)}var gd=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Sv(t){return gd.lastIndex=0,gd.test(t)}var Ev=-(2**31),kv=2**31-1;function $v(t){return Number.isInteger(t)&&t<=kv&&t>=Ev}function Rv(t){return Number.isInteger(t)}function yd(){return!0}var Pv=/[^\\]\\Z/;function Av(t){if(Pv.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ed=_(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.formatLimitDefinition=void 0;var Tv=Bo(),qe=T(),Ct=qe.operators,Uo={formatMaximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},formatMinimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},formatExclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},formatExclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},xv={message:({keyword:t,schemaCode:e})=>(0,qe.str)`should be ${Uo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,qe._)`{comparison: ${Uo[t].okStr}, limit: ${e}}`};Ln.formatLimitDefinition={keyword:Object.keys(Uo),type:"string",schemaType:"string",$data:!0,error:xv,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Tv.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let h=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,qe._)`${h}[${c.schemaCode}]`);t.fail$data((0,qe.or)((0,qe._)`typeof ${p} != "object"`,(0,qe._)`${p} instanceof RegExp`,(0,qe._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let h=c.schema,p=a.formats[h];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${h}" does not define "compare" function`);let f=e.scopeValue("formats",{key:h,ref:p,code:s.code.formats?(0,qe._)`${s.code.formats}${(0,qe.getProperty)(h)}`:void 0});t.fail$data(d(f))}function d(h){return(0,qe._)`${h}.compare(${n}, ${r}) ${Uo[o].fail} 0`}},dependencies:["format"]};var Cv=t=>(t.addKeyword(Ln.formatLimitDefinition),t);Ln.default=Cv});var fa=_((Nr,Rd)=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});var Mn=Sd(),Iv=Ed(),ua=T(),kd=new ua.Name("fullFormats"),Ov=new ua.Name("fastFormats"),da=(t,e={keywords:!0})=>{if(Array.isArray(e))return $d(t,e,Mn.fullFormats,kd),t;let[n,r]=e.mode==="fast"?[Mn.fastFormats,Ov]:[Mn.fullFormats,kd],o=e.formats||Mn.formatNames;return $d(t,o,n,r),e.keywords&&(0,Iv.default)(t),t};da.get=(t,e="full")=>{let r=(e==="fast"?Mn.fastFormats:Mn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function $d(t,e,n,r){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,ua._)`require("ajv-formats/dist/formats").${r}`);for(let s of e)t.addFormat(s,n[s])}Rd.exports=Nr=da;Object.defineProperty(Nr,"__esModule",{value:!0});Nr.default=da});var ht=_((AP,Ld)=>{"use strict";var Od=["nodebuffer","arraybuffer","fragments"],Nd=typeof Blob<"u";Nd&&Od.push("blob");Ld.exports={BINARY_TYPES:Od,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Nd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Lr=_((TP,qo)=>{"use strict";var{EMPTY_BUFFER:Vv}=ht(),pa=Buffer[Symbol.species];function Wv(t,e){if(t.length===0)return Vv;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let o=0;o<t.length;o++){let i=t[o];n.set(i,r),r+=i.length}return r<e?new pa(n.buffer,n.byteOffset,r):n}function Md(t,e,n,r,o){for(let i=0;i<o;i++)n[r+i]=t[i]^e[i&3]}function jd(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function zv(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ha(t){if(ha.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pa(t):ArrayBuffer.isView(t)?e=new pa(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ha.readOnly=!1),e}qo.exports={concat:Wv,mask:Md,toArrayBuffer:zv,toBuffer:ha,unmask:jd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ee("bufferutil");qo.exports.mask=function(e,n,r,o,i){i<48?Md(e,n,r,o,i):t.mask(e,n,r,o,i)},qo.exports.unmask=function(e,n){e.length<32?jd(e,n):t.unmask(e,n)}}catch{}});var Bd=_((xP,Fd)=>{"use strict";var Dd=Symbol("kDone"),ga=Symbol("kRun"),ya=class{constructor(e){this[Dd]=()=>{this.pending--,this[ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ga]()}[ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Dd])}}};Fd.exports=ya});var Un=_((CP,Gd)=>{"use strict";var Mr=ee("zlib"),Ud=Lr(),Kv=Bd(),{kStatusCode:qd}=ht(),Jv=Buffer[Symbol.species],Yv=Buffer.from([0,0,255,255]),Go=Symbol("permessage-deflate"),gt=Symbol("total-length"),Fn=Symbol("callback"),It=Symbol("buffers"),Bn=Symbol("error"),Ho,_a=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ho){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ho=new Kv(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Fn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(o=>!(n.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>o.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let o=n[r];if(o.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(o=o[0],r==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else if(r==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${o}`);o=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${o}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=o})}),e}decompress(e,n,r){Ho.add(o=>{this._decompress(e,n,(i,s)=>{o(),r(i,s)})})}compress(e,n,r){Ho.add(o=>{this._compress(e,n,(i,s)=>{o(),r(i,s)})})}_decompress(e,n,r){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Mr.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Mr.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Go]=this,this._inflate[gt]=0,this._inflate[It]=[],this._inflate.on("error",Xv),this._inflate.on("data",Hd)}this._inflate[Fn]=r,this._inflate.write(e),n&&this._inflate.write(Yv),this._inflate.flush(()=>{let i=this._inflate[Bn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let s=Ud.concat(this._inflate[It],this._inflate[gt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gt]=0,this._inflate[It]=[],n&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,s=typeof this.params[i]!="number"?Mr.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Mr.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[gt]=0,this._deflate[It]=[],this._deflate.on("data",Qv)}this._deflate[Fn]=r,this._deflate.write(e),this._deflate.flush(Mr.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ud.concat(this._deflate[It],this._deflate[gt]);n&&(i=new Jv(i.buffer,i.byteOffset,i.length-4)),this._deflate[Fn]=null,this._deflate[gt]=0,this._deflate[It]=[],n&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Gd.exports=_a;function Qv(t){this[It].push(t),this[gt]+=t.length}function Hd(t){if(this[gt]+=t.length,this[Go]._maxPayload<1||this[gt]<=this[Go]._maxPayload){this[It].push(t);return}this[Bn]=new RangeError("Max payload size exceeded"),this[Bn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bn][qd]=1009,this.removeListener("data",Hd),this.reset()}function Xv(t){if(this[Go]._inflate=null,this[Bn]){this[Fn](this[Bn]);return}t[qd]=1007,this[Fn](t)}});var qn=_((IP,Vo)=>{"use strict";var{isUtf8:Vd}=ee("buffer"),{hasBlob:Zv}=ht(),eb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function tb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function wa(t){let e=t.length,n=0;for(;n<e;)if(!(t[n]&128))n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function nb(t){return Zv&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Vo.exports={isBlob:nb,isValidStatusCode:tb,isValidUTF8:wa,tokenChars:eb};if(Vd)Vo.exports.isValidUTF8=function(t){return t.length<24?wa(t):Vd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ee("utf-8-validate");Vo.exports.isValidUTF8=function(e){return e.length<32?wa(e):t(e)}}catch{}});var ka=_((OP,Xd)=>{"use strict";var{Writable:rb}=ee("stream"),Wd=Un(),{BINARY_TYPES:ob,EMPTY_BUFFER:zd,kStatusCode:ib,kWebSocket:sb}=ht(),{concat:va,toArrayBuffer:ab,unmask:cb}=Lr(),{isValidStatusCode:lb,isValidUTF8:Kd}=qn(),Wo=Buffer[Symbol.species],Le=0,Jd=1,Yd=2,Qd=3,ba=4,Sa=5,zo=6,Ea=class extends rb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ob[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[sb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Le}_write(e,n,r){if(this._opcode===8&&this._state==Le)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e),new Wo(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],o=n.length-e;e>=r.length?n.set(this._buffers.shift(),o):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),o),this._buffers[0]=new Wo(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Le:this.getInfo(e);break;case Jd:this.getPayloadLength16(e);break;case Yd:this.getPayloadLength64(e);break;case Qd:this.getMask();break;case ba:this.getData(e);break;case Sa:case zo:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if(n[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Wd.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(r){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Jd:this._payloadLength===127?this._state=Yd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Qd:this._state=ba}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ba}getData(e){let n=zd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&cb(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Sa,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Wd.extensionName].decompress(e,this._fin,(o,i)=>{if(o)return n(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(i)}this.dataMessage(n),this._state===Le&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Le;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=va(r,n):this._binaryType==="arraybuffer"?o=ab(va(r,n)):this._binaryType==="blob"?o=new Blob(r):o=r,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!0),this._state=Le,this.startLoop(e)}))}else{let o=va(r,n);if(!this._skipUTF8Validation&&!Kd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Sa||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit("message",o,!1),this._state=Le,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,zd),this.end();else{let r=e.readUInt16BE(0);if(!lb(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let o=new Wo(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Kd(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,o),this.end()}this._state=Le;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Le):(this._state=zo,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Le,this.startLoop(n)}))}createError(e,n,r,o,i){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=i,s[ib]=o,s}};Xd.exports=Ea});var Pa=_((LP,tf)=>{"use strict";var{Duplex:NP}=ee("stream"),{randomFillSync:ub}=ee("crypto"),Zd=Un(),{EMPTY_BUFFER:db,kWebSocket:fb,NOOP:mb}=ht(),{isBlob:Hn,isValidStatusCode:pb}=qn(),{mask:ef,toBuffer:nn}=Lr(),Me=Symbol("kByteLength"),hb=Buffer.alloc(4),Ko=8*1024,rn,Gn=Ko,He=0,gb=1,yb=2,$a=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=He,this.onerror=mb,this[fb]=void 0}static frame(e,n){let r,o=!1,i=2,s=!1;n.mask&&(r=n.maskBuffer||hb,n.generateMask?n.generateMask(r):(Gn===Ko&&(rn===void 0&&(rn=Buffer.alloc(Ko)),ub(rn,0,Ko),Gn=0),r[0]=rn[Gn++],r[1]=rn[Gn++],r[2]=rn[Gn++],r[3]=rn[Gn++]),s=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||s)&&n[Me]!==void 0?a=n[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,o=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(o?a+i:i);return l[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),n.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],s?[l,e]:o?(ef(e,r,l,i,a),[l]):(ef(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,o){let i;if(e===void 0)i=db;else{if(typeof e!="number"||!pb(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let s={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==He?this.enqueue([this.dispatch,i,!1,s,o]):this.sendFrame(t.frame(i,s),o)}ping(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=nn(e),o=e.length,i=nn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let o,i;if(typeof e=="string"?(o=Buffer.byteLength(e),i=!1):Hn(e)?(o=e.size,i=!1):(e=nn(e),o=e.length,i=nn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Me]:o,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==He?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let o=this._extensions[Zd.extensionName],i=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Hn(e)?(a=e.size,c=!1):(e=nn(e),a=e.length,c=nn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=o._threshold),this._compress=s):(s=!1,i=0),n.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:s};Hn(e)?this._state!==He?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==He?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,o){this._bufferedBytes+=r[Me],this._state=yb,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ra,this,a,o);return}this._bufferedBytes-=r[Me];let s=nn(i);n?this.dispatch(s,n,r,o):(this._state=He,this.sendFrame(t.frame(s,r),o),this.dequeue())}).catch(i=>{process.nextTick(_b,this,i,o)})}dispatch(e,n,r,o){if(!n){this.sendFrame(t.frame(e,r),o);return}let i=this._extensions[Zd.extensionName];this._bufferedBytes+=r[Me],this._state=gb,i.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Ra(this,c,o);return}this._bufferedBytes-=r[Me],this._state=He,r.readOnly=!1,this.sendFrame(t.frame(a,r),o),this.dequeue()})}dequeue(){for(;this._state===He&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};tf.exports=$a;function Ra(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let o=t._queue[r],i=o[o.length-1];typeof i=="function"&&i(e)}}function _b(t,e,n){Ra(t,e,n),t.onerror(e)}});var df=_((MP,uf)=>{"use strict";var{kForOnEventAttribute:jr,kListener:Aa}=ht(),nf=Symbol("kCode"),rf=Symbol("kData"),of=Symbol("kError"),sf=Symbol("kMessage"),af=Symbol("kReason"),Vn=Symbol("kTarget"),cf=Symbol("kType"),lf=Symbol("kWasClean"),yt=class{constructor(e){this[Vn]=null,this[cf]=e}get target(){return this[Vn]}get type(){return this[cf]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var on=class extends yt{constructor(e,n={}){super(e),this[nf]=n.code===void 0?0:n.code,this[af]=n.reason===void 0?"":n.reason,this[lf]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[nf]}get reason(){return this[af]}get wasClean(){return this[lf]}};Object.defineProperty(on.prototype,"code",{enumerable:!0});Object.defineProperty(on.prototype,"reason",{enumerable:!0});Object.defineProperty(on.prototype,"wasClean",{enumerable:!0});var Wn=class extends yt{constructor(e,n={}){super(e),this[of]=n.error===void 0?null:n.error,this[sf]=n.message===void 0?"":n.message}get error(){return this[of]}get message(){return this[sf]}};Object.defineProperty(Wn.prototype,"error",{enumerable:!0});Object.defineProperty(Wn.prototype,"message",{enumerable:!0});var Dr=class extends yt{constructor(e,n={}){super(e),this[rf]=n.data===void 0?null:n.data}get data(){return this[rf]}};Object.defineProperty(Dr.prototype,"data",{enumerable:!0});var wb={addEventListener(t,e,n={}){for(let o of this.listeners(t))if(!n[jr]&&o[Aa]===e&&!o[jr])return;let r;if(t==="message")r=function(i,s){let a=new Dr("message",{data:s?i:i.toString()});a[Vn]=this,Jo(e,this,a)};else if(t==="close")r=function(i,s){let a=new on("close",{code:i,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Vn]=this,Jo(e,this,a)};else if(t==="error")r=function(i){let s=new Wn("error",{error:i,message:i.message});s[Vn]=this,Jo(e,this,s)};else if(t==="open")r=function(){let i=new yt("open");i[Vn]=this,Jo(e,this,i)};else return;r[jr]=!!n[jr],r[Aa]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Aa]===e&&!n[jr]){this.removeListener(t,n);break}}};uf.exports={CloseEvent:on,ErrorEvent:Wn,Event:yt,EventTarget:wb,MessageEvent:Dr};function Jo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yo=_((jP,ff)=>{"use strict";var{tokenChars:Fr}=qn();function nt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function vb(t){let e=Object.create(null),n=Object.create(null),r=!1,o=!1,i=!1,s,a,c=-1,l=-1,u=-1,d=0;for(;d<t.length;d++)if(l=t.charCodeAt(d),s===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(d!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);l===44?(nt(e,p,n),n=Object.create(null)):s=p,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(l===32||l===9)u===-1&&c!==-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),nt(n,t.slice(c,u),!0),l===44&&(nt(e,s,n),n=Object.create(null),s=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,d),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(o){if(Fr[l]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),o=!1}else if(i)if(Fr[l]===1)c===-1&&(c=d);else if(l===34&&c!==-1)i=!1,u=d;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(l===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Fr[l]===1)c===-1&&(c=d);else if(c!==-1&&(l===32||l===9))u===-1&&(u=d);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(c,u);r&&(p=p.replace(/\\/g,""),r=!1),nt(n,a,p),l===44&&(nt(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let h=t.slice(c,u);return s===void 0?nt(e,h,n):(a===void 0?nt(n,h,!0):r?nt(n,a,h.replace(/\\/g,"")):nt(n,a,h),nt(e,s,n)),e}function bb(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(o=>{let i=r[o];return Array.isArray(i)||(i=[i]),i.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ff.exports={format:bb,parse:vb}});var ei=_((BP,kf)=>{"use strict";var Sb=ee("events"),Eb=ee("https"),kb=ee("http"),hf=ee("net"),$b=ee("tls"),{randomBytes:Rb,createHash:Pb}=ee("crypto"),{Duplex:DP,Readable:FP}=ee("stream"),{URL:Ta}=ee("url"),Ot=Un(),Ab=ka(),Tb=Pa(),{isBlob:xb}=qn(),{BINARY_TYPES:mf,CLOSE_TIMEOUT:Cb,EMPTY_BUFFER:Qo,GUID:Ib,kForOnEventAttribute:xa,kListener:Ob,kStatusCode:Nb,kWebSocket:ie,NOOP:gf}=ht(),{EventTarget:{addEventListener:Lb,removeEventListener:Mb}}=df(),{format:jb,parse:Db}=Yo(),{toBuffer:Fb}=Lr(),yf=Symbol("kAborted"),Ca=[8,13],_t=["CONNECTING","OPEN","CLOSING","CLOSED"],Bb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,z=class t extends Sb{constructor(e,n,r){super(),this._binaryType=mf[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),_f(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){mf.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let o=new Ab({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Tb(e,this._extensions,r.generateMask);this._receiver=o,this._sender=i,this._socket=e,o[ie]=this,i[ie]=this,e[ie]=this,o.on("conclude",Hb),o.on("drain",Gb),o.on("error",Vb),o.on("message",Wb),o.on("ping",zb),o.on("pong",Kb),i.onerror=Jb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bf),e.on("data",Zo),e.on("end",Sf),e.on("error",Ef),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ot.extensionName]&&this._extensions[Ot.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),vf(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Qo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ia(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Qo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ia(this,e,r);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ot.extensionName]||(o.compress=!1),this._sender.send(e||Qo,o,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(z,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(z.prototype,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(z,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(z.prototype,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(z,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(z.prototype,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(z,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});Object.defineProperty(z.prototype,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(z.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(z.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[xa])return e[Ob];return null},set(e){for(let n of this.listeners(t))if(n[xa]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[xa]:!0})}})});z.prototype.addEventListener=Lb;z.prototype.removeEventListener=Mb;kf.exports=z;function _f(t,e,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Cb,protocolVersion:Ca[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Ca.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Ca.join(", ")})`);let i;if(e instanceof Ta)i=e;else try{i=new Ta(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let s=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Xo(t,m);return}let l=s?443:80,u=Rb(16).toString("base64"),d=s?Eb.request:kb.request,h=new Set,p;if(o.createConnection=o.createConnection||(s?qb:Ub),o.defaultPort=o.defaultPort||l,o.port=i.port||l,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(p=new Ot({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=jb({[Ot.extensionName]:p.offer()})),n.length){for(let m of n){if(typeof m!="string"||!Bb.test(m)||h.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(m)}o.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),a){let m=o.path.split(":");o.socketPath=m[0],o.path=m[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?o.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,y]of Object.entries(m))r.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,m||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=d(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(o);o.timeout&&f.on("timeout",()=>{$e(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[yf]||(f=t._req=null,Xo(t,m))}),f.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&o.followRedirects&&y>=300&&y<400){if(++t._redirects>o.maxRedirects){$e(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new Ta(g,e)}catch{let R=new SyntaxError(`Invalid URL: ${g}`);Xo(t,R);return}_f(t,v,n,r)}else t.emit("unexpected-response",f,m)||$e(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==z.CONNECTING)return;f=t._req=null;let v=m.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){$e(t,g,"Invalid Upgrade header");return}let S=Pb("sha1").update(u+Ib).digest("base64");if(m.headers["sec-websocket-accept"]!==S){$e(t,g,"Invalid Sec-WebSocket-Accept header");return}let R=m.headers["sec-websocket-protocol"],$;if(R!==void 0?h.size?h.has(R)||($="Server sent an invalid subprotocol"):$="Server sent a subprotocol but none was requested":h.size&&($="Server sent no subprotocol"),$){$e(t,g,$);return}R&&(t._protocol=R);let K=m.headers["sec-websocket-extensions"];if(K!==void 0){if(!p){$e(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let X;try{X=Db(K)}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ae=Object.keys(X);if(ae.length!==1||ae[0]!==Ot.extensionName){$e(t,g,"Server indicated an extension that was not requested");return}try{p.accept(X[Ot.extensionName])}catch{$e(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ot.extensionName]=p}t.setSocket(g,y,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Xo(t,e){t._readyState=z.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Ub(t){return t.path=t.socketPath,hf.connect(t)}function qb(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=hf.isIP(t.host)?"":t.host),$b.connect(t)}function $e(t,e,n){t._readyState=z.CLOSING;let r=new Error(n);Error.captureStackTrace(r,$e),e.setHeader?(e[yf]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Xo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ia(t,e,n){if(e){let r=xb(e)?e.size:Fb(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_t[t.readyState]})`);process.nextTick(n,r)}}function Hb(t,e){let n=this[ie];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ie]!==void 0&&(n._socket.removeListener("data",Zo),process.nextTick(wf,n._socket),t===1005?n.close():n.close(t,e))}function Gb(){let t=this[ie];t.isPaused||t._socket.resume()}function Vb(t){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",Zo),process.nextTick(wf,e._socket),e.close(t[Nb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function pf(){this[ie].emitClose()}function Wb(t,e){this[ie].emit("message",t,e)}function zb(t){let e=this[ie];e._autoPong&&e.pong(t,!this._isServer,gf),e.emit("ping",t)}function Kb(t){this[ie].emit("pong",t)}function wf(t){t.resume()}function Jb(t){let e=this[ie];e.readyState!==z.CLOSED&&(e.readyState===z.OPEN&&(e._readyState=z.CLOSING,vf(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function vf(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bf(){let t=this[ie];if(this.removeListener("close",bf),this.removeListener("data",Zo),this.removeListener("end",Sf),t._readyState=z.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ie]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",pf),t._receiver.on("finish",pf))}function Zo(t){this[ie]._receiver.write(t)||this.pause()}function Sf(){let t=this[ie];t._readyState=z.CLOSING,t._receiver.end(),this.end()}function Ef(){let t=this[ie];this.removeListener("error",Ef),this.on("error",gf),t&&(t._readyState=z.CLOSING,this.destroy())}});var Af=_((qP,Pf)=>{"use strict";var UP=ei(),{Duplex:Yb}=ee("stream");function $f(t){t.emit("close")}function Qb(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rf(t){this.removeListener("error",Rf),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Xb(t,e){let n=!0,r=new Yb({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,s){let a=!s&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(o,i){if(t.readyState===t.CLOSED){i(o),process.nextTick($f,r);return}let s=!1;t.once("error",function(c){s=!0,i(c)}),t.once("close",function(){s||i(o),process.nextTick($f,r)}),n&&t.terminate()},r._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(o,i,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(o,i,s)});return}t.send(o,s)},r.on("end",Qb),r.on("error",Rf),r}Pf.exports=Xb});var Oa=_((HP,Tf)=>{"use strict";var{tokenChars:Zb}=qn();function eS(t){let e=new Set,n=-1,r=-1,o=0;for(o;o<t.length;o++){let s=t.charCodeAt(o);if(r===-1&&Zb[s]===1)n===-1&&(n=o);else if(o!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=o);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${o}`);r===-1&&(r=o);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,o);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Tf.exports={parse:eS}});var Mf=_((VP,Lf)=>{"use strict";var tS=ee("events"),ti=ee("http"),{Duplex:GP}=ee("stream"),{createHash:nS}=ee("crypto"),xf=Yo(),sn=Un(),rS=Oa(),oS=ei(),{CLOSE_TIMEOUT:iS,GUID:sS,kWebSocket:aS}=ht(),cS=/^[+/0-9A-Za-z]{22}==$/,Cf=0,If=1,Nf=2,Na=class extends tS{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:iS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:oS,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=ti.createServer((r,o)=>{let i=ti.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=lS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,s)=>{this.handleUpgrade(o,i,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Cf}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Nf){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Br,this);return}if(e&&this.once("close",e),this._state!==If)if(this._state=If,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Br,this):process.nextTick(Br,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Br(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,o){n.on("error",Of);let i=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){an(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){an(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!cS.test(i)){an(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){an(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ur(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=rS.parse(c)}catch{an(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let h=new sn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=xf.parse(u);p[sn.extensionName]&&(h.accept(p[sn.extensionName]),d[sn.extensionName]=h)}catch{an(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,f,m,g)=>{if(!p)return Ur(n,f||401,m,g);this.completeUpgrade(d,i,l,e,n,r,o)});return}if(!this.options.verifyClient(h))return Ur(n,401)}this.completeUpgrade(d,i,l,e,n,r,o)}completeUpgrade(e,n,r,o,i,s,a){if(!i.readable||!i.writable)return i.destroy();if(i[aS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Cf)return Ur(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${nS("sha1").update(n+sS).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,o):r.values().next().value;d&&(l.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[sn.extensionName]){let d=e[sn.extensionName].params,h=xf.format({[sn.extensionName]:[d]});l.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",l,o),i.write(l.concat(`\r
|
|
11
11
|
`).join(`\r
|
|
12
|
-
`)),i.removeListener("error",
|
|
12
|
+
`)),i.removeListener("error",Of),u.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Br,this)})),a(u,o)}};Lf.exports=Na;function lS(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Br(t){t._state=Nf,t.emit("close")}function Of(){this.destroy()}function Ur(t,e,n,r){n=n||ti.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${ti.STATUS_CODES[e]}\r
|
|
13
13
|
`+Object.keys(r).map(o=>`${o}: ${r[o]}`).join(`\r
|
|
14
14
|
`)+`\r
|
|
15
15
|
\r
|
|
16
|
-
`+n)}function
|
|
17
|
-
`}import
|
|
16
|
+
`+n)}function an(t,e,n,r,o,i){if(t.listenerCount("wsClientError")){let s=new Error(o);Error.captureStackTrace(s,an),t.emit("wsClientError",s,n,e)}else Ur(n,r,o,i)}});var Tc={"-v":"version","-h":"help"};function Cp(t){return t.startsWith("--")?!0:Tc[t]!==void 0}function xc(t,e){let n=[],r={},o=[],i=new Map;for(let c of e)i.set(c.name,c);let s=!1,a=0;for(;a<t.length;){let c=t[a];if(s){n.push(c),a+=1;continue}if(c==="--"){s=!0,a+=1;continue}if(c.startsWith("--")){let l=c.indexOf("="),u=l>=0?c.slice(2,l):c.slice(2),d=l>=0?c.slice(l+1):void 0,h=i.get(u);if(!h){o.push(`unknown flag: --${u}`),a+=1;continue}if(h.type==="boolean"){d===void 0||d==="true"?r[u]=!0:d==="false"?r[u]=!1:o.push(`flag --${u} expects no value (got "${d}")`),a+=1;continue}let p;if(d!==void 0)p=d,a+=1;else{let f=t[a+1];if(f===void 0||Cp(f)){o.push(`flag --${u} requires a value`),a+=1;continue}p=f,a+=2}if(h.type==="number"){if(!/^-?\d+(\.\d+)?$/.test(p)){o.push(`flag --${u} requires a number (got "${p}")`);continue}r[u]=Number(p);continue}r[u]=p;continue}if(c.startsWith("-")&&c.length>1){let l=Tc[c];if(!l){o.push(`unknown flag: ${c}`),a+=1;continue}let u=i.get(l);if(!u||u.type!=="boolean"){o.push(`unknown flag: ${c}`),a+=1;continue}r[l]=!0,a+=1;continue}n.push(c),a+=1}for(let c of e)c.default!==void 0&&r[c.name]===void 0&&(r[c.name]=c.default);for(let c of e)c.required&&r[c.name]===void 0&&o.push(`missing required flag: --${c.name}`);return{positional:n,flags:r,errors:o}}import Oc from"node:path";import Nc from"node:fs";import Cc from"node:fs";import Ip from"node:os";import Ic from"node:path";var Op=Ic.join(".aifight","runtime");function oe(){let t=process.env.AIFIGHT_RUNTIME_HOME;return t&&t.length>0?t:Ic.join(Ip.homedir(),Op)}function at(){let t=oe();if(Cc.mkdirSync(t,{recursive:!0}),process.platform!=="win32")try{Cc.chmodSync(t,448)}catch{}}var ke=class extends Error{name="RuntimeFilesError";kind;filePath;constructor(e,n,r){super(r),this.kind=e,this.filePath=n}};function Np(){return Oc.join(oe(),"token")}function Lp(){return Oc.join(oe(),"port")}function Lc(){let t=Np(),e;try{e=Nc.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new ke("token_missing",t,`token file not found at ${t}; AIFight Bridge must be running`):new ke("token_corrupt",t,`failed to read token file at ${t}: ${r.message}`)}let n=e.trim();if(n.length===0)throw new ke("token_corrupt",t,`token file at ${t} is empty`);return n}function Mc(){let t=Lp(),e;try{e=Nc.readFileSync(t,"utf8")}catch(o){throw o.code==="ENOENT"?new ke("port_missing",t,`port file not found at ${t}; AIFight Bridge must be running`):new ke("port_corrupt",t,`failed to read port file at ${t}: ${o.message}`)}let n=e.trim();if(n.length===0)throw new ke("port_corrupt",t,`port file at ${t} is empty`);if(!/^-?\d+$/.test(n))throw new ke("port_corrupt",t,`port file at ${t} is not a number: "${n}"`);let r=Number.parseInt(n,10);if(r<1||r>65535)throw new ke("port_corrupt",t,`port file at ${t} is out of range [1, 65535]: ${r}`);return r}var Mp=new Set(["unauthorized","not_found","method_not_allowed","bad_request","unsupported_media_type","payload_too_large","not_implemented","service_unavailable","internal_error"]);function jp(t){return typeof t=="string"&&Mp.has(t)}function Dp(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let n=e;return jp(n.code)&&typeof n.message=="string"}var pe=class extends Error{name="ControlClientError";kind;serverCode;status;body;cause;constructor(e,n,r){super(n),this.kind=e,this.serverCode=r?.serverCode,this.status=r?.status??0,this.body=r?.body,this.cause=r?.cause}},Fp="127.0.0.1",Bp=1e4;function jc(t){let e=t.host??Fp,n=t.baseTimeoutMs??Bp,r=t.fetchImpl??globalThis.fetch,o,i;function s(f){return f.kind==="token_missing"||f.kind==="port_missing"?new pe("daemon_unreachable",`AIFight Bridge not running: ${f.message}`,{cause:f}):new pe("runtime_files_corrupt",`corrupt runtime files: ${f.message}`,{cause:f})}function a(){if(o!==void 0&&i!==void 0)return{token:o,port:i};try{let f=t.tokenSource(),m=t.portSource();return o=f,i=m,{token:f,port:m}}catch(f){throw f instanceof ke?s(f):f}}function c(){let f=o,m=i;try{let g=t.tokenSource(),y=t.portSource();return o=g,i=y,{token:g,port:y,changed:g!==f||y!==m}}catch(g){throw g instanceof ke?s(g):g}}function l(f){return typeof f!="object"||f===null?!1:f.name==="AbortError"}function u(f,m,g,y){let v={Authorization:`Bearer ${g}`},S;return m===void 0?S=void 0:(v["Content-Type"]="application/json",S=JSON.stringify(m)),{method:f,headers:v,body:S,signal:y}}async function d(f,m,g,y,v){let S=`http://${e}:${v}${m}`,R=new AbortController,$=setTimeout(()=>{R.abort()},n);try{let K;try{K=await r(S,u(f,g,y,R.signal))}catch(ae){throw l(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("daemon_unreachable",`AIFight Bridge not running: ${ae.message}`,{cause:ae})}let X;try{X=await K.text()}catch(ae){throw l(ae)?new pe("request_timeout",`request timed out after ${n}ms`,{cause:ae}):new pe("transport_unparseable",`failed to read response body (status ${K.status})`,{status:K.status,cause:ae})}if(X.length===0)return{status:K.status,parsedBody:void 0,parseFailed:!1};try{return{status:K.status,parsedBody:JSON.parse(X),parseFailed:!1}}catch{return{status:K.status,parsedBody:X,parseFailed:!0}}}finally{clearTimeout($)}}function h(f){if(f.status>=200&&f.status<300){if(f.parseFailed)throw new pe("transport_unparseable",`non-JSON success response (status ${f.status})`,{status:f.status,body:f.parsedBody});return f.parsedBody}if(f.parseFailed||!Dp(f.parsedBody))throw new pe("transport_unparseable",`invalid error envelope (status ${f.status})`,{status:f.status,body:f.parsedBody});let m=f.parsedBody;throw new pe("server_error",m.error.message,{serverCode:m.error.code,status:f.status,body:m})}async function p(f,m,g){let y=a(),v=await d(f,m,g,y.token,y.port);if(v.status!==401)return h(v);let S=c();if(!S.changed)throw new pe("auth_failed","token mismatch \u2014 daemon rejected the cached credentials and the token / port files have not been rotated",{status:401});t.onLog&&t.onLog({code:"rebootstrap",message:"rebootstrap reason=401"});let R=await d(f,m,g,S.token,S.port);if(R.status===401)throw new pe("auth_failed","token mismatch \u2014 daemon still rejected after reread + retry",{status:401});return h(R)}return{get(f){return p("GET",f,void 0)},post(f,m){return p("POST",f,m)},delete(f){return p("DELETE",f,void 0)}}}function Dc(t,e={}){return jc({tokenSource:Lc,portSource:Mc,fetchImpl:t.fetchImpl,onLog:t.onLog,baseTimeoutMs:t.baseTimeoutMs,...e})}var he=["texas_holdem","liars_dice","coup"];function ct(t){return he.includes(t)}var O=class extends Error{name="UsageError";hint;constructor(e,n){super(e),n!==void 0&&(this.hint=n)}},U=class extends Error{name="CommandError";code;exitCode;hint;constructor(e,n,r={}){super(n),this.code=e,this.exitCode=r.exitCode??1,r.hint!==void 0&&(this.hint=r.hint)}};function W(t,e,n,r){let o=t.positional.length;if(o<e)throw new O(`missing required positional argument${e===1?"":"s"}`,r);if(o>n){let i=t.positional.slice(n).join(" ");throw new O(`unexpected extra positional argument${o-n===1?"":"s"}: ${i}`,r)}}function no(t,e,n){return JSON.stringify(n===void 0?{error:{code:t,message:e}}:{error:{code:t,message:e,details:n}})+`
|
|
17
|
+
`}import oo from"node:fs";import or from"node:path";import{fileURLToPath as Up}from"node:url";var Fc=["./schemas","../../../protocol/schema","../../protocol/schema"],ro=null;function ir(t=qp()){if(ro)return ro;for(let e of Fc){let n=or.resolve(t,e);if(Bc(n)&&Bc(or.join(n,"messages")))return ro=n,ro}throw new Error(`@aifight/aifight: cannot locate protocol/schema tree. Searched relative to ${t}: ${Fc.join(", ")}. Run build.sh to populate dist/schemas/ before packaging.`)}function qp(){return or.dirname(Up(import.meta.url))}function Bc(t){try{return oo.statSync(t).isDirectory()}catch{return!1}}var Hp={welcome:"messages/server_welcome.schema.json",queue_joined:"messages/server_queue_joined.schema.json",queue_left:"messages/server_queue_left.schema.json",match_confirm_request:"messages/server_match_confirm_request.schema.json",match_cancelled:"messages/server_match_cancelled.schema.json",game_start:"messages/server_game_start.schema.json",readiness_check:"messages/server_readiness_check.schema.json",action_request:"messages/server_action_request.schema.json",event:"messages/server_event.schema.json",game_state:"messages/server_game_state.schema.json",game_over:"messages/server_game_over.schema.json",error:"messages/server_error.schema.json",join_queue:"messages/client_join_queue.schema.json",leave_queue:"messages/client_leave_queue.schema.json",match_confirm:"messages/client_match_confirm.schema.json",action:"messages/client_action.schema.json",runtime_status:"messages/client_runtime_status.schema.json"};function wi(){return Object.keys(Hp)}function qt(){let t=ir(),e=new Map;return qc(t,n=>{if(!n.endsWith(".schema.json"))return;let r=oo.readFileSync(n,"utf8"),o=JSON.parse(r);typeof o.$id=="string"&&o.$id!==""&&e.set(o.$id,o)}),e}function qc(t,e){for(let n of oo.readdirSync(t,{withFileTypes:!0})){let r=or.join(t,n.name);n.isDirectory()?qc(r,e):n.isFile()&&e(r)}}var Uc={register_request:"rest/register_request.schema.json",register_response:"rest/register_response.schema.json",error_response:"rest/error_response.schema.json"};function vi(t){let e=Uc[t];if(!e)throw new Error(`@aifight/aifight: unknown REST schema '${t}'. Known: ${Object.keys(Uc).join(", ")}`);let n=ir(),r=or.join(n,e),o=oo.readFileSync(r,"utf8");return JSON.parse(o)}var Pd=xe(Bo(),1),Ad=xe(fa(),1);var jn=class extends Error{},pt=class extends jn{kind="network";cause;constructor(e,n){super(e),this.name="RegisterNetworkError",this.cause=n}},Zt=class extends jn{kind="http";status;body;constructor(e,n,r){super(r),this.name="RegisterHttpError",this.status=e,this.body=n}},en=class extends jn{kind="schema";ajvErrors;constructor(e,n){super(n),this.name="RegisterSchemaError",this.ajvErrors=e}};var Nv=3e4,tn="/api/agents/register",Lv="https://aifight.ai/protocol/v1/rest/register_response.schema.json",Dn=null;function Mv(){if(Dn)return Dn;let t=new Pd.default({strict:!1,allErrors:!0});(0,Ad.default)(t);let e=qt();for(let[o,i]of e)t.getSchema(o)||t.addSchema(i,o);let n=t.getSchema(Lv);if(n)return Dn=n,Dn;let r=vi("register_response");return Dn=t.compile(r),Dn}async function ma(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??Nv,r=t.baseUrl.replace(/\/+$/,"")+tn,o=AbortSignal.timeout(n),i=t.signal?AbortSignal.any([o,t.signal]):o,s;try{s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.request),signal:i})}catch(p){if(o.aborted)throw new pt(`POST ${tn} timed out after ${n}ms`,p);if(t.signal?.aborted)throw new pt(`POST ${tn} aborted by caller`,p);let f=p instanceof Error?p.message:String(p);throw new pt(`POST ${tn} failed: ${f}`,p)}let a=await s.text(),c,l=null;if(a.length>0)try{c=JSON.parse(a)}catch(p){l=p instanceof Error?p:new Error(String(p))}if(s.status!==201){let p=c&&typeof c=="object"&&c!==null&&"error"in c?c:a;throw new Zt(s.status,p,`POST ${tn} returned HTTP ${s.status}`)}if(l!==null)throw new en([],`POST ${tn} returned 201 with non-JSON body: ${l.message}`);if(typeof c!="object"||c===null)throw new en([],`POST ${tn} returned 201 with non-object body`);let u=Mv();if(!u(c)){let p=(u.errors??[]).map(f=>({instancePath:f.instancePath,message:f.message??void 0}));throw new en(p,"register_response schema validation failed")}let h=c;return{response:h,apiKey:h.agent.api_key,claimToken:h.claim_token,agentId:h.agent.id,claimUrl:h.claim_url}}import hP from"better-sqlite3";var Td=`-- runtime/src/store/schema.sql
|
|
18
18
|
-- AUTO-APPLIED by src/store/sqlite.ts as the v1 migration step.
|
|
19
19
|
-- DO NOT edit this file by hand \u2014 this is v1's BYTE SOURCE (bundled
|
|
20
20
|
-- into SCHEMA_SQL_V1 by bundle-schema.mjs). M1-05 appended a v2
|
|
@@ -49,7 +49,7 @@ CREATE TABLE IF NOT EXISTS agents (
|
|
|
49
49
|
);
|
|
50
50
|
|
|
51
51
|
CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
|
|
52
|
-
`;var
|
|
52
|
+
`;var xd=[{version:1,up:t=>{t.exec(Td)}},{version:2,up:t=>{let e=t.prepare("SELECT COUNT(*) AS n FROM agents").get().n;if(e>0)throw new Error(`M1-05 migration refuses to upgrade a populated agents table (${e} rows). These rows were written in schema v1 with TEXT plaintext columns and cannot be silently reinterpreted as encrypted BLOBs. Remediation: back up the DB file, then DELETE FROM agents, then re-open to trigger migration. For a real re-encrypt migration, open a new TED.`);t.exec(`
|
|
53
53
|
CREATE TABLE agents_new (
|
|
54
54
|
id TEXT NOT NULL PRIMARY KEY,
|
|
55
55
|
name TEXT NOT NULL UNIQUE,
|
|
@@ -64,116 +64,116 @@ CREATE INDEX IF NOT EXISTS idx_agents_name ON agents(name);
|
|
|
64
64
|
ALTER TABLE agents_new RENAME TO agents;
|
|
65
65
|
DROP INDEX IF EXISTS idx_agents_name;
|
|
66
66
|
CREATE INDEX idx_agents_name ON agents(name);
|
|
67
|
-
`)}}],XR=Pd[Pd.length-1].version;import{Entry as tP}from"@napi-rs/keyring";var Td="AIFIGHT_KEYCHAIN_V1:",Ad="AIFIGHT_CRYPTO_V1:";var oP=Buffer.byteLength(Td,"ascii"),iP=Buffer.byteLength(Ad,"ascii");var rS=Ce($f(),1),oS=Ce(Jo(),1),iS=Ce(qn(),1),sS=Ce(Sa(),1),aS=Ce($a(),1),cS=Ce(xa(),1),Oa=Ce(Zo(),1),lS=Ce(Of(),1);var fe=class extends Error{},It=class extends fe{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Ot=class extends fe{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},an=class extends fe{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Nt=class extends fe{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},cn=class extends fe{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},ln=class extends fe{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends fe{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},nt=class extends fe{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},_t=class extends fe{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},wt=class extends fe{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var Nf=Ce(Fo(),1),Mf=Ce(ua(),1);var Ma=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),La=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Lf="https://aifight.ai/protocol/v1/messages/";function uS(t){return`${Lf}client_${t}.schema.json`}function dS(t){return`${Lf}server_${t}.schema.json`}var Na=null;function jf(){if(Na)return Na;let t=new Nf.default({strict:!1,allErrors:!0});(0,Mf.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Na=t,t}function Df(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function Ff(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Bf(t){if(!Ff(t))throw new nt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new nt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(La.has(e))throw new nt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!Ma.has(e))throw new nt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...Ma].join(", ")})`);let n=jf(),r=uS(e),o=n.getSchema(r);if(!o)throw new nt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new nt(e,Df(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function ja(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!Ff(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!La.has(r))throw Ma.has(r)?new _t(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new _t(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...La].join(", ")})`);let o=jf(),i=dS(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,Df(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var fS=1e4,mS=25e3;function qf(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var Da=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??mS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=ja(n)}catch(o){if(o instanceof Re||o instanceof _t)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#h(r)}#h(e){let n=[...this.#a];for(let r of n)this.#p(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#p(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#p(()=>r(e))}#p(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new ln(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Bf(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function Fa(t){let e=t.welcomeTimeoutMs??fS;return t.signal?.aborted?Promise.reject(new wt(`createWSClient aborted before start: ${qf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new Oa.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new It(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new wt(`createWSClient aborted during handshake: ${qf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new It(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Ot(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Ot(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new an(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),h;try{h=ja(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof _t?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Nt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Nt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new cn(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Da(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var zn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},pS=1e3,hS=2,gS=3e4,yS="full",_S=5*60*1e3,wS=15*60*1e3,vS=new Set([1001,1006,1011,1012]);function bS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function SS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function ES(t){return t.code>=4e3&&t.code<5e3?!1:vS.has(t.code)}function kS(t){if(t instanceof wt||t instanceof Nt||t instanceof cn)return!1;if(t instanceof It||t instanceof an)return!0;if(t instanceof Ot){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function $S(t){return t>=wS?"error":t>=_S?"warning":"info"}var Ba=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#h=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new ln(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#h&&this.#h("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await Fa({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!ES(l)){let u=new zn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof fe&&(e=a),!kS(a)){let c=a instanceof fe?a:void 0,l=a instanceof wt?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=bS(this.#u,this.#e.initialBackoffMs??pS,this.#e.backoffFactor??hS,this.#e.maxBackoffMs??gS),o=SS(r,this.#e.jitter??yS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#p(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new zn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#p(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#h=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#h=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?$S(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new zn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function qa(t){let e=new Ba(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var RS=["check","call","fold","raise","allin"];function Ua(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of RS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Ga(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=PS(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=TS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function PS(t){let e=AS(t);if(!e)return;let n=Ha(e,"min_quantity"),r=Ha(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Ha(e,"max_quantity")}}function TS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function AS(t){return t!==null&&typeof t=="object"?t:void 0}function Ha(t,e){let n=t[e];return typeof n=="number"?n:void 0}var CS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],xS=["pass","challenge"],IS=["pass","block"],OS=["lose_card"],NS=["return_cards"];function Wa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return Ur(n,CS);case"challenge_action":case"challenge_block":return Ur(n,xS);case"block":return Ur(n,IS);case"lose_influence":return Ur(n,OS);case"exchange_return":return Ur(n,NS);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function Ur(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var MS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function za(t,e,n=500){let r=t.trim(),o=DS(r),i;try{i=JSON.parse(o)}catch{return un("json_parse",r,n)}if(!ti(i))return un("missing_fields",r,n);let s=i.action;if(typeof s!="string")return un("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ti(c))return un("missing_fields",r,n);let l=ti(c)?c:void 0;if(!LS.has(s))return un("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return un("action_not_legal",r,n);if(s==="raise"){let d=jS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:un("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var LS=new Set(["fold","check","call","raise","allin"]);function jS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ti(t.data)?t.data:void 0,o=Va(r,"amount"),i=Va(r,"min")??o,s=Va(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function DS(t){let e=t.match(MS);return e?e[1].trim():t}function ti(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Va(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function un(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var FS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=US(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!ni(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ni(c))return dn("missing_fields",r,n);let l=ni(c)?c:void 0;if(!BS.has(s))return dn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return dn("action_not_legal",r,n);if(s==="bid"){let d=qS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var BS=new Set(["bid","challenge"]);function qS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ni(t.data)?t.data:void 0,i=Ka(o,"min_quantity"),s=Ka(o,"min_face"),a=Ka(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function US(t){let e=t.match(FS);return e?e[1].trim():t}function ni(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ka(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var HS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,GS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Ya(t,e,n=500){let r=t.trim(),o=VS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!Kn(i))return fn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return fn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return fn("missing_fields",r,n);let l=Kn(c)?c:void 0;if(!GS.has(s))return fn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return fn("action_not_legal",r,n);let d=WS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}function WS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Uf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>zS(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=KS(o.data,"return_indices");return i!==void 0&&JS(i,r)})}default:return e[0]}}function VS(t){let e=t.match(HS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function zS(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function KS(t,e){if(!Kn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function JS(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var Se="0.1.0-alpha.3",Jf="v1.0.0";function Yf(){let t=ir(),e=qt(),n=yi();return{ok:!0,runtimeVersion:Se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Qa(t,e){return J(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:Se})+`
|
|
68
|
-
`):e.stdout(`${
|
|
69
|
-
`),0}import Hr from"node:fs";import
|
|
70
|
-
`,{mode:384}),Hr.renameSync(n,e),process.platform!=="win32")try{Hr.chmodSync(e,384)}catch{}}function
|
|
67
|
+
`)}}],wP=xd[xd.length-1].version;import{Entry as SP}from"@napi-rs/keyring";var Cd="AIFIGHT_KEYCHAIN_V1:",Id="AIFIGHT_CRYPTO_V1:";var $P=Buffer.byteLength(Cd,"ascii"),RP=Buffer.byteLength(Id,"ascii");var uS=xe(Af(),1),dS=xe(Yo(),1),fS=xe(Un(),1),mS=xe(ka(),1),pS=xe(Pa(),1),hS=xe(Oa(),1),La=xe(ei(),1),gS=xe(Mf(),1);var me=class extends Error{},Nt=class extends me{kind="connect";cause;constructor(e,n){super(e),this.name="WSConnectError",this.cause=n}},Lt=class extends me{kind="handshake";statusCode;responseBody;cause;constructor(e,n,r,o){super(r),this.name="WSHandshakeError",this.statusCode=e,this.responseBody=n,this.cause=o}},cn=class extends me{kind="welcome-timeout";constructor(e){super(e),this.name="WSWelcomeTimeoutError"}},Mt=class extends me{kind="welcome-invalid";ajvErrors;constructor(e,n){super(n),this.name="WSWelcomeInvalidError",this.ajvErrors=e}},ln=class extends me{kind="protocol-version";clientVersion;serverVersion;constructor(e,n,r){super(r),this.name="WSProtocolVersionError",this.clientVersion=e,this.serverVersion=n}},un=class extends me{kind="closed";constructor(e){super(e),this.name="WSClosedError"}},Re=class extends me{kind="schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSSchemaError",this.messageType=e,this.ajvErrors=n}},rt=class extends me{kind="outbound-schema";messageType;ajvErrors;constructor(e,n,r){super(r),this.name="WSOutboundSchemaError",this.messageType=e,this.ajvErrors=n}},wt=class extends me{kind="unknown-message";messageType;constructor(e,n){super(n),this.name="WSUnknownMessageError",this.messageType=e}},vt=class extends me{kind="aborted";cause;constructor(e,n){super(e),this.name="WSAbortedError",this.cause=n}};var jf=xe(Bo(),1),Df=xe(fa(),1);var ja=new Set(["join_queue","leave_queue","match_confirm","action","runtime_status"]),Da=new Set(["welcome","queue_joined","queue_left","match_confirm_request","match_cancelled","game_start","readiness_check","action_request","event","game_state","game_over","error"]),Ff="https://aifight.ai/protocol/v1/messages/";function yS(t){return`${Ff}client_${t}.schema.json`}function _S(t){return`${Ff}server_${t}.schema.json`}var Ma=null;function Bf(){if(Ma)return Ma;let t=new jf.default({strict:!1,allErrors:!0});(0,Df.default)(t);for(let[e,n]of qt())t.getSchema(e)||t.addSchema(n,e);return Ma=t,t}function Uf(t){return(t.errors??[]).map(n=>({instancePath:n.instancePath,message:n.message??void 0}))}function qf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hf(t){if(!qf(t))throw new rt("<unknown>",[],"serializeClientMessage: envelope must be a plain object");let e=t.type;if(typeof e!="string"||e.length===0)throw new rt("<unknown>",[],"serializeClientMessage: envelope is missing a string `type` field");if(Da.has(e))throw new rt(e,[],`serializeClientMessage: '${e}' is a server-only message type and cannot be sent by the client`);if(!ja.has(e))throw new rt(e,[],`serializeClientMessage: unknown client message type '${e}' (known: ${[...ja].join(", ")})`);let n=Bf(),r=yS(e),o=n.getSchema(r);if(!o)throw new rt(e,[],`serializeClientMessage: schema not registered for $id ${r} (packaging bug \u2014 loadAllSchemas did not include this file)`);if(!o(t))throw new rt(e,Uf(o),`serializeClientMessage: '${e}' envelope failed schema validation`);return JSON.stringify(t)}function Fa(t){let e=typeof t=="string"?t:t.toString("utf8"),n;try{n=JSON.parse(e)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Re("<unknown>",[],`parseServerFrame: malformed JSON: ${l}`)}if(!qf(n))throw new Re("<unknown>",[],"parseServerFrame: frame must be a JSON object");let r=n.type;if(typeof r!="string"||r.length===0)throw new Re("<unknown>",[],"parseServerFrame: frame is missing a string `type` field");if(!Da.has(r))throw ja.has(r)?new wt(r,`parseServerFrame: '${r}' is a client-only message type and was not expected on the inbound channel`):new wt(r,`parseServerFrame: unknown server message type '${r}' (known: ${[...Da].join(", ")})`);let o=Bf(),i=_S(r),s=o.getSchema(i);if(!s)throw new Re(r,[],`parseServerFrame: schema not registered for $id ${i} (packaging bug)`);if(!s(n))throw new Re(r,Uf(s),`parseServerFrame: '${r}' frame failed schema validation`);return n}var wS=1e4,vS=25e3;function Gf(t){if(t===void 0)return"(no reason)";if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return String(t)}catch{return"(unstringifiable reason)"}}var Ba=class{#e;#t="connected";#n=null;#r=null;#o=null;#a=new Set;#c=new Set;#u=new Set;#g=!1;#d=null;#l=null;#i=null;welcome;constructor(e,n,r){this.#e=e,this.welcome=n,this.#e.on("message",i=>{this.#s(i)}),this.#e.on("error",()=>{}),this.#e.once("close",(i,s)=>{let a=s?.toString("utf8")??"",c=this.#d??"server";this.#y({code:i,reason:a,initiator:c}),this.#t="closed",this.#_(),this.#i&&(this.#i(),this.#i=null)});let o=r.pingIntervalMs??vS;o>0&&(this.#n=setInterval(()=>{try{this.#e.ping()}catch{this.#n&&(clearInterval(this.#n),this.#n=null)}},o)),r.signal&&(this.#r=r.signal,this.#o=()=>{if(this.#t!=="closed"){this.#d="abort",this.#y({code:0,reason:"aborted",initiator:"abort"}),this.#t="closed",this.#_();try{this.#e.terminate()}catch{}}},r.signal.addEventListener("abort",this.#o,{once:!0}))}get state(){return this.#t}onMessage(e){return this.#a.add(e),()=>{this.#a.delete(e)}}onError(e){return this.#c.add(e),()=>{this.#c.delete(e)}}onClose(e){return this.#u.add(e),()=>{this.#u.delete(e)}}#s(e){if(this.#t!=="connected")return;let n=typeof e=="string"||Buffer.isBuffer(e)?e:Buffer.from(e),r;try{r=Fa(n)}catch(o){if(o instanceof Re||o instanceof wt)this.#m(o);else{let i=o instanceof Error?o.message:String(o);this.#m(new Re("<unknown>",[],`unexpected frame parse error: ${i}`))}return}this.#h(r)}#h(e){let n=[...this.#a];for(let r of n)this.#p(()=>r(e))}#m(e){let n=[...this.#c];for(let r of n)this.#p(()=>r(e))}#y(e){if(this.#g)return;this.#g=!0;let n=[...this.#u];for(let r of n)this.#p(()=>r(e))}#p(e){try{let n=e();n&&typeof n.then=="function"&&n.then(void 0,()=>{})}catch{}}send(e){if(this.#t!=="connected")throw new un(`cannot send: client state is "${this.#t}" (expected "connected")`);let n=Hf(e);this.#e.send(n)}#_(){this.#n&&(clearInterval(this.#n),this.#n=null),this.#r&&this.#o&&(this.#r.removeEventListener("abort",this.#o),this.#r=null,this.#o=null)}async close(e=1e3,n=""){if(this.#t!=="closed"){if(this.#t==="closing"){this.#l&&await this.#l;return}this.#d="client",this.#t="closing",this.#_(),this.#l=new Promise(r=>{this.#i=r});try{this.#e.close(e,n)}catch{this.#y({code:e,reason:n,initiator:"client"}),this.#t="closed",this.#i&&(this.#i(),this.#i=null)}await this.#l}}};async function Ua(t){let e=t.welcomeTimeoutMs??wS;return t.signal?.aborted?Promise.reject(new vt(`createWSClient aborted before start: ${Gf(t.signal.reason)}`,t.signal.reason)):new Promise((n,r)=>{let o;try{o=new La.default(t.url,{headers:{"X-API-Key":t.apiKey}})}catch(u){let d=u instanceof Error?u.message:String(u);r(new Nt(`failed to construct WebSocket for ${t.url}: ${d}`,u));return}let i=!1,s=null,a=null,c=()=>{s&&(clearTimeout(s),s=null),t.signal&&a&&(t.signal.removeEventListener("abort",a),a=null),o.removeAllListeners(),o.on("error",()=>{})},l=u=>{i||(i=!0,c(),u())};t.signal&&(a=()=>{l(()=>{try{o.terminate()}catch{}r(new vt(`createWSClient aborted during handshake: ${Gf(t.signal.reason)}`,t.signal.reason))})},t.signal.addEventListener("abort",a,{once:!0})),o.once("error",u=>{l(()=>{try{o.terminate()}catch{}r(new Nt(`WebSocket connect failed for ${t.url}: ${u.message}`,u))})}),o.once("unexpected-response",(u,d)=>{let h="";d.setEncoding("utf8"),d.on("data",p=>{h+=p}),d.on("end",()=>{let p=d.statusCode??0,f=d.statusMessage??"";try{u.destroy()}catch{}l(()=>r(new Lt(p,h,`HTTP upgrade rejected: ${p} ${f}`.trim())))}),d.on("error",p=>{let f=d.statusCode??0;l(()=>r(new Lt(f,h,`HTTP upgrade response read failed: ${p.message}`,p)))})}),o.once("open",()=>{s=setTimeout(()=>{l(()=>{try{o.terminate()}catch{}r(new cn(`welcome did not arrive within ${e}ms after WebSocket open`))})},e)}),o.once("message",u=>{let d=typeof u=="string"||Buffer.isBuffer(u)?u:Buffer.from(u),h;try{h=Fa(d)}catch(v){let S=[],R="first frame failed to parse";v instanceof Re?(S=v.ajvErrors,R=v.messageType==="welcome"?`welcome failed schema validation: ${v.message}`:`first frame parse failure (${v.messageType}): ${v.message}`):v instanceof wt?R=`first frame had unknown server message type '${v.messageType}': ${v.message}`:v instanceof Error&&(R=`first frame parse error: ${v.message}`),l(()=>{try{o.terminate()}catch{}r(new Mt(S,R))});return}if(h.type!=="welcome"){l(()=>{try{o.terminate()}catch{}r(new Mt([],`expected first frame to be 'welcome', got '${h.type}'`))});return}let p=h,f=p.data.server_protocol_version,m=v=>v.startsWith("v")?v.slice(1):v,g=m(t.expectedProtocolVersion).split(".")[0],y=m(f).split(".")[0];if(g!==y){l(()=>{try{o.terminate()}catch{}r(new ln(t.expectedProtocolVersion,f,`protocol major version mismatch: client expected '${t.expectedProtocolVersion}', server is '${f}'`))});return}l(()=>{let v=new Ba(o,p,{pingIntervalMs:t.pingIntervalMs,signal:t.signal});n(v)})})})}var zn=class extends Error{name="ReconnectStoppedError";kind;cause;constructor(e,n,r){super(r),this.kind=e,this.cause=n}},bS=1e3,SS=2,ES=3e4,kS="full",$S=5*60*1e3,RS=15*60*1e3,PS=new Set([1001,1006,1011,1012]);function AS(t,e,n,r){let o=e*Math.pow(n,Math.max(0,t-1));return Math.min(o,r)}function TS(t,e){switch(e){case"none":return t;case"full":return Math.floor(Math.random()*t);case"equal":return Math.floor(t/2+Math.random()*t/2)}}function xS(t){return t.code>=4e3&&t.code<5e3?!1:PS.has(t.code)}function CS(t){if(t instanceof vt||t instanceof Mt||t instanceof ln)return!1;if(t instanceof Nt||t instanceof cn)return!0;if(t instanceof Lt){let e=t.statusCode;return e===401||e===403||e===404?!1:e===408||e===429||e>=500&&e<600}return!1}function IS(t){return t>=RS?"error":t>=$S?"warning":"info"}var qa=class{state="connecting";attempt=0;welcome=null;#e;#t=null;#n=new Set;#r=new Set;#o=new Set;#a=new Set;#c=0;#u=0;#g=null;#d=null;#l=!1;#i=null;#s=!1;#h=null;#m=[];constructor(e){this.#e=e}send(e){if(this.state!=="connected"||this.#t===null)throw new un(`cannot send while ReconnectingWSClient.state="${this.state}"`);this.#t.send(e)}onMessage(e){this.#n.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onMessage(e)),()=>{this.#n.delete(e),n&&n()}}onError(e){this.#r.add(e);let n=null;return this.#t!==null&&this.state==="connected"&&(n=this.#t.onError(e)),()=>{this.#r.delete(e),n&&n()}}onClose(e){return this.#o.add(e),()=>{this.#o.delete(e)}}onReconnect(e){return this.#a.add(e),()=>{this.#a.delete(e)}}async close(e,n){this.state!=="closed"&&(this.#i={code:e,reason:n},this.#h&&this.#h("close"),this.#t!==null?await this.#t.close(e,n).catch(()=>{}):this.#s||this.#f({kind:"caller-close",code:e??1e3,closeReason:n,cause:void 0}))}begin(e,n){this.#g=e,this.#d=n,this.#y()}async#y(){if(this.#c=Date.now(),this.#e.signal?.aborted){this.#S("signal",void 0,"ReconnectingWSClient pre-aborted by signal");return}for(;this.state!=="closed";){this.attempt++,this.state="connecting",this.#b("attempt-start",this.attempt);let e,n=!1;try{let a=await Ua({url:this.#e.url,apiKey:this.#e.apiKey,expectedProtocolVersion:this.#e.expectedProtocolVersion,welcomeTimeoutMs:this.#e.welcomeTimeoutMs,pingIntervalMs:this.#e.pingIntervalMs,signal:this.#e.signal});n=!0,this.#t=a,this.welcome=a.welcome,this.#E(a),this.state="connected";let c=this.attempt;this.attempt=0,this.#u=0,this.#b("attempt-success",c),this.#l||(this.#l=!0,this.#g?.());let l=await this.#_(a);if(this.#w(),this.#t=null,this.#i){this.#f({kind:"caller-close",code:this.#i.code??l.code,closeReason:this.#i.reason??l.reason,cause:void 0});return}if(this.#e.signal?.aborted){this.#f({kind:"signal",cause:void 0});return}if(!xS(l)){let u=new zn("fatal-close",void 0,`close code ${l.code} not in retry whitelist`);this.#f({kind:"fatal-close",code:l.code,closeReason:l.reason,cause:u});return}this.#u=1,this.state="backoff",this.#c=Date.now()}catch(a){if(n)throw a;if(a instanceof me&&(e=a),!CS(a)){let c=a instanceof me?a:void 0,l=a instanceof vt?"signal":"fatal-error",u=a instanceof Error?a.message:"non-retriable error";this.#S(l,c,u);return}this.#u++,this.state="backoff"}let r=AS(this.#u,this.#e.initialBackoffMs??bS,this.#e.backoffFactor??SS,this.#e.maxBackoffMs??ES),o=TS(r,this.#e.jitter??kS),i=this.attempt===0?1:this.attempt;if(this.#b("attempt-failure",i,o,e),this.#e.maxAttempts!==void 0&&this.#u>=this.#e.maxAttempts){this.#S("max-attempts",e,`exhausted maxAttempts=${this.#e.maxAttempts}`);return}let s=await this.#p(o);if(s==="abort"){this.#f({kind:"signal",cause:void 0}),this.#l||(this.#l=!0,this.#d?.(new zn("signal",void 0,"ReconnectingWSClient aborted during backoff")));return}if(s==="close"){this.#f({kind:"caller-close",code:this.#i?.code??1e3,closeReason:this.#i?.reason,cause:void 0});return}}}#p(e){return new Promise(n=>{let r=!1,o=c=>{r||(r=!0,clearTimeout(i),s&&a&&s.removeEventListener("abort",a),this.#h=null,n(c))},i=setTimeout(()=>o("timeout"),e),s=this.#e.signal,a=null;if(s){if(s.aborted){o("abort");return}a=()=>o("abort"),s.addEventListener("abort",a)}this.#h=c=>o(c)})}#_(e){return new Promise(n=>{let r=e.onClose(o=>{try{r()}catch{}n(o)})})}#E(e){this.#w();for(let n of this.#n)this.#m.push(e.onMessage(n));for(let n of this.#r)this.#m.push(e.onError(n))}#w(){for(let e of this.#m)try{e()}catch{}this.#m.length=0}#b(e,n,r,o){let i=Date.now()-this.#c,s=e==="give-up"?"error":e==="attempt-failure"?IS(i):"info",a={type:e,attempt:n,nextDelayMs:r,cause:o,elapsedMs:i,severity:s},c=[...this.#a];for(let l of c)try{l(a)}catch{}}#S(e,n,r){let o=new zn(e,n,r);this.#f({kind:e,cause:e==="fatal-error"||e==="max-attempts"?o:void 0}),this.#l||(this.#l=!0,this.#d?.(o))}#f(e){if(this.#s)return;this.#s=!0,this.state="closed",this.#w(),this.#t=null,this.#b("give-up",this.attempt,void 0,e.cause);let n=[...this.#o];for(let r of n)try{r(e)}catch{}}};async function Ha(t){let e=new qa(t);return await new Promise((n,r)=>{e.begin(n,r)}),e}var OS=["check","call","fold","raise","allin"];function Ga(t){let{legalActions:e}=t;if(e.length===0)throw new Error("Texas Hold'em fallback requires at least one legal action");for(let n of OS){let r=e.find(o=>o.type===n);if(r)return r}return e[0]}function Wa(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Liar's Dice fallback requires at least one legal action");let r=n.find(i=>i.type==="bid"),o=n.find(i=>i.type==="challenge");if(r){let i=NS(r.data);if(i)return i.maxQuantity!==void 0&&i.minQuantity>i.maxQuantity?o??n[0]:{type:"bid",data:{quantity:i.minQuantity,face:i.minFace}};let s=LS(e);if(s)return typeof e.total_dice=="number"&&s.quantity>e.total_dice?o??n[0]:{type:"bid",data:s}}return o||n[0]}function NS(t){let e=MS(t);if(!e)return;let n=Va(e,"min_quantity"),r=Va(e,"min_face");if(!(n===void 0||r===void 0))return{minQuantity:n,minFace:r,maxQuantity:Va(e,"max_quantity")}}function LS(t){let e=t.current_bid;if(!e)return typeof t.total_dice!="number"?void 0:{quantity:1,face:1};if(!(typeof e.quantity!="number"||typeof e.face!="number"))return e.face<6?{quantity:e.quantity,face:e.face+1}:{quantity:e.quantity+1,face:1}}function MS(t){return t!==null&&typeof t=="object"?t:void 0}function Va(t,e){let n=t[e];return typeof n=="number"?n:void 0}var jS=["income","foreign_aid","coup","tax","steal","assassinate","exchange"],DS=["pass","challenge"],FS=["pass","block"],BS=["lose_card"],US=["return_cards"];function za(t){let{publicState:e,legalActions:n}=t;if(n.length===0)throw new Error("Coup fallback requires at least one legal action");switch(e.phase){case"action":return qr(n,jS);case"challenge_action":case"challenge_block":return qr(n,DS);case"block":return qr(n,FS);case"lose_influence":return qr(n,BS);case"exchange_return":return qr(n,US);case"done":throw new Error("Coup fallback should not run when phase is done");default:return n[0]}}function qr(t,e){for(let n of e){let r=t.find(o=>o.type===n);if(r)return r}return t[0]}var qS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Ja(t,e,n=500){let r=t.trim(),o=VS(r),i;try{i=JSON.parse(o)}catch{return dn("json_parse",r,n)}if(!ni(i))return dn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return dn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ni(c))return dn("missing_fields",r,n);let l=ni(c)?c:void 0;if(!HS.has(s))return dn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return dn("action_not_legal",r,n);if(s==="raise"){let d=GS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:dn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var HS=new Set(["fold","check","call","raise","allin"]);function GS(t,e){if(!e)return;let n=e.amount;if(typeof n!="number"||!Number.isFinite(n))return;let r=ni(t.data)?t.data:void 0,o=Ka(r,"amount"),i=Ka(r,"min")??o,s=Ka(r,"max")??o;if(!(i!==void 0&&n<i)&&!(s!==void 0&&n>s))return{type:"raise",data:{amount:n}}}function VS(t){let e=t.match(qS);return e?e[1].trim():t}function ni(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ka(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function dn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var WS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/;function Qa(t,e,n=500){let r=t.trim(),o=JS(r),i;try{i=JSON.parse(o)}catch{return fn("json_parse",r,n)}if(!ri(i))return fn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return fn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!ri(c))return fn("missing_fields",r,n);let l=ri(c)?c:void 0;if(!zS.has(s))return fn("unknown_action_type",r,n);let u=e.find(d=>d.type===s);if(!u)return fn("action_not_legal",r,n);if(s==="bid"){let d=KS(u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:fn("data_validation",r,n)}return a!==void 0?{kind:"ok",action:u,summary:a}:{kind:"ok",action:u}}var zS=new Set(["bid","challenge"]);function KS(t,e){if(!e)return;let n=e.quantity,r=e.face;if(typeof n!="number"||!Number.isFinite(n)||!Number.isInteger(n)||typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)||r<1||r>6||n<1)return;let o=ri(t.data)?t.data:void 0,i=Ya(o,"min_quantity"),s=Ya(o,"min_face"),a=Ya(o,"max_quantity");if(!(i!==void 0&&n<i)&&!(a!==void 0&&n>a)&&!(i!==void 0&&s!==void 0&&n===i&&r<s))return{type:"bid",data:{quantity:n,face:r}}}function JS(t){let e=t.match(WS);return e?e[1].trim():t}function ri(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ya(t,e){if(!t)return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function fn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var YS=/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/,QS=new Set(["income","foreign_aid","coup","tax","assassinate","steal","exchange","challenge","pass","block","lose_card","return_cards"]);function Xa(t,e,n=500){let r=t.trim(),o=ZS(r),i;try{i=JSON.parse(o)}catch{return mn("json_parse",r,n)}if(!Kn(i))return mn("missing_fields",r,n);let s=i.action;if(typeof s!="string")return mn("missing_fields",r,n);let a=typeof i.summary=="string"?i.summary:void 0,c=i.data;if(c!=null&&!Kn(c))return mn("missing_fields",r,n);let l=Kn(c)?c:void 0;if(!QS.has(s))return mn("unknown_action_type",r,n);let u=e.filter(h=>h.type===s);if(u.length===0)return mn("action_not_legal",r,n);let d=XS(s,u,l);return d?a!==void 0?{kind:"ok",action:d,summary:a}:{kind:"ok",action:d}:mn("data_validation",r,n)}function XS(t,e,n){switch(t){case"coup":case"assassinate":case"steal":{let r=n?.target;return typeof r!="string"?void 0:e.find(o=>Vf(o.data,"target")===r)}case"block":{let r=n?.role;return typeof r!="string"?void 0:e.find(o=>Vf(o.data,"role")===r)}case"lose_card":{let r=n?.card_index;return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?void 0:e.find(o=>e0(o.data,"card_index")===r)}case"return_cards":{let r=n?.return_indices;return!Array.isArray(r)||!r.every(o=>typeof o=="number"&&Number.isFinite(o)&&Number.isInteger(o))?void 0:e.find(o=>{let i=t0(o.data,"return_indices");return i!==void 0&&n0(i,r)})}default:return e[0]}}function ZS(t){let e=t.match(YS);return e?e[1].trim():t}function Kn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vf(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="string"?n:void 0}function e0(t,e){if(!Kn(t))return;let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function t0(t,e){if(!Kn(t))return;let n=t[e];if(Array.isArray(n)&&n.every(r=>typeof r=="number"&&Number.isFinite(r)))return n}function n0(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function mn(t,e,n){return{kind:"invalid",reason:t,rawSnippet:e.length>n?e.slice(0,n):e}}var se="0.1.0-alpha.6",Xf="v1.0.0";function Zf(){let t=ir(),e=qt(),n=wi();return{ok:!0,runtimeVersion:se,schemaCount:e.size,messageTypeCount:n.length,schemasRoot:t}}async function Za(t,e){return W(t,0,0,"usage: aifight version"),t.jsonMode?e.stdout(JSON.stringify({version:se})+`
|
|
68
|
+
`):e.stdout(`${se}
|
|
69
|
+
`),0}import Hr from"node:fs";import i0 from"node:path";var Ge=class extends Error{name="RuntimeLocalUrlError"};function Jn(t){switch(t){case"openclaw":return"http://127.0.0.1:18789";case"hermes":return"http://127.0.0.1:8642";case"mock":return"mock://local"}}function Gr(t,e){let n=t.trim();if(e==="mock"&&n==="mock://local")return n;let r;try{r=new URL(n)}catch{throw new Ge("runtime URL must be a valid localhost HTTP URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Ge("runtime URL must use http:// or https://");if(!l0(r.hostname))throw new Ge("runtime URL must point to localhost, 127.0.0.1, or [::1]");if(r.username!==""||r.password!=="")throw new Ge("runtime URL must not include credentials");if(r.pathname!==""&&r.pathname!=="/"||r.search!==""||r.hash!=="")throw new Ge("runtime URL must be a base URL without path, query, or fragment");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function jt(t){switch(t){case"openclaw":return"openclaw/default";case"hermes":return"hermes-agent";case"mock":return"mock"}}function tc(){return i0.join(oe(),"bridge.json")}function em(){Hr.rmSync(tc(),{force:!0})}function pn(t){at();let e=tc(),n=`${e}.tmp`;if(Hr.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
70
|
+
`,{mode:384}),Hr.renameSync(n,e),process.platform!=="win32")try{Hr.chmodSync(e,384)}catch{}}function ne(){let t=tc(),e;try{e=Hr.readFileSync(t,"utf8")}catch(r){throw r.code==="ENOENT"?new Error("bridge is not configured; run `aifight register` for a new agent or `aifight connect <PAIRING_CODE>` for an existing agent"):r}let n=JSON.parse(e);if(!a0(n))throw new Error("bridge config is invalid; run connect again");return n}function Dt(t){return{...t,apiKey:ec(t.apiKey),...t.claimUrl!==void 0?{claimUrl:s0(t.claimUrl)}:{},...t.claimToken!==void 0?{claimToken:ec(t.claimToken)}:{},...t.runtimeLocalToken!==void 0?{runtimeLocalToken:ec(t.runtimeLocalToken)}:{}}}function ec(t){return t.length<=8?"***":`${t.slice(0,4)}...${t.slice(-4)}`}function s0(t){try{let e=new URL(t),n=e.pathname.split("/"),r=n.at(-1);return r&&r.length>0&&(n[n.length-1]="<redacted>",e.pathname=n.join("/")),e.toString()}catch{return"<redacted>"}}function a0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.baseUrl=="string"&&typeof e.wsUrl=="string"&&typeof e.agentId=="string"&&typeof e.agentName=="string"&&(e.suggestedName===void 0||typeof e.suggestedName=="string")&&typeof e.apiKey=="string"&&(e.claimUrl===void 0||typeof e.claimUrl=="string")&&(e.claimToken===void 0||typeof e.claimToken=="string")&&(e.runtimeType==="openclaw"||e.runtimeType==="hermes"||e.runtimeType==="mock")&&typeof e.runtimeLocalUrl=="string"&&c0(e.runtimeLocalUrl,e.runtimeType)&&typeof e.updatedAt=="string"&&(e.runtimeLocalToken===void 0||typeof e.runtimeLocalToken=="string")&&(e.runtimeModel===void 0||typeof e.runtimeModel=="string")&&(e.autoDailyLimit===void 0||typeof e.autoDailyLimit=="number"&&Number.isInteger(e.autoDailyLimit)&&e.autoDailyLimit>=0)&&(e.autoGames===void 0||Array.isArray(e.autoGames)&&e.autoGames.every(n=>typeof n=="string"))}function c0(t,e){if(e!=="openclaw"&&e!=="hermes"&&e!=="mock")return!1;try{return Gr(t,e),!0}catch{return!1}}function l0(t){let e=t.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}var u0="npm install -g @aifight/aifight@alpha";async function je(t){let e=t.fetchImpl??globalThis.fetch,n=t.timeoutMs??1500,r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await e(`${f0(t.baseUrl)}/api/bridge/version`,{method:"GET",signal:r.signal});if(!i.ok)return nc(t.currentVersion,`version check returned HTTP ${i.status}`);let s=await i.json().catch(()=>{}),a=m0(s);return a===null?nc(t.currentVersion,"version check returned invalid policy"):d0(t.currentVersion,a)}catch(i){let s=i?.name;return nc(t.currentVersion,s==="AbortError"?"version check timed out":"version check unavailable")}finally{clearTimeout(o)}}function d0(t,e){let n=tm(t,e.minimumSupportedVersion);if(n!==null&&n<0)return{status:"unsupported",currentVersion:t,policy:e,message:`Bridge ${t} is below the minimum supported version ${e.minimumSupportedVersion}. Update before joining matches.`};let r=tm(t,e.recommendedVersion);return r!==null&&r<0?{status:"update_recommended",currentVersion:t,policy:e,message:`Bridge ${t} works, but ${e.recommendedVersion} is recommended.`}:n===null||r===null?{status:"unknown",currentVersion:t,policy:e,message:"Bridge version could not be compared with the platform policy."}:{status:"current",currentVersion:t,policy:e,message:`Bridge ${t} is current enough for AIFight.`}}function nc(t,e){return{status:"unknown",currentVersion:t,message:e}}function f0(t){return t.replace(/\/+$/,"")}function m0(t){if(!t||typeof t!="object")return null;let e=t,n=e.minimum_supported_version,r=e.recommended_version,o=e.latest_version;return typeof n!="string"||typeof r!="string"||typeof o!="string"?null:{minimumSupportedVersion:n,recommendedVersion:r,latestVersion:o,updateCommand:typeof e.update_command=="string"&&e.update_command.trim()!==""?e.update_command:u0,...typeof e.release_notes_url=="string"?{releaseNotesUrl:e.release_notes_url}:{},...typeof e.policy=="string"?{policy:e.policy}:{}}}function tm(t,e){let n=nm(t),r=nm(e);if(n===null||r===null)return null;for(let o of["major","minor","patch"])if(n[o]!==r[o])return n[o]>r[o]?1:-1;return p0(n.prerelease,r.prerelease)}function nm(t){let e=t.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);return e===null?null:{major:Number.parseInt(e[1],10),minor:Number.parseInt(e[2],10),patch:Number.parseInt(e[3],10),prerelease:e[4]===void 0?[]:e[4].split(".")}}function p0(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;let n=Math.max(t.length,e.length);for(let r=0;r<n;r++){let o=t[r],i=e[r];if(o===void 0)return-1;if(i===void 0)return 1;if(o===i)continue;let s=/^\d+$/.test(o)?Number.parseInt(o,10):null,a=/^\d+$/.test(i)?Number.parseInt(i,10):null;return s!==null&&a!==null?s>a?1:-1:s!==null?-1:a!==null||o>i?1:-1}return 0}var h0=1500;async function rm(t,e){W(t,0,0,"usage: aifight doctor");let n;try{n=(e.hello??Zf)()}catch(i){return t.jsonMode?e.stderr(JSON.stringify({error:{code:"client_doctor_schema",message:i.message}})+`
|
|
71
71
|
`):e.stderr(`aifight doctor FAILED: ${i.message}
|
|
72
|
-
`),1}let r=await
|
|
73
|
-
`),0;let o=[];return o.push("aifight doctor:"),o.push(` version : ${n.runtimeVersion}`),o.push(` node : ${process.versions.node}`),o.push(` platform : ${process.platform}-${process.arch}`),o.push(` bridge config : ${r.config}`),r.runtime!==void 0&&o.push(` runtime probe : ${r.runtime.status}${r.runtime.detail?` (${r.runtime.detail})`:""}`),r.update!==void 0&&(o.push(` version policy : ${r.update.message}`),(r.update.status==="update_recommended"||r.update.status==="unsupported")&&o.push(
|
|
74
|
-
`)),0}async function
|
|
75
|
-
`)}function
|
|
76
|
-
`)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function
|
|
77
|
-
`)[0];if(i)return
|
|
78
|
-
`)[0]??"unknown error"}function
|
|
79
|
-
`);async function
|
|
72
|
+
`),1}let r=await g0(n.runtimeVersion,e.fetchImpl??globalThis.fetch);if(t.jsonMode)return e.stdout(JSON.stringify({runtimeVersion:n.runtimeVersion,messageTypeCount:n.messageTypeCount,schemaCount:n.schemaCount,schemasRoot:n.schemasRoot,node:process.versions.node,platform:`${process.platform}-${process.arch}`,bridge:r})+`
|
|
73
|
+
`),0;let o=[];return o.push("aifight doctor:"),o.push(` version : ${n.runtimeVersion}`),o.push(` node : ${process.versions.node}`),o.push(` platform : ${process.platform}-${process.arch}`),o.push(` bridge config : ${r.config}`),r.runtime!==void 0&&o.push(` runtime probe : ${r.runtime.status}${r.runtime.detail?` (${r.runtime.detail})`:""}`),r.update!==void 0&&(o.push(` version policy : ${r.update.message}`),(r.update.status==="update_recommended"||r.update.status==="unsupported")&&(o.push(" update command : aifight update --yes"),o.push(` manual npm : ${r.update.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}`))),o.push(""),e.stdout(o.join(`
|
|
74
|
+
`)),0}async function g0(t,e){try{let n=ne(),r=await je({baseUrl:n.baseUrl,currentVersion:t,fetchImpl:e});return{config:`configured for ${n.agentName} (${n.runtimeType})`,redactedConfig:Dt(n),runtime:await y0(n,e),update:r}}catch(n){let r=n.message;return r.includes("bridge is not configured")?{config:"not configured"}:{config:`invalid (${r})`}}}async function y0(t,e){if(t.runtimeLocalUrl.startsWith("mock://"))return{status:"mock runtime configured"};let n=t.runtimeLocalUrl.replace(/\/+$/,""),r=t.runtimeModel??jt(t.runtimeType),o=new AbortController,i=setTimeout(()=>o.abort(),h0);try{let s=await e(`${n}/v1/responses`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json",...t.runtimeLocalToken?{Authorization:`Bearer ${t.runtimeLocalToken}`}:{}},body:JSON.stringify({model:r,input:'AIFight doctor health check. Return only JSON: {"action":"pass"}'})}),a=_0(t.runtimeType);return s.ok?{status:"ready",detail:`${a} /v1/responses HTTP ${s.status}`}:{status:"not ready",detail:`${a} /v1/responses HTTP ${s.status}; ${w0(t.runtimeType,s.status)}`}}catch(s){return{status:s?.name==="AbortError"?"timeout":"not reachable"}}finally{clearTimeout(i)}}function _0(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function w0(t,e){return t==="openclaw"?e===404?"enable OpenClaw responses endpoint: openclaw config set gateway.http.endpoints.responses.enabled true --strict-json, then let Gateway restart or run openclaw gateway restart --safe":e===401||e===403?"check the local OpenClaw Gateway token passed with --runtime-token":"check OpenClaw Gateway logs and local model/provider config":t==="hermes"?e===401||e===403?"check Hermes API_SERVER_KEY and the local --runtime-token value":e===404?"confirm Hermes API Server is enabled in ~/.hermes/.env and restart Hermes; it does not hot-reload API_SERVER_*":"check Hermes API Server logs and local model/provider config":"check local runtime config"}import tE from"node:os";import{randomBytes as nE}from"node:crypto";import{execFile as v0}from"node:child_process";import Pe from"node:fs";import rc from"node:os";import bt from"node:path";import{promisify as b0}from"node:util";var Ft="aifight.service",oi="ai.aifight.service",Q=class extends Error{code;hint;constructor(e,n,r){super(n),this.name="BridgeServiceError",this.code=e,r!==void 0&&(this.hint=r)}},S0=b0(v0),Ve=async(t,e)=>{try{let{stdout:n,stderr:r}=await S0(t,[...e],{timeout:5e3,maxBuffer:131072});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}}catch(n){throw n}};async function oc(t={}){let e=await Qn(t),n=t.execFile??Ve;E0(e);try{if(e.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]);let o=await ic(t);return{...e,linger:"not_needed",...o?{warning:o}:{}}}let r=hn(e.platform);if(await n("systemctl",[...r,"daemon-reload"]),await n("systemctl",[...r,"enable","--now",Ft]),e.platform==="linux-systemd-user"){let o=await R0(t);return{...e,linger:o.status,...o.warning?{warning:o.warning}:{}}}return{...e,linger:"not_needed"}}catch(r){throw await P0(e,t),new Q("service_install_failed",`failed to install ${Ft}: ${Yn(r)}`,"The bridge can still run in the foreground with `aifight run`.")}}async function ii(t={}){let e=await Qn(t),n=t.execFile??Ve;if(e.platform==="darwin-launchd-user")return await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),e;let r=hn(e.platform);return await n("systemctl",[...r,"disable","--now",Ft]).catch(()=>{}),Pe.rmSync(e.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{}),e}async function am(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootstrap",ot(t),e.unitPath]).catch(()=>{}),await ic(t),e):(await n("systemctl",[...hn(e.platform),"start",Ft]),e)}async function cm(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),e):(await n("systemctl",[...hn(e.platform),"stop",Ft]),e)}async function zr(t={}){let e=await Qn(t),n=t.execFile??Ve;return e.platform==="darwin-launchd-user"?(await n("launchctl",["bootout",ot(t),e.unitPath]).catch(()=>{}),await n("launchctl",["bootstrap",ot(t),e.unitPath]),await ic(t),e):(await n("systemctl",[...hn(e.platform),"restart",Ft]),e)}async function St(t={}){let e=await Qn(t),n=t.execFile??Ve;if(!Pe.existsSync(e.unitPath))return{...e,installed:!1,running:null,detail:"not installed"};if(e.platform==="darwin-launchd-user")try{return await n("launchctl",["print",`${ot(t)}/${oi}`]),{...e,installed:!0,running:!0,detail:"running"}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}try{let i=(await n("systemctl",[...hn(e.platform),"is-active",Ft])).stdout.trim()||"active";return{...e,installed:!0,running:i==="active",detail:i}}catch(o){return{...e,installed:!0,running:!1,detail:Yn(o)}}}async function Qn(t={}){let e=t.platform??process.platform,n=t.uid??process.getuid?.()??0,r=t.homeDir??rc.homedir(),o=t.runtimeHome??oe(),i=await A0(t),s=T0(t);if(e==="linux")return await om("systemctl",["--version"],t),n===0?{platform:"linux-systemd-system",unitPath:t.systemdSystemUnitPath??"/etc/systemd/system/aifight.service",nodeExec:s,aifightExec:i,runtimeHome:o}:{platform:"linux-systemd-user",unitPath:t.systemdUserUnitPath??bt.join(r,".config","systemd","user","aifight.service"),nodeExec:s,aifightExec:i,runtimeHome:o};if(e==="darwin")return await om("launchctl",["version"],t),{platform:"darwin-launchd-user",unitPath:t.launchdPlistPath??bt.join(r,"Library","LaunchAgents","ai.aifight.service.plist"),nodeExec:s,aifightExec:i,runtimeHome:o};throw new Q("service_platform_unsupported",`automatic background service is not supported on ${e}`,"Run `aifight run` manually or use your own process manager.")}function E0(t){Pe.mkdirSync(bt.dirname(t.unitPath),{recursive:!0});let e=t.platform==="darwin-launchd-user"?$0(t):k0(t);C0(t.unitPath,e,t.platform==="linux-systemd-system"?420:384)}function k0(t){let e=t.platform==="linux-systemd-system"?"multi-user.target":"default.target";return["# Auto-generated by AIFight. Re-run `aifight service install` to refresh.","","[Unit]","Description=AIFight Agent Service","Documentation=https://aifight.ai/skill.md","Wants=network-online.target","After=network-online.target","","[Service]","Type=simple",`ExecStart=${im(t.nodeExec)} ${im(t.aifightExec)} run`,sm("AIFIGHT_RUNTIME_HOME",t.runtimeHome),sm("AIFIGHT_SERVICE_RUN","1"),"Restart=always","RestartSec=5","StandardOutput=journal","StandardError=journal","","[Install]",`WantedBy=${e}`,""].join(`
|
|
75
|
+
`)}function $0(t){let e=bt.dirname(t.unitPath).includes("LaunchAgents")?bt.join(rc.homedir(),"Library","Logs","aifight"):bt.join(bt.dirname(t.unitPath),"logs");return Pe.mkdirSync(e,{recursive:!0}),['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${oi}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Vr(t.nodeExec)}</string>`,` <string>${Vr(t.aifightExec)}</string>`," <string>run</string>"," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>AIFIGHT_RUNTIME_HOME</key>",` <string>${Vr(t.runtimeHome)}</string>`," <key>AIFIGHT_SERVICE_RUN</key>"," <string>1</string>"," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${Vr(bt.join(e,"service.out.log"))}</string>`," <key>StandardErrorPath</key>",` <string>${Vr(bt.join(e,"service.err.log"))}</string>`,"</dict>","</plist>",""].join(`
|
|
76
|
+
`)}function hn(t){return t==="linux-systemd-user"?["--user"]:[]}function ot(t){return`gui/${t.uid??process.getuid?.()??0}`}async function ic(t){let e=t.execFile??Ve,n=`${ot(t)}/${oi}`;try{await e("launchctl",["kickstart","-k",n]);return}catch(r){try{return await e("launchctl",["print",n]),`launchctl kickstart did not complete cleanly, but ${oi} is loaded: ${Yn(r)}`}catch{throw r}}}async function R0(t){let e=t.username??rc.userInfo().username;if(!e)return{status:"skipped",warning:"could not determine username for loginctl enable-linger"};let n=t.execFile??Ve;try{return await n("loginctl",["enable-linger",e]),{status:"enabled"}}catch(r){return{status:"failed",warning:`loginctl enable-linger ${e} failed: ${Yn(r)}`}}}async function P0(t,e){let n=e.execFile??Ve;if(t.platform==="darwin-launchd-user"){await n("launchctl",["bootout",ot(e),t.unitPath]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0});return}let r=hn(t.platform);await n("systemctl",[...r,"disable","--now",Ft]).catch(()=>{}),Pe.rmSync(t.unitPath,{force:!0}),await n("systemctl",[...r,"daemon-reload"]).catch(()=>{})}async function A0(t){let e=t.aifightExec;if(e!==void 0&&e.trim()!=="")return Wr(e);let n=process.argv[1];if(n!==void 0&&n!==""&&!x0(n))try{return Wr(n)}catch{}let r=t.execFile??Ve;try{let i=(await r("sh",["-lc","command -v aifight"])).stdout.trim().split(`
|
|
77
|
+
`)[0];if(i)return Wr(i)}catch{}throw new Q("service_exec_unresolved","could not resolve a stable `aifight` executable for the background service","Install with `npm install -g @aifight/aifight@alpha`, then run `aifight service install` again.")}function T0(t){let e=t.nodeExec;if(e!==void 0&&e.trim()!=="")return Wr(e);try{return Wr(process.execPath)}catch{throw new Q("service_exec_unresolved","could not resolve a stable Node.js executable for the background service","Install Node.js >=20.19 and rerun `aifight service install`.")}}function Wr(t){let e=Pe.realpathSync(t);return Pe.accessSync(e,Pe.constants.X_OK),e}function x0(t){return/[/\\](_npx|\.npm[/\\]_npx|npm-cache[/\\]_npx)[/\\]/.test(t)}async function om(t,e,n){let r=n.execFile??Ve;try{await r(t,e)}catch(o){throw new Q("service_manager_unavailable",`${t} is not available or not usable on this system: ${Yn(o)}`,"AIFight will keep running in the foreground; use your own process manager if needed.")}}function im(t){return/[\s"\\]/.test(t)?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function sm(t,e){return`Environment="${t}=${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function C0(t,e,n){let r=`${t}.${process.pid}.tmp`;Pe.writeFileSync(r,e,{mode:n}),process.platform!=="win32"&&Pe.chmodSync(r,n),Pe.renameSync(r,t)}function Yn(t){let e=t,n=typeof e.stderr=="string"&&e.stderr.trim()!==""?e.stderr:e.message;return String(n).trim().split(`
|
|
78
|
+
`)[0]??"unknown error"}function Vr(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var sc=["usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
|
|
79
|
+
`);async function um(t,e){W(t,1,1,sc);let n=t.positional[0],r=I0(t,"aifight-path");if(r!==void 0&&n!=="install")throw new O("--aifight-path is only supported with `aifight service install`",sc);try{switch(n){case"install":{ne();let o=r===void 0?e.bridgeService:{...e.bridgeService??{},aifightExec:r},i=await oc(o);return t.jsonMode?e.stdout(JSON.stringify({status:"installed",result:i})+`
|
|
80
80
|
`):(e.stdout(`aifight.service installed and started (${i.platform}).
|
|
81
81
|
`),e.stdout(`unit: ${i.unitPath}
|
|
82
82
|
`),i.warning&&e.stderr(`warning: ${i.warning}
|
|
83
|
-
`)),0}case"status":{let o=await
|
|
83
|
+
`)),0}case"status":{let o=await St(e.bridgeService);return t.jsonMode?e.stdout(JSON.stringify(o)+`
|
|
84
84
|
`):o.installed?(e.stdout(`aifight.service: ${o.running?"running":"stopped"} (${o.detail})
|
|
85
85
|
`),e.stdout(`unit: ${o.unitPath}
|
|
86
86
|
`)):(e.stdout(`aifight.service: not installed
|
|
87
87
|
`),e.stdout(`run: aifight service install
|
|
88
|
-
`)),0}case"start":{let o=await
|
|
89
|
-
`),0}case"stop":{let o=await
|
|
90
|
-
`),0}case"restart":{let o=await
|
|
91
|
-
`),0}case"uninstall":{let o=await
|
|
92
|
-
`),0}default:throw new O(`unknown service command '${n}'`,
|
|
88
|
+
`)),0}case"start":{let o=await am(e.bridgeService);return e.stdout(`aifight.service started (${o.platform}).
|
|
89
|
+
`),0}case"stop":{let o=await cm(e.bridgeService);return e.stdout(`aifight.service stopped (${o.platform}).
|
|
90
|
+
`),0}case"restart":{let o=await zr(e.bridgeService);return e.stdout(`aifight.service restarted (${o.platform}).
|
|
91
|
+
`),0}case"uninstall":{let o=await ii(e.bridgeService);return e.stdout(`aifight.service uninstalled (${o.platform}).
|
|
92
|
+
`),0}default:throw new O(`unknown service command '${n}'`,sc)}}catch(o){if(o instanceof O)throw o;if(o instanceof Q)return t.jsonMode?e.stderr(JSON.stringify({error:{code:o.code,message:o.message,...o.hint?{hint:o.hint}:{}}})+`
|
|
93
93
|
`):(e.stderr(`aifight: ${o.message}
|
|
94
94
|
`),o.hint&&e.stderr(`${o.hint}
|
|
95
95
|
`)),o.code==="service_platform_unsupported"||o.code==="service_manager_unavailable"?2:1;let i=o instanceof Error?o.message:String(o);return t.jsonMode?e.stderr(JSON.stringify({error:{code:"service_command_failed",message:i}})+`
|
|
96
96
|
`):e.stderr(`aifight: service command failed: ${i}
|
|
97
|
-
`),1}}function
|
|
98
|
-
`)),!(e.approvedLocalSetup===!0?!0:await
|
|
99
|
-
`);try{let i=await
|
|
97
|
+
`),1}}function I0(t,e){let n=t.flags[e];return typeof n=="string"?n:void 0}async function dm(t,e={}){if(!process.stdin.isTTY&&e.approvedLocalSetup!==!0)return"unavailable";let n=await O0(t);if(n?.installed&&n.running===!0){if(t.stdout(["aifight.service is already running.","AIFight just saved bridge credentials, so the service must reload them before the Dashboard can show the new Agent online.",""].join(`
|
|
98
|
+
`)),!(e.approvedLocalSetup===!0?!0:await lm(t,"Restart aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting aifight.service now.
|
|
99
|
+
`);try{let i=await zr(t.bridgeService);return t.stdout(`aifight.service restarted (${i.platform}).
|
|
100
100
|
`),t.stdout(`unit: ${i.unitPath}
|
|
101
|
-
`),"installed"}catch(i){let s=(i instanceof
|
|
101
|
+
`),"installed"}catch(i){let s=(i instanceof Q,i.message),a=i instanceof Q?i.hint:void 0;return t.stderr(`aifight.service could not be restarted: ${s}
|
|
102
102
|
`),a&&t.stderr(`${a}
|
|
103
103
|
`),"unavailable"}}if(t.stdout(["AIFight needs a long-running local Bridge before your Agent can play scheduled matches and challenges.","","I can install a local background service named aifight.service.","It runs `aifight run` after reboot and keeps the outbound Bridge online for normal use.","","This does not expose your machine to the public internet.","AIFight Bridge only opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","","If you do not install it now, finish setup later with `aifight service install` or manage `aifight run` yourself.",""].join(`
|
|
104
|
-
`)),!(e.approvedLocalSetup===!0?!0:await
|
|
105
|
-
`);try{let o=await
|
|
104
|
+
`)),!(e.approvedLocalSetup===!0?!0:await lm(t,"Install and start aifight.service now? [Y/n] ")))return"declined";e.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; installing aifight.service now.
|
|
105
|
+
`);try{let o=await oc(t.bridgeService);return t.stdout(`aifight.service installed and started (${o.platform}).
|
|
106
106
|
`),t.stdout(`unit: ${o.unitPath}
|
|
107
107
|
`),o.warning&&t.stderr(`warning: ${o.warning}
|
|
108
|
-
`),"installed"}catch(o){let i=(o instanceof
|
|
108
|
+
`),"installed"}catch(o){let i=(o instanceof Q,o.message),s=o instanceof Q?o.hint:void 0;return t.stderr(`aifight.service could not be installed: ${i}
|
|
109
109
|
`),s&&t.stderr(`${s}
|
|
110
|
-
`),"unavailable"}}async function
|
|
110
|
+
`),"unavailable"}}async function O0(t){try{return await St(t.bridgeService)}catch{return}}async function lm(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}import{execFile as N0}from"node:child_process";import fm from"node:fs";import mm from"node:path";var L0=3e4;function Ae(t){let e=process.env.PATH??"",n=process.platform==="win32"?["",".cmd",".exe",".bat"]:[""];for(let r of e.split(mm.delimiter))if(r)for(let o of n){let i=mm.join(r,`${t}${o}`);try{return fm.accessSync(i,fm.constants.X_OK),i}catch{}}}async function it(t,e){let n=Ae(t)??t;return new Promise(r=>{let o=!1,i=a=>{o||(o=!0,r(a))};N0(n,e,{timeout:L0},(a,c,l)=>{let u=a?.code;i({code:typeof u=="number"?u:a?1:0,stdout:String(c??""),stderr:String(l??"")})}).on("error",a=>{i({code:1,stdout:"",stderr:a.message})})})}function gn(t,e,n){n.stdout.trim()&&t.stdout(`${e}: ${n.stdout.trim()}
|
|
111
111
|
`),n.stderr.trim()&&t.stderr(`${e}: ${n.stderr.trim()}
|
|
112
|
-
`)}async function
|
|
112
|
+
`)}async function si(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r===""||r==="y"||r==="yes"}async function Kr(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}async function Xn(t,e,n,r={}){let o=await M0(e),i=e==="openclaw"?"OpenClaw Gateway":"Hermes Gateway";if(o===void 0)return t.stdout([`${i} needs a restart for this change to apply.`,"I could not safely detect how it is managed, so I will not restart it automatically.",`Manual restart options: ${B0(e)}`,""].join(`
|
|
113
113
|
`)),!1;if(t.stdout([`${i} needs a restart for this change to apply.`,`Detected restart method: ${o.label}.`,`Reason: ${n}`,"Restarting may interrupt any current OpenClaw/Hermes tasks using this Gateway.",o.note??"",`Command I would run: ${o.manualCommand}`,""].filter(c=>c!=="").join(`
|
|
114
114
|
`)+`
|
|
115
|
-
`),!(r.approvedLocalSetup===!0?!0:await
|
|
115
|
+
`),!(r.approvedLocalSetup===!0?!0:await Kr(t,"Restart now? [y/N] ")))return t.stdout(`Skipped restart. Run when ready: ${o.manualCommand}
|
|
116
116
|
|
|
117
117
|
`),!1;r.approvedLocalSetup===!0&&t.stdout(`Using the previously approved AIFight local setup scope; restarting now.
|
|
118
|
-
`);let a=await
|
|
118
|
+
`);let a=await it(o.command,o.args);return gn(t,o.manualCommand,a),e==="hermes"&&F0(a)?(t.stdout("Hermes reported that no restartable service is available. Start it manually with `hermes gateway run` when ready.\n\n"),!1):a.code!==0?(t.stderr(`Restart command did not complete successfully. Run manually when ready: ${o.manualCommand}
|
|
119
119
|
|
|
120
120
|
`),!1):(t.stdout(`${i} restart requested.
|
|
121
121
|
|
|
122
|
-
`),!0)}async function
|
|
123
|
-
${t.stderr}`)}function
|
|
124
|
-
`,{mode:384}),
|
|
122
|
+
`),!0)}async function M0(t){let e=await j0(t);if(e)return e;if(t==="openclaw"&&Ae("openclaw"))return{label:"OpenClaw CLI",command:"openclaw",args:["gateway","restart","--safe"],manualCommand:"openclaw gateway restart --safe",note:"This uses OpenClaw's own safe restart command instead of killing a process."};if(t==="hermes"&&Ae("hermes"))return{label:"Hermes CLI",command:"hermes",args:["gateway","restart"],manualCommand:"hermes gateway restart",note:"If Hermes is running in a foreground terminal, stop that process and run `hermes gateway run` when ready."}}async function j0(t){if(process.platform!=="linux"||!Ae("systemctl"))return;let e=t==="openclaw"?["openclaw-gateway.service","openclaw.gateway.service","openclaw.service"]:["hermes-gateway.service","hermes.gateway.service","hermes.service"];for(let n of[[],["--user"]])for(let r of e){let o=await it("systemctl",[...n,"is-active",r]);if(D0(o)){let i=n.length>0?`${n.join(" ")} `:"";return{label:`systemd ${i}${r}`.trim(),command:"systemctl",args:[...n,"restart",r],manualCommand:`systemctl ${i}restart ${r}`}}}}function D0(t){return t.code===0&&t.stdout.trim()==="active"}function F0(t){return/cannot restart gateway as a service|no restartable service/i.test(`${t.stdout}
|
|
123
|
+
${t.stderr}`)}function B0(t){return t==="openclaw"?"`openclaw gateway restart --safe`, or restart your own OpenClaw service manager":"`hermes gateway restart`, or restart the terminal running `hermes gateway run`"}import{randomBytes as H0}from"node:crypto";import Zn from"node:fs";import G0 from"node:os";import hm from"node:path";import Jr from"node:fs";import U0 from"node:path";function ac(){return U0.join(oe(),"runtime-setup.json")}function cc(){try{let t=Jr.readFileSync(ac(),"utf8"),e=JSON.parse(t);return q0(e)?e:void 0}catch(t){if(t.code==="ENOENT")return;throw t}}function lc(t){at();let e=cc(),n={version:1,updatedAt:new Date().toISOString(),...e?.openclaw?{openclaw:e.openclaw}:{},...e?.hermes?{hermes:e.hermes}:{},...t.openclaw?{openclaw:t.openclaw}:{},...t.hermes?{hermes:t.hermes}:{}},r=ac(),o=`${r}.tmp`;if(Jr.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
124
|
+
`,{mode:384}),Jr.renameSync(o,r),process.platform!=="win32")try{Jr.chmodSync(r,384)}catch{}}function pm(){Jr.rmSync(ac(),{force:!0})}function q0(t){if(!t||typeof t!="object")return!1;let e=t;return e.version===1&&typeof e.updatedAt=="string"}var dc="gateway.http.endpoints.responses.enabled",gm=4e3,V0=6e3,ym=1e4;async function _m(t){if(t.jsonMode||!process.stdin.isTTY&&t.approvedLocalSetup!==!0)return{};switch(t.runtimeType){case"openclaw":return W0(t);case"hermes":return z0(t);case"mock":return{}}}async function W0(t){let e=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`OpenClaw local /v1/responses is reachable (${e.detail}).
|
|
125
125
|
|
|
126
126
|
`),{};if(e.status==="auth_failed"){if(t.runtimeLocalToken!==void 0)return t.env.stdout(`OpenClaw local /v1/responses rejected the provided runtime token (${e.detail}).
|
|
127
127
|
|
|
128
128
|
`),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."};if(t.env.stdout([`OpenClaw local /v1/responses is enabled but requires a local Gateway token (${e.detail}).`,"AIFight can store that token only in the local bridge credentials so the bridge can call localhost.","The token is not uploaded to AIFight and will not be printed.",""].join(`
|
|
129
|
-
`)),!(t.approvedLocalSetup===!0?!0:await
|
|
130
|
-
`);let u=await
|
|
129
|
+
`)),!(t.approvedLocalSetup===!0?!0:await si(t.env,"Allow AIFight to read and store the local OpenClaw Gateway token now? [Y/n] ")))return{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; reading the local OpenClaw Gateway token now.
|
|
130
|
+
`);let u=await X0();if(u.length===0)return t.env.stdout("Could not find an OpenClaw Gateway token from OPENCLAW_GATEWAY_TOKEN or `openclaw config get gateway.auth.token`.\n\n"),{blockedReason:"OpenClaw requires a local Gateway token before AIFight registration can finish."};for(let d of u){let h=await er(t.env,t.runtimeLocalUrl,d,t.runtimeModel);if(h.status==="ready"||h.status==="endpoint_reachable")return t.env.stdout(`OpenClaw accepted a local Gateway token (${h.detail}).
|
|
131
131
|
|
|
132
132
|
`),{runtimeLocalToken:d}}return t.env.stdout(`OpenClaw did not accept any discovered local Gateway token.
|
|
133
133
|
|
|
134
|
-
`),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."}}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost / 127.0.0.1.","Your model/provider keys stay inside OpenClaw.","If Gateway is already running, it may need a safe restart for this change to apply.","","I can run:",` openclaw config set ${
|
|
135
|
-
`)),!
|
|
134
|
+
`),{blockedReason:"OpenClaw requires a valid local Gateway token before AIFight registration can finish."}}if(t.env.stdout(["OpenClaw needs its local /v1/responses endpoint enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call OpenClaw only on localhost / 127.0.0.1.","Your model/provider keys stay inside OpenClaw.","If Gateway is already running, it may need a safe restart for this change to apply.","","I can run:",` openclaw config set ${dc} true --strict-json`," openclaw config validate",""].join(`
|
|
135
|
+
`)),!Ae("openclaw"))return t.env.stderr(`OpenClaw CLI was not found on PATH. Enable the endpoint manually after installing OpenClaw.
|
|
136
136
|
|
|
137
|
-
`),{};if(!(t.approvedLocalSetup===!0?!0:await
|
|
137
|
+
`),{};if(!(t.approvedLocalSetup===!0?!0:await si(t.env,"Allow this local OpenClaw config change now? [Y/n] ")))return t.env.stdout(`Skipped OpenClaw config change. You can run the command above later.
|
|
138
138
|
|
|
139
139
|
`),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; applying OpenClaw config now.
|
|
140
|
-
`);let r=await
|
|
140
|
+
`);let r=await eE(),o=await it("openclaw",["config","set",dc,"true","--strict-json"]);if(gn(t.env,"openclaw config set",o),o.code!==0)return t.env.stderr(`OpenClaw config update failed. Continue only after enabling /v1/responses manually.
|
|
141
141
|
|
|
142
|
-
`),{};let i=await
|
|
143
|
-
`),await
|
|
142
|
+
`),{};let i=await it("openclaw",["config","validate"]);gn(t.env,"openclaw config validate",i),lc({openclaw:{responsesEnabledByAIFight:r!==!0,updatedAt:new Date().toISOString()}}),t.env.stdout(`OpenClaw config updated. Gateway may need a restart before the endpoint is available.
|
|
143
|
+
`),await fc(V0);let s=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(s.status==="ready"||s.status==="endpoint_reachable")return t.env.stdout(`OpenClaw endpoint check: ${s.detail}
|
|
144
144
|
|
|
145
145
|
`),{};if(t.env.stdout(`OpenClaw endpoint is still not ready (${s.detail}).
|
|
146
146
|
`),!await Xn(t.env,"openclaw","OpenClaw /v1/responses was enabled for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`OpenClaw endpoint will be available after you restart Gateway when ready.
|
|
147
147
|
|
|
148
148
|
`),{};t.env.stdout(`Waiting 10 seconds before checking OpenClaw /v1/responses again...
|
|
149
|
-
`),await
|
|
149
|
+
`),await fc(ym);let c=await er(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);return t.env.stdout(`OpenClaw endpoint after restart: ${c.detail}
|
|
150
150
|
|
|
151
|
-
`),{}}async function
|
|
151
|
+
`),{}}async function z0(t){let e=await ai(t.env,t.runtimeLocalUrl,t.runtimeLocalToken,t.runtimeModel);if(e.status==="ready"||e.status==="endpoint_reachable")return t.env.stdout(`Hermes local API Server is reachable (${e.detail}).
|
|
152
152
|
|
|
153
|
-
`),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost / 127.0.0.1.","Your Hermes provider keys, tools, and strategy prompts stay local.","Hermes may need a Gateway restart for API_SERVER_* changes to apply.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${
|
|
154
|
-
`)),!
|
|
153
|
+
`),{};if(t.env.stdout(["Hermes needs its local API Server enabled before AIFight can ask your Agent for match decisions.","","AIFight Bridge will call Hermes only on localhost / 127.0.0.1.","Your Hermes provider keys, tools, and strategy prompts stay local.","Hermes may need a Gateway restart for API_SERVER_* changes to apply.","","I can update ~/.hermes/.env with:"," API_SERVER_ENABLED=true"," API_SERVER_HOST=127.0.0.1",` API_SERVER_PORT=${vm(t.runtimeLocalUrl)}`," API_SERVER_KEY=<local token>",""].join(`
|
|
154
|
+
`)),!Ae("hermes"))return t.env.stderr(`Hermes CLI was not found on PATH. Enable the API Server manually after installing Hermes.
|
|
155
155
|
|
|
156
|
-
`),{};if(!(t.approvedLocalSetup===!0?!0:await
|
|
156
|
+
`),{};if(!(t.approvedLocalSetup===!0?!0:await si(t.env,"Allow this local Hermes .env update now? [Y/n] ")))return t.env.stdout(`Skipped Hermes .env update. You can add the API_SERVER_* values later.
|
|
157
157
|
|
|
158
158
|
`),{};t.approvedLocalSetup===!0&&t.env.stdout(`Using the previously approved AIFight local setup scope; updating Hermes .env now.
|
|
159
|
-
`);let r=
|
|
159
|
+
`);let r=K0({runtimeLocalUrl:t.runtimeLocalUrl,runtimeLocalToken:t.runtimeLocalToken,runtimeModel:t.runtimeModel}),o=r.token;if(lc({hermes:{envPath:r.envPath,previous:r.previous,updatedAt:new Date().toISOString()}}),t.env.stdout(`Hermes .env updated and backed up if it already existed.
|
|
160
160
|
`),t.env.stdout(`Hermes does not hot-reload API_SERVER_* settings.
|
|
161
161
|
`),!await Xn(t.env,"hermes","Hermes API Server settings were updated for AIFight.",{approvedLocalSetup:t.approvedLocalSetup}))return t.env.stdout(`Hermes API Server will be available after you start or restart Gateway when ready.
|
|
162
162
|
|
|
163
163
|
`),{runtimeLocalToken:o};t.env.stdout(`Waiting 10 seconds before checking Hermes /v1/responses again...
|
|
164
|
-
`),await
|
|
164
|
+
`),await fc(ym);let s=await ai(t.env,t.runtimeLocalUrl,o,t.runtimeModel);return t.env.stdout(`Hermes endpoint check: ${s.detail}
|
|
165
165
|
|
|
166
|
-
`),{runtimeLocalToken:o}}async function er(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),
|
|
166
|
+
`),{runtimeLocalToken:o}}async function er(t,e,n,r="openclaw/default"){let o=t.fetchImpl??globalThis.fetch,i=new AbortController,s=setTimeout(()=>i.abort(),gm);try{let a={"Content-Type":"application/json"};n&&(a.Authorization=`Bearer ${n}`);let c=await o(`${e.replace(/\/+$/,"")}/v1/responses`,{method:"POST",headers:a,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'}),signal:i.signal});return c.status===404?{status:"disabled",detail:"OpenClaw /v1/responses returned HTTP 404"}:c.status===401||c.status===403?{status:"auth_failed",detail:`OpenClaw /v1/responses returned HTTP ${c.status}`}:c.ok?{status:"ready",detail:`OpenClaw /v1/responses HTTP ${c.status}`}:{status:"endpoint_reachable",detail:`OpenClaw /v1/responses HTTP ${c.status}`}}catch(a){let c=a instanceof Error&&a.name==="AbortError"?"OpenClaw /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config":`OpenClaw /v1/responses is not reachable (${a instanceof Error?a.message:String(a)})`;return{status:a instanceof Error&&a.name==="AbortError"?"endpoint_reachable":"unreachable",detail:c}}finally{clearTimeout(s)}}async function ai(t,e,n,r="hermes-agent"){let o=t.fetchImpl??globalThis.fetch,i=e.replace(/\/+$/,"");try{let s=await uc(o,`${i}/health`,{});if(!s.ok)return{status:"unreachable",detail:`Hermes /health HTTP ${s.status}`};let a={};n&&(a.Authorization=`Bearer ${n}`);let c=await uc(o,`${i}/v1/models`,{headers:a});if(c.status===401||c.status===403)return{status:"auth_failed",detail:`Hermes /v1/models HTTP ${c.status}; check API_SERVER_KEY and --runtime-token`};if(!c.ok)return{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}`};let l={"Content-Type":"application/json",...a},u;try{u=await uc(o,`${i}/v1/responses`,{method:"POST",headers:l,body:JSON.stringify({model:r,input:'AIFight setup check. Return JSON: {"action":"pass"}'})})}catch(d){return d instanceof Error&&d.name==="AbortError"?{status:"endpoint_reachable",detail:"Hermes /v1/responses probe timed out; endpoint may be enabled but waiting on model/provider config"}:{status:"unreachable",detail:`Hermes /v1/responses is not reachable (${d instanceof Error?d.message:String(d)})`}}return u.status===404?{status:"disabled",detail:"Hermes /v1/responses returned HTTP 404"}:u.status===401||u.status===403?{status:"auth_failed",detail:`Hermes /v1/responses HTTP ${u.status}; check API_SERVER_KEY and --runtime-token`}:u.ok?{status:"ready",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}:{status:"endpoint_reachable",detail:`Hermes /health HTTP ${s.status}, /v1/models HTTP ${c.status}, /v1/responses HTTP ${u.status}`}}catch(s){return{status:"unreachable",detail:`Hermes API Server is not reachable (${s instanceof Error?s.message:String(s)})`}}}async function uc(t,e,n){let r=new AbortController,o=setTimeout(()=>r.abort(),gm);try{return await t(e,{...n,signal:r.signal})}finally{clearTimeout(o)}}function K0(t){let e=process.env.HERMES_HOME??hm.join(G0.homedir(),".hermes");Zn.mkdirSync(e,{recursive:!0,mode:448});let n=hm.join(e,".env"),r=Zn.existsSync(n)?Zn.readFileSync(n,"utf8"):"";if(r!==""){let l=new Date().toISOString().replace(/[-:]/g,"").replace(/\..+$/,"Z");Zn.copyFileSync(n,`${n}.aifight-backup-${l}`)}let o=wm(r,"API_SERVER_KEY"),i=t.runtimeLocalToken??o??`aifight_${H0(24).toString("base64url")}`,s={API_SERVER_ENABLED:"true",API_SERVER_HOST:Y0(t.runtimeLocalUrl),API_SERVER_PORT:String(vm(t.runtimeLocalUrl)),API_SERVER_KEY:i,API_SERVER_MODEL_NAME:t.runtimeModel??"hermes-agent"},a=Q0(r,Object.keys(s)),c=J0(r,s);if(Zn.writeFileSync(n,c,{mode:384}),process.platform!=="win32")try{Zn.chmodSync(n,384)}catch{}return{token:i,envPath:n,previous:a}}function J0(t,e){let n=new Set(Object.keys(e)),r=new Set,i=t.split(/\r?\n/).map(s=>{let a=s.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);if(!a)return s;let c=a[3];return n.has(c)?(r.add(c),`${c}=${e[c]}`):s});if(i.length>0&&i[i.length-1]!==""&&i.push(""),[...n].some(s=>!r.has(s))){i.push("# AIFight local API Server settings");for(let s of Object.keys(e))r.has(s)||i.push(`${s}=${e[s]}`)}return i.join(`
|
|
167
167
|
`).replace(/\n*$/,`
|
|
168
|
-
`)}function
|
|
169
|
-
`);async function
|
|
168
|
+
`)}function wm(t,e){for(let n of t.split(/\r?\n/)){if(n.trimStart().startsWith("#"))continue;let r=n.match(new RegExp(`^\\s*${e}\\s*=\\s*(.*)\\s*$`));if(!r)continue;return r[1].trim().replace(/^['"]|['"]$/g,"")}}function Y0(t){try{return new URL(t).hostname||"127.0.0.1"}catch{return"127.0.0.1"}}function vm(t){try{let e=new URL(t);if(e.port)return Number(e.port)}catch{}return 8642}function Q0(t,e){let n={};for(let r of e){let o=wm(t,r);n[r]=o===void 0?{wasActive:!1}:{wasActive:!0,value:o}}return n}async function X0(){let t=[],e=o=>{o&&!t.includes(o)&&t.push(o)},n=process.env.OPENCLAW_GATEWAY_TOKEN?.trim();if(e(n),!Ae("openclaw"))return t;let r=await it("openclaw",["config","get","gateway.auth.token"]);return r.code===0&&e(Z0(r.stdout)),t}function Z0(t){let e=t.trim();if(e===""||e.toLowerCase()==="null"||e.toLowerCase()==="undefined")return;try{let i=JSON.parse(e);if(typeof i=="string"&&i.trim()!=="")return i.trim();if(i&&typeof i=="object"){let s=i.value??i.token??i["gateway.auth.token"];if(typeof s=="string"&&s.trim()!=="")return s.trim()}}catch{}let n=e.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);if(!n)return;let o=(n.match(/(?:gateway\.auth\.token|token)\s*[:=]\s*(.+)$/i)?.[1]??n).trim().replace(/^['"]|['"]$/g,"");return o.length>0?o:void 0}async function eE(){let t=await it("openclaw",["config","get",dc]);if(t.code!==0)return;let e=t.stdout.trim().toLowerCase();if(e==="true"||e.endsWith(" true"))return!0;if(e==="false"||e.endsWith(" false"))return!1}function fc(t){return new Promise(e=>setTimeout(e,t))}var rE="https://aifight.ai",bm=2,oE="approved-local-setup",yn=["usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Creates a private bootstrap AIFight identity, saves local match credentials, and offers aifight.service."," In human interactive mode, asks which local runtime to use when none is specified."," --approved-local-setup is for Agent-assisted setup after the human already approved local runtime/service changes."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Claim the agent and choose its official Dashboard name before it can play matches or challenges."].join(`
|
|
169
|
+
`);async function Em(t,e){W(t,0,1,yn);let n=t.flags[oE]===!0;if(t.jsonMode&&n)throw new O("--approved-local-setup cannot be combined with --json",yn);let r=await iE(t,e,n),o=cE(t,r),i=lE(process.env.AIFIGHT_BASE_URL??rE),s=Yr(t.flags,"runtime-model")??jt(r),a=dE(Yr(t.flags,"runtime-url")??Jn(r),r),c=Yr(t.flags,"runtime-token");try{let l=await _m({env:e,runtimeType:r,runtimeLocalUrl:a,runtimeLocalToken:c,runtimeModel:s,jsonMode:t.jsonMode,approvedLocalSetup:n});if(l.blockedReason!==void 0)throw new U("runtime_setup_incomplete",l.blockedReason);c=c??l.runtimeLocalToken;let u=await ma({baseUrl:i,request:{name:o,model:s,description:`AIFight Bridge agent (${r})`},fetchImpl:e.fetchImpl}),d={version:1,baseUrl:i,wsUrl:uE(i),agentId:u.agentId,agentName:u.response.agent.name,suggestedName:u.response.agent.suggested_name??o,apiKey:u.apiKey,claimUrl:u.claimUrl,claimToken:u.claimToken,runtimeType:r,runtimeLocalUrl:a,...c!==void 0?{runtimeLocalToken:c}:{},runtimeModel:s,autoDailyLimit:bm,updatedAt:new Date().toISOString()};return pn(d),t.jsonMode?(e.stdout(JSON.stringify({status:"registered",claimUrl:u.claimUrl,config:Dt(d)})+`
|
|
170
170
|
`),0):(e.stdout(`AIFight Agent registered.
|
|
171
171
|
|
|
172
172
|
`),e.stdout(`Bootstrap ID: ${d.agentName}
|
|
173
173
|
`),e.stdout(`Suggested name: ${d.suggestedName??o}
|
|
174
174
|
`),e.stdout(`Status: unclaimed, official name pending
|
|
175
|
-
`),e.stdout(`Runtime: ${
|
|
176
|
-
`),e.stdout(`Automatic ranked matches: ${
|
|
175
|
+
`),e.stdout(`Runtime: ${km(d.runtimeType)} at ${d.runtimeLocalUrl}
|
|
176
|
+
`),e.stdout(`Automatic ranked matches: ${bm} per day
|
|
177
177
|
`),e.stdout(`Local credentials saved on this machine.
|
|
178
178
|
|
|
179
179
|
`),e.stdout(`Claim URL:
|
|
@@ -181,78 +181,101 @@ ${t.stderr}`)}function O0(t){return t==="openclaw"?"`openclaw gateway restart --
|
|
|
181
181
|
|
|
182
182
|
`),e.stdout(`Claim this agent, then confirm its official public name in Dashboard before starting matches, challenges, or Grand Prix events. Claiming also enables dashboard management, profile settings, and recovery.
|
|
183
183
|
|
|
184
|
-
`),await
|
|
184
|
+
`),await dm(e,{approvedLocalSetup:n})==="installed"||(e.stdout(`AIFight Agent registered, but it is not online yet.
|
|
185
185
|
|
|
186
186
|
`),e.stdout(`Normal use requires a long-running local Bridge.
|
|
187
187
|
`),e.stdout(`Finish setup with:
|
|
188
188
|
`),e.stdout(` aifight service install
|
|
189
189
|
|
|
190
190
|
`),e.stdout(`Advanced alternatives:
|
|
191
|
-
`),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(l){if(l instanceof
|
|
191
|
+
`),e.stdout(" - Manage `aifight run` with your own process manager.\n"),e.stdout(" - For developer debugging only, run `aifight run` in a terminal.\n")),0)}catch(l){if(l instanceof Zt){let u=typeof l.body=="object"?l.body.error:void 0;throw new U("registration_failed",u??`registration failed with HTTP ${l.status}`)}throw l instanceof pt?new U("registration_failed",l.message):l}}function km(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}async function iE(t,e,n){let r=t.positional[0],o=Yr(t.flags,"runtime"),i=process.env.AIFIGHT_RUNTIME_TYPE,s=o??r??i;if(o!==void 0&&r!==void 0&&o!==r)throw new O("runtime argument and --runtime disagree",yn);if(s==="openclaw"||s==="hermes")return s;if(s===void 0){if(n){let a=await sE(e);if(a.runtimeType!==void 0)return e.stdout(`Detected local Agent runtime: ${km(a.runtimeType)} (${a.detail}).
|
|
192
192
|
|
|
193
193
|
`),a.runtimeType;throw new O(["Could not safely auto-detect whether this machine is running OpenClaw or Hermes.",a.detail,"Rerun with an explicit runtime:"," aifight register openclaw --approved-local-setup"," aifight register hermes --approved-local-setup"].join(`
|
|
194
|
-
`),yn)}return!t.jsonMode&&process.stdin.isTTY?
|
|
195
|
-
`)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,yn)}function
|
|
196
|
-
`);async function
|
|
194
|
+
`),yn)}return!t.jsonMode&&process.stdin.isTTY?aE(e):"openclaw"}throw new O(`runtime must be openclaw or hermes (got '${s}')`,yn)}async function sE(t){let[e,n]=await Promise.all([er(t,Jn("openclaw"),void 0,jt("openclaw")),ai(t,Jn("hermes"),void 0,jt("hermes"))]),r=Sm(e),o=Sm(n);if(r>o)return{runtimeType:"openclaw",detail:e.detail};if(o>r)return{runtimeType:"hermes",detail:n.detail};if(r>0&&o>0)return{detail:`OpenClaw and Hermes both looked reachable: ${e.detail}; ${n.detail}`};let i=Ae("openclaw")!==void 0,s=Ae("hermes")!==void 0;if(i&&!s)return{runtimeType:"openclaw",detail:"OpenClaw CLI found on PATH; Hermes CLI not found"};if(s&&!i)return{runtimeType:"hermes",detail:"Hermes CLI found on PATH; OpenClaw CLI not found"};let a=i&&s?"both OpenClaw and Hermes CLIs are installed":"neither OpenClaw nor Hermes CLI was found on PATH";return{detail:`OpenClaw probe: ${e.detail}; Hermes probe: ${n.detail}; ${a}.`}}function Sm(t){switch(t.status){case"ready":case"endpoint_reachable":case"auth_failed":return 3;case"disabled":return 2;case"unreachable":return 0}}async function aE(t){t.stdout(["Which local Agent runtime should this Bridge use?"," 1) OpenClaw (default)"," 2) Hermes","","Runtime [OpenClaw]: "].join(`
|
|
195
|
+
`)),process.stdin.resume(),process.stdin.setEncoding("utf8");let e=await new Promise(r=>{process.stdin.once("data",o=>r(String(o)))});process.stdin.pause();let n=e.trim().toLowerCase();if(n===""||n==="1"||n==="openclaw"||n==="o")return"openclaw";if(n==="2"||n==="hermes"||n==="h")return"hermes";throw new O(`runtime must be openclaw or hermes (got '${e.trim()}')`,yn)}function cE(t,e){let n=Yr(t.flags,"name");if(n!==void 0)return n;let r=tE.hostname().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,""),o=r.length>=2?r.slice(0,24):"local";return`agent-${e}-${o}-${nE(3).toString("hex")}`.slice(0,50)}function lE(t){return t.replace(/\/+$/,"")}function uE(t){let e=new URL(t);if(e.protocol==="https:")e.protocol="wss:";else if(e.protocol==="http:")e.protocol="ws:";else throw new Error(`unsupported AIFight base URL protocol: ${e.protocol}`);return e.pathname="/api/ws",e.search="",e.hash="",e.toString()}function Yr(t,e){let n=t[e];if(!(typeof n!="string"||n.trim()===""))return n.trim()}function dE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,yn):n}}var fE="https://aifight.ai";async function $m(t){let e=t.pairingCode.trim();if(e==="")throw new Error("pairing code is required");let n=mE(t.baseUrl??process.env.AIFIGHT_BASE_URL??fE),o=await(t.fetchImpl??globalThis.fetch)(`${n}/api/bridge/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pairing_code:e})});if(!o.ok){let l=await pE(o);throw new Error(l)}let i=await o.json(),s=hE(i),a=s.agent.runtime_type,c=t.now??(()=>new Date);return{version:1,baseUrl:n,wsUrl:s.ws_url,agentId:s.agent.id,agentName:s.agent.name,apiKey:s.agent.api_key,runtimeType:a,runtimeLocalUrl:Jn(a),runtimeModel:jt(a),updatedAt:c().toISOString()}}function mE(t){return t.replace(/\/+$/,"")}async function pE(t){let e=await t.json().catch(()=>{});if(e&&typeof e=="object"){let n=e.error;if(typeof n=="string"&&n.length>0)return n}return`pairing failed with HTTP ${t.status}`}function hE(t){if(!t||typeof t!="object")throw new Error("pairing response was not an object");let e=t,n=e.agent;if(!n||typeof n!="object")throw new Error("pairing response missing agent");let r=n;if(typeof r.id!="string"||typeof r.name!="string"||typeof r.api_key!="string"||r.runtime_type!=="openclaw"&&r.runtime_type!=="hermes"&&r.runtime_type!=="mock"||typeof e.ws_url!="string")throw new Error("pairing response had invalid fields");return{agent:{id:r.id,name:r.name,api_key:r.api_key,runtime_type:r.runtime_type},ws_url:e.ws_url,...typeof e.message=="string"?{message:e.message}:{}}}var Pm=["usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," --runtime-token is local only; it is never sent to AIFight."].join(`
|
|
196
|
+
`);async function Am(t,e){W(t,1,1,Pm);let n=t.positional[0],r;try{r=await $m({pairingCode:n,fetchImpl:e.fetchImpl})}catch(l){let u=l instanceof Error?l.message:String(l);throw new U("pairing_failed",u)}let o={...r,...Rm(t.flags,"runtime-token","runtimeLocalToken"),...Rm(t.flags,"runtime-model","runtimeModel")},i=t.flags["runtime-url"],s=typeof i=="string"&&i.trim()!==""?i.trim():void 0,a=gE(s??o.runtimeLocalUrl,o.runtimeType),c={...o,runtimeLocalUrl:a};return pn(c),t.jsonMode?(e.stdout(JSON.stringify({status:"configured",config:Dt(c)})+`
|
|
197
197
|
`),0):(e.stdout(`Bridge configured for ${c.agentName} (${c.runtimeType}).
|
|
198
198
|
`),e.stdout(`Runtime local URL: ${c.runtimeLocalUrl}
|
|
199
199
|
`),c.runtimeLocalToken&&e.stdout(`Runtime local token: configured locally (redacted)
|
|
200
200
|
`),e.stdout(`Next: aifight service install
|
|
201
|
-
`),0)}function
|
|
202
|
-
`);async function
|
|
203
|
-
`),e.stderr(`
|
|
201
|
+
`),0)}function Rm(t,e,n){let r=t[e];return typeof r!="string"||r.trim()===""?{}:{[n]:r.trim()}}function gE(t,e){try{return Gr(t,e)}catch(n){throw n instanceof Ge?new O(n.message,Pm):n}}var mc=20,ci=["usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running AIFight Bridge.",` N must be 1-${mc}. Manual starts do not consume the daily automatic match limit.`,` supported games: ${he.join(", ")}`].join(`
|
|
202
|
+
`);async function Cm(t,e){if(t.positional.length>2){let i=t.positional.slice(2).join(" ");throw new O(`unexpected extra positional arguments: ${i}`,ci)}let n=yE(),r=_E(t.positional,n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl});if(o.status==="unsupported")return e.stderr(`${o.message}
|
|
203
|
+
`),e.stderr(`Run: aifight update --yes
|
|
204
|
+
`),e.stderr(`Manual npm command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
|
|
204
205
|
`),1;o.status==="update_recommended"&&(e.stdout(`[warn] bridge.update: ${o.message}
|
|
205
|
-
`),e.stdout(`[warn] update
|
|
206
|
-
`));try{await
|
|
207
|
-
`);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${
|
|
206
|
+
`),e.stdout(`[warn] update when ready: aifight update --yes
|
|
207
|
+
`));try{await Dc(e).post(`/v1/agents/${encodeURIComponent(n.agentName)}/join`,{game:r.game,mode:"ranked",one_shot:!0,count:r.count})}catch(i){throw i instanceof pe?new U(wE(i),vE(i),{hint:await bE(e)}):i}if(t.jsonMode)e.stdout(JSON.stringify({status:"queued",agent:n.agentName,game:r.game,count:r.count,mode:"ranked",manual:!0})+`
|
|
208
|
+
`);else{let i=r.count===1?"match":"matches";e.stdout(`Requested ${r.count} manual ranked ${SE(r.game)} ${i} for ${n.agentName}.
|
|
208
209
|
`),e.stdout(`The running Bridge will keep your Agent online and handle the match when AIFight pairs it.
|
|
209
|
-
`)}return 0}function uE(){try{return ce()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new W("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function dE(t,e){if(t.length===0)return{game:Pm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Rm(n);if(i!==null)return{game:Pm(e.autoGames),count:i};if(at(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ai)}let r=t[1];if(!at(n))throw new O(`unsupported game '${n}'`,ai);let o=Rm(r);if(o===null)throw new O(`N must be an integer between 1 and ${fc}`,ai);return{game:n,count:o}}function Rm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>fc?null:e}function Pm(t){let e=(t??pe).filter(at),n=e.length>0?e:pe;return n[Math.floor(Math.random()*n.length)]}function fE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function mE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function pE(t){try{let e=await pn(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof te))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function hE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Ft from"node:path";import ee from"node:fs";import gE from"node:crypto";var ye=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Cm(){return Ft.join(re(),"token")}function xm(){return Ft.join(re(),"port")}function pc(){return Ft.join(re(),"pid")}function yE(){return Ft.join(re(),"lock")}var Am=0,_E=/^[0-9a-f]{64}$/;function hc(t,e,n){let r=Ft.dirname(t),o=Ft.basename(t);Am+=1;let i=Ft.join(r,`${o}.${process.pid}.${Am}.tmp`),s;try{if(s=ee.openSync(i,"w",n),ee.writeSync(s,e),ee.closeSync(s),s=void 0,process.platform!=="win32")try{ee.chmodSync(i,n)}catch{}ee.renameSync(i,t)}catch(a){if(s!==void 0)try{ee.closeSync(s)}catch{}try{ee.unlinkSync(i)}catch{}throw new ye("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Im(){return gE.randomBytes(32).toString("hex")}function Om(t){let e=Cm();if(!_E.test(t))throw new ye("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);hc(e,t,384)}function Nm(t){let e=xm();if(!Number.isInteger(t)||t<1||t>65535)throw new ye("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);hc(e,String(t),420)}function Mm(t){let e=pc();if(!Number.isInteger(t)||t<1)throw new ye("write_failed",e,`pid must be a positive integer but received ${t}`);hc(e,String(t),420)}function gc(t){for(let e of[Cm(),xm(),pc()])try{ee.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Lm(){let t=re(),e;try{e=ee.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{ee.unlinkSync(Ft.join(t,n))}catch{}}var mc=new Set;function wE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function vE(t){let e;try{e=ee.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function jm(t){let e=yE(),n=pc(),r=t?.processIsAlive??wE;if(mc.has(e))throw new ye("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=ee.openSync(e,ee.constants.O_WRONLY|ee.constants.O_CREAT|ee.constants.O_EXCL,384);if(ee.closeSync(i),process.platform!=="win32")try{ee.chmodSync(e,384)}catch{}return mc.add(e),bE(e)}catch(i){if(i.code!=="EEXIST")throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=vE(n);if(a.kind==="missing")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new ye("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new ye("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{ee.unlinkSync(e)}catch{}try{ee.unlinkSync(n)}catch{}}throw new ye("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function bE(t){let e=!1;return{release(){if(!e){e=!0,mc.delete(t);try{ee.unlinkSync(t)}catch{}}}}}import*as Hm from"node:http";import{Buffer as wc}from"node:buffer";import*as Gm from"node:crypto";var _n=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Wm="0.1.0-alpha.3",Dm=`aifight-runtime/${Wm}`,SE="127.0.0.1",EE=0,kE=1048576,$E=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Vm(t){return t.split("/").filter(e=>e.length>0)}function Ae(t){let e=Vm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function RE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function Fm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=wc.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Bm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function yc(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function qm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function Um(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function PE(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function zm(t){let e=t.host??SE,n=t.port??EE,r=t.bodyLimitBytes??kE,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Ae("/v1/health"),handler:h},{method:"GET",pattern:Ae("/v1/agents"),handler:y},{method:"GET",pattern:Ae("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Ae("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Ae("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Ae("/v1/agents/:name/schedule"),handler:$},{method:"POST",pattern:Ae("/v1/agents/:name/schedule"),handler:z},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/pause"),handler:Q},{method:"POST",pattern:Ae("/v1/agents/:name/schedule/resume"),handler:ie},{method:"POST",pattern:Ae("/v1/shutdown"),handler:it},{method:"POST",pattern:Ae("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:Ae("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:Ae("/v1/agents/:name/setup"),handler:p("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let C=E.slice(7),k=t.tokenSource();if(k===null)return{ok:!1,reason:"token_unset"};let j=wc.from(C,"utf8"),X=wc.from(k,"utf8");return j.length!==X.length?{ok:!1,reason:"token_mismatch"}:Gm.timingSafeEqual(j,X)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,C){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",Dm),w.statusCode=E,w.end(JSON.stringify(C)))}function d(w,E,C,k,j){u(w,E,j===void 0?{error:{code:C,message:k}}:{error:{code:C,message:k,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Wm,uptimeMs:o.now()-i})}function p(w){return E=>{let C=E.url.pathname;throw new B(501,"not_implemented",`${C} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",Dm),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Um);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,C;try{C=t.router.getAgent({name:E})}catch(j){throw yc(j)?new B(404,"not_found",`agent '${E}' not found`):j}let k=C.snapshot();u(w.res,200,{agent:Um(k)})}async function S(w){let E=w.params.name,C=await Fm(w.req,r);Bm(C,["game"],"/v1/agents/:name/join");let k=C;if(typeof k.game!="string"||k.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if(k.mode!==void 0&&typeof k.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if(k.one_shot!==void 0&&typeof k.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if(k.oneShot!==void 0&&typeof k.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=k.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let X=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...X!==void 0?{oneShot:X}:{},...typeof j=="number"?{count:j}:{}})}catch(K){throw yc(K)?new B(404,"not_found",`agent '${E}' not found`):K}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(C){throw yc(C)?new B(404,"not_found",`agent '${E}' not found`):C}g(w.res)}function $(w){let E=w.params.name,C=f(E),k=m(E),j=PE(C.snapshot());u(w.res,200,{schedule:k,snapshot:j})}async function z(w){let E=w.params.name,C=f(E),k=await Fm(w.req,r),j;if(k===null)j=null;else{Bm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let X=k;if(typeof X.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof X.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof X.days!="object"||X.days===null||Array.isArray(X.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{C.setSchedule(j)}catch(X){let K=qm(X);throw K||X}a.set(E,j),g(w.res)}function Q(w){ze(w,!1)}function ie(w){ze(w,!0)}function ze(w,E){let C=w.params.name,k=f(C),j=m(C);if(j===null){let K=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${K}; POST /schedule first or configure initial schedule`)}let X={...j,enabled:E};try{k.setSchedule(X)}catch(K){let eo=qm(K);throw eo||K}a.set(C,X),g(w.res)}function it(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${_c(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function nr(w,E){let C=o.now(),k=w.method??"GET",j=w.url??"/",X=`http://${w.headers.host??"localhost"}`,K;try{K=new URL(j,X)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${k} ${j} -> 400 (${o.now()-C}ms)`,method:k,path:j,status:400,durationMs:o.now()-C});return}let eo=Vm(K.pathname),rr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${K.pathname}: auth failed (${Ee.reason})`,method:k,path:K.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let pi=s.map(bt=>({route:bt,params:RE(bt.pattern,eo)})).filter(bt=>bt.params!==null);if(pi.length===0)throw new B(404,"not_found","path not found");let hi=pi.find(bt=>bt.route.method===k);if(!hi){let bt=pi.map(gi=>gi.route.method).filter((gi,gp,yp)=>yp.indexOf(gi)===gp).join(", ");throw E.headersSent||E.setHeader("Allow",bt),new B(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${K.pathname}`,method:k,path:K.pathname}),await hi.route.handler({req:w,res:E,url:K,params:hi.params}),rr=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),rr=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${K.pathname}: ${_c(Ee)}`,method:k,path:K.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),rr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${K.pathname} -> ${rr} (${o.now()-C}ms)`,method:k,path:K.pathname,status:rr,durationMs:o.now()-C})}}let Ke=Hm.createServer((w,E)=>{nr(w,E).catch(C=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${_c(C)}`,method:w.method,path:w.url,cause:C}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),ne="pre-listen",Bt=null,wn=null,Zr=null;function mp(){return ne==="listening"?Promise.reject(new _n("invalid_state","server already listening")):ne==="closing"||ne==="closed"||ne==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let C=k=>{ne="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Ke.once("error",C),Ke.listen({host:e,port:n},()=>{Ke.off("error",C);let k=Ke.address();if(typeof k=="string"||k===null){ne="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Bt=k.address,wn=k.port,ne="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Bt}:${wn}`,host:Bt,port:wn}),w(wn)})})}function pp(){return ne!=="listening"||Bt===null||wn===null?null:{host:Bt,port:wn}}function hp(){return ne==="pre-listen"||ne==="bind-failed"?(ne="closed",Promise.resolve()):ne==="closed"?Promise.resolve():(ne==="closing"&&Zr||(ne="closing",Zr=new Promise(w=>{let E=!1,C=()=>{E||(E=!0,clearTimeout(j),ne="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Ke.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Ke)}catch{}C()},$E);j.unref(),Ke.close(()=>C())})),Zr)}return{listen:mp,address:pp,close:hp}}function _c(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function vc(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function Km(t,e){if(e.type==="start")return U(vc(e));if(t.phase==="closed")return e.type==="stop"?U(t):Ve(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return TE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return AE(t);case"command.confirm_match":return CE(t,e.confirmId);case"ws.message":return xE(t,e.message,e.now);case"decision.ready":return DE(t,e.action);case"decision.failed":return FE(t,e.reason);case"reconnect.event":return HE(t,e.event);case"reconnect.close":return GE(t,e.info);case"stop":return U({...t,phase:"closed",transport:"closed"})}}function TE(t,e,n,r){if(!t.availableGames.includes(e))return Ve(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Yr(n),...r===!0?{one_shot:!0}:{}};return U({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function AE(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?Ve(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function CE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?Ve(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):U({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function xE(t,e,n){switch(e.type){case"queue_joined":return IE(t,e);case"queue_left":return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return OE(t,e);case"match_cancelled":return NE(t,e);case"game_start":return ME(t,e,n);case"game_state":return LE(t,e);case"action_request":return jE(t,e);case"game_over":return BE(t,e);case"error":return qE(t,e);case"event":return UE(t,e);default:return Ve(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function IE(t,e){return U({...t,phase:"queuing",queue:{game:e.data.game,mode:Yr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function OE(t,e){let n={game:e.data.game,mode:Yr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?U({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):U({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[We("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function NE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Yr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Yr(e.data.mode)}:n;return U({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function ME(t,e,n){return U({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function LE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function jE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?Ve(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?Ve(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function DE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):U({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function FE(t,e){return t.phase!=="deciding"||!t.pendingAction?Ve(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):U(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function BE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?Ve(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):U({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function qE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return U({...t,lastError:n},[We("error","server.error",n)])}function UE(t,e){return U(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function HE(t,e){return e.type==="attempt-success"?U({...t,transport:"connected"}):e.type==="attempt-start"?U({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?U({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):U({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function GE(t,e){return U({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function U(t,e=[]){return{state:t,effects:e}}function Ve(t,e,n){return U(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Yr(t){return t&&t.length>0?t:"ranked"}var tr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Qr=class extends tr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Xr=class extends tr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},li=class extends tr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},bc=class extends tr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},ui=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new li(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Qr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??qa,n;try{n=await e(this.#e.ws)}catch(r){throw new Qr(`failed to start agent '${this.#e.name}': ${ci(r)}`,r)}if(n.welcome===null)throw new Qr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=vc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#k()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#$();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#k()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=WE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#p({type:"runtime_status",data:VE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Jm(`readiness check failed: ${ci(r)}`)}})}}#s(e){let n=this.#S(),r=Km(n,e);this.#n=r.state,this.#f(),this.#h(r.effects)}#h(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${ci(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#p(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#p(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${ci(r)}`,cause:new bc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new li(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Xr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#$(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#k(){return this.#e.now?.()??Date.now()}};function ci(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function WE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function VE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Jm(n.detail)),n}function Jm(t){return t.length>240?t.slice(0,240):t}function Ym(t){return{async decide(e){let n=QE(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:XE(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return di(n,o,r.state)}}return zE({game:n,raw:s,legalActions:o,publicState:r.state})}}}function Qm(){return{name:"mock",async decide(t){return di(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function zE(t){if(typeof t.raw!="string")return YE(t.raw,t.legalActions)??di(t.game,t.legalActions,t.publicState);let e=KE(t.game,t.raw,t.legalActions);return e!==null?e:di(t.game,t.legalActions,t.publicState)}function KE(t,e,n){let r=JE(e),o=t==="texas_holdem"?za(r,n):t==="liars_dice"?Ja(r,n):Ya(r,n);return o.kind==="ok"?o.action:null}function JE(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function YE(t,e){let n=e.find(o=>ZE(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function di(t,e,n){return t==="texas_holdem"?Ua({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):Wa({publicState:n,legalActions:e,yourPlayerId:"p0"})}function QE(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function XE(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function ZE(t,e){return JSON.stringify(t)===JSON.stringify(e)}var ek="http://127.0.0.1:18789",tk="openclaw/default";function Xm(t){let e=(t.baseUrl??ek).replace(/\/+$/,""),n=t.model??tk,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:nk(t,o),body:JSON.stringify({model:n,input:rk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=ok(s);return ik(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function nk(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function rk(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
|
|
210
|
-
`)}function
|
|
211
|
-
`):null}function
|
|
212
|
-
`)}function
|
|
213
|
-
`):null}function
|
|
214
|
-
`)}function
|
|
215
|
-
`)
|
|
216
|
-
`)
|
|
217
|
-
`),
|
|
210
|
+
`)}return 0}function yE(){try{return ne()}catch(t){throw(t instanceof Error?t.message:String(t)).includes("bridge is not configured")?new U("bridge_not_configured","AIFight Bridge is not configured.",{hint:"Run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent. Then install `aifight.service` before requesting manual matches."}):t}}function _E(t,e){if(t.length===0)return{game:xm(e.autoGames),count:1};let n=t[0];if(t.length===1){let i=Tm(n);if(i!==null)return{game:xm(e.autoGames),count:i};if(ct(n))return{game:n,count:1};throw new O(`unsupported game or count '${n}'`,ci)}let r=t[1];if(!ct(n))throw new O(`unsupported game '${n}'`,ci);let o=Tm(r);if(o===null)throw new O(`N must be an integer between 1 and ${mc}`,ci);return{game:n,count:o}}function Tm(t){if(!/^\d+$/.test(t))return null;let e=Number.parseInt(t,10);return!Number.isInteger(e)||e<1||e>mc?null:e}function xm(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}function wE(t){return t.kind==="daemon_unreachable"?"bridge_not_running":t.kind==="runtime_files_corrupt"?"bridge_runtime_files_invalid":t.kind==="auth_failed"?"bridge_control_auth_failed":t.kind==="request_timeout"?"bridge_control_timeout":"bridge_control_failed"}function vE(t){return t.kind==="daemon_unreachable"?"AIFight Bridge is not running.":t.kind==="runtime_files_corrupt"?"AIFight Bridge runtime files are invalid.":t.kind==="auth_failed"?"AIFight Bridge rejected the local control token.":t.kind==="request_timeout"?"AIFight Bridge did not answer the local control request in time.":t.message}async function bE(t){try{let e=await St(t.bridgeService);if(e.installed&&e.running===!1)return"Start it with `aifight service start`, then run this command again.";if(e.installed&&e.running===!0)return"The service appears to be running, but its local control API did not answer. Try `aifight service restart` when no match is in progress."}catch(e){if(!(e instanceof Q))throw e}return"Install the background service with `aifight service install`, or self-manage `aifight run` as an advanced path."}function SE(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup"}}import Bt from"node:path";import te from"node:fs";import EE from"node:crypto";var _e=class extends Error{name="RuntimeFilesWriteError";kind;filePath;heldByPid;cause;constructor(e,n,r,o){super(r),this.kind=e,this.filePath=n,o?.heldByPid!==void 0&&(this.heldByPid=o.heldByPid),o?.cause!==void 0&&(this.cause=o.cause)}};function Om(){return Bt.join(oe(),"token")}function Nm(){return Bt.join(oe(),"port")}function hc(){return Bt.join(oe(),"pid")}function kE(){return Bt.join(oe(),"lock")}var Im=0,$E=/^[0-9a-f]{64}$/;function gc(t,e,n){let r=Bt.dirname(t),o=Bt.basename(t);Im+=1;let i=Bt.join(r,`${o}.${process.pid}.${Im}.tmp`),s;try{if(s=te.openSync(i,"w",n),te.writeSync(s,e),te.closeSync(s),s=void 0,process.platform!=="win32")try{te.chmodSync(i,n)}catch{}te.renameSync(i,t)}catch(a){if(s!==void 0)try{te.closeSync(s)}catch{}try{te.unlinkSync(i)}catch{}throw new _e("write_failed",t,`failed to write ${t}: ${a.message}`,{cause:a})}}function Lm(){return EE.randomBytes(32).toString("hex")}function Mm(t){let e=Om();if(!$E.test(t))throw new _e("write_failed",e,`token must match /^[0-9a-f]{64}$/ but received "${t}" (length ${t.length})`);gc(e,t,384)}function jm(t){let e=Nm();if(!Number.isInteger(t)||t<1||t>65535)throw new _e("write_failed",e,`port must be an integer in [1, 65535] but received ${t}`);gc(e,String(t),420)}function Dm(t){let e=hc();if(!Number.isInteger(t)||t<1)throw new _e("write_failed",e,`pid must be a positive integer but received ${t}`);gc(e,String(t),420)}function yc(t){for(let e of[Om(),Nm(),hc()])try{te.unlinkSync(e)}catch(n){if(n.code==="ENOENT")continue;t.onLog?.(`failed to unlink ${e}: ${n.message}`)}}function Fm(){let t=oe(),e;try{e=te.readdirSync(t)}catch{return}for(let n of e)if(n.endsWith(".tmp"))try{te.unlinkSync(Bt.join(t,n))}catch{}}var pc=new Set;function RE(t){try{return process.kill(t,0),!0}catch(e){return e.code!=="ESRCH"}}function PE(t){let e;try{e=te.readFileSync(t,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"missing"}:{kind:"read_error",cause:o}}let n=e.trim();if(n.length===0)return{kind:"invalid",raw:n};if(!/^\d+$/.test(n))return{kind:"invalid",raw:n};let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<1?{kind:"invalid",raw:n}:{kind:"valid",pid:r}}function Bm(t){let e=kE(),n=hc(),r=t?.processIsAlive??RE;if(pc.has(e))throw new _e("lock_acquire_failed",e,`lock at ${e} already held by this process; release the existing handle first (reentrancy guard)`);for(let o=0;o<2;o+=1)try{let i=te.openSync(e,te.constants.O_WRONLY|te.constants.O_CREAT|te.constants.O_EXCL,384);if(te.closeSync(i),process.platform!=="win32")try{te.chmodSync(e,384)}catch{}return pc.add(e),AE(e)}catch(i){if(i.code!=="EEXIST")throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e}: ${i.message}`,{cause:i});let a=PE(n);if(a.kind==="missing")throw new _e("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} is missing \u2014 ambiguous (possibly a racing daemon between acquireDaemonLock and writePid); refusing to steal lock. If the previous daemon truly crashed, manually remove ${e}.`);if(a.kind==="invalid")throw new _e("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} content is invalid (raw="${a.raw}") \u2014 ambiguous; refusing to steal lock. Manually remove both files if you confirm no daemon is running.`);if(a.kind==="read_error")throw new _e("lock_acquire_failed",e,`lock at ${e} exists but pid file ${n} could not be read (${a.cause.code??"unknown"}: ${a.cause.message}) \u2014 ambiguous; refusing to steal lock.`,{cause:a.cause});if(r(a.pid))throw new _e("lock_held_by_other",e,`lock at ${e} held by live PID ${a.pid}`,{heldByPid:a.pid});try{te.unlinkSync(e)}catch{}try{te.unlinkSync(n)}catch{}}throw new _e("lock_acquire_failed",e,`failed to acquire lock at ${e} after stale-cleanup retry; another daemon may be racing`)}function AE(t){let e=!1;return{release(){if(!e){e=!0,pc.delete(t);try{te.unlinkSync(t)}catch{}}}}}import*as Wm from"node:http";import{Buffer as vc}from"node:buffer";import*as zm from"node:crypto";var _n=class extends Error{name="ControlServerError";kind;cause;constructor(e,n,r){super(n),this.kind=e,this.cause=r}};var Km="0.1.0-alpha.6",Um=`aifight-runtime/${Km}`,TE="127.0.0.1",xE=0,CE=1048576,IE=5e3,B=class extends Error{name="HttpError";status;code;details;constructor(e,n,r,o){super(r),this.status=e,this.code=n,this.details=o}};function Jm(t){return t.split("/").filter(e=>e.length>0)}function Te(t){let e=Jm(t).map(n=>n.startsWith(":")?{param:n.slice(1)}:{literal:n});return{raw:t,segments:e}}function OE(t,e){if(t.segments.length!==e.length)return null;let n={};for(let r=0;r<t.segments.length;r++){let o=t.segments[r],i=e[r];if(o.literal!==void 0){if(o.literal!==i)return null}else if(o.param!==void 0)try{n[o.param]=decodeURIComponent(i)}catch{return null}}return n}async function qm(t,e){if(((t.headers["content-type"]??"").toString().split(";")[0]?.trim().toLowerCase()??"")!=="application/json")throw new B(415,"unsupported_media_type","Content-Type must be application/json");let o=[],i=0,s=!1;for await(let c of t){if(s)continue;let l=c;if(i+=l.length,i>e)throw s=!0,new B(413,"payload_too_large",`request body exceeds ${e} bytes`);o.push(l)}let a=vc.concat(o).toString("utf8");if(a.length===0)throw new B(400,"bad_request","request body required");try{return JSON.parse(a)}catch(c){throw new B(400,"bad_request",`invalid JSON: ${c instanceof Error?c.message:String(c)}`)}}function Hm(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new B(400,"bad_request",`${n} body must be a JSON object`,{missing_fields:[...e]});let r=t,o=e.filter(i=>!Object.prototype.hasOwnProperty.call(r,i));if(o.length>0)throw new B(400,"bad_request",`missing required fields: ${o.join(", ")}`,{missing_fields:o})}function _c(t){return typeof t=="object"&&t!==null&&"kind"in t&&t.kind==="router_agent_not_found"}function Gm(t){if(typeof t!="object"||t===null||!("kind"in t))return null;let e=t.kind,n=t instanceof Error?t.message:"schedule operation failed";return e==="invalid_timezone"||e==="invalid_count"||e==="invalid_min_interval"?new B(400,"bad_request",n,{validation:e}):e==="invalid_state"?new B(503,"service_unavailable","scheduler stopped"):null}function Vm(t){if(t.state===null)return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:null};let e=t.state,n={phase:e.phase,agentId:e.agentId,agentName:e.agentName,availableGames:e.availableGames,autoConfirmMatches:e.autoConfirmMatches,...e.queue!==void 0?{queue:e.queue}:{},...e.activeMatch!==void 0?{activeMatch:e.activeMatch}:{}};return{name:t.name,started:t.started,stopped:t.stopped,transport:t.transport,state:n}}function NE(t){let e=t.lastAttempt===null?null:{atMs:t.lastAttempt.atMs,game:t.lastAttempt.game,outcome:t.lastAttempt.outcome};return{running:t.running,today:t.today,remaining:t.remaining,nextFireInMs:t.nextFireInMs,lastAttempt:e}}function Ym(t){let e=t.host??TE,n=t.port??xE,r=t.bodyLimitBytes??CE,o=t.clock??{now:()=>Date.now()},i=o.now(),s=[{method:"GET",pattern:Te("/v1/health"),handler:h},{method:"GET",pattern:Te("/v1/agents"),handler:y},{method:"GET",pattern:Te("/v1/agents/:name/status"),handler:v},{method:"POST",pattern:Te("/v1/agents/:name/join"),handler:S},{method:"POST",pattern:Te("/v1/agents/:name/leave"),handler:R},{method:"GET",pattern:Te("/v1/agents/:name/schedule"),handler:$},{method:"POST",pattern:Te("/v1/agents/:name/schedule"),handler:K},{method:"POST",pattern:Te("/v1/agents/:name/schedule/pause"),handler:X},{method:"POST",pattern:Te("/v1/agents/:name/schedule/resume"),handler:ae},{method:"POST",pattern:Te("/v1/shutdown"),handler:st},{method:"POST",pattern:Te("/v1/agents"),handler:p("M1-18")},{method:"DELETE",pattern:Te("/v1/agents/:name"),handler:p("M1-18")},{method:"POST",pattern:Te("/v1/agents/:name/setup"),handler:p("M1-18")}],a=new Map;function c(w){if(t.onLog)try{t.onLog(w)}catch{}}function l(w){let E=w.headers.authorization;if(!E)return{ok:!1,reason:"missing_header"};if(!E.startsWith("Bearer "))return{ok:!1,reason:"invalid_format"};let x=E.slice(7),k=t.tokenSource();if(k===null)return{ok:!1,reason:"token_unset"};let j=vc.from(x,"utf8"),Z=vc.from(k,"utf8");return j.length!==Z.length?{ok:!1,reason:"token_mismatch"}:zm.timingSafeEqual(j,Z)?{ok:!0}:{ok:!1,reason:"token_mismatch"}}function u(w,E,x){w.headersSent||(w.setHeader("Content-Type","application/json; charset=utf-8"),w.setHeader("Server",Um),w.statusCode=E,w.end(JSON.stringify(x)))}function d(w,E,x,k,j){u(w,E,j===void 0?{error:{code:x,message:k}}:{error:{code:x,message:k,details:j}})}function h(w){u(w.res,200,{status:"ok",version:Km,uptimeMs:o.now()-i})}function p(w){return E=>{let x=E.url.pathname;throw new B(501,"not_implemented",`${x} deferred to ${w} daemon lifecycle wiring`,{retry_after_milestone:w})}}function f(w){let E=t.schedulerLookup?.(w)??null;if(!E)throw new B(404,"not_found",`agent '${w}' has no scheduler`);return E}function m(w){return a.has(w)?a.get(w)??null:t.scheduleConfigLookup?.(w)??null}function g(w){w.headersSent||(w.setHeader("Server",Um),w.statusCode=204,w.end())}function y(w){let E=t.router.listAgents().map(Vm);u(w.res,200,{agents:E})}function v(w){let E=w.params.name,x;try{x=t.router.getAgent({name:E})}catch(j){throw _c(j)?new B(404,"not_found",`agent '${E}' not found`):j}let k=x.snapshot();u(w.res,200,{agent:Vm(k)})}async function S(w){let E=w.params.name,x=await qm(w.req,r);Hm(x,["game"],"/v1/agents/:name/join");let k=x;if(typeof k.game!="string"||k.game.length===0)throw new B(400,"bad_request","field 'game' must be a non-empty string",{invalid_field:"game"});if(k.mode!==void 0&&typeof k.mode!="string")throw new B(400,"bad_request","field 'mode' must be a string when present",{invalid_field:"mode"});if(k.one_shot!==void 0&&typeof k.one_shot!="boolean")throw new B(400,"bad_request","field 'one_shot' must be a boolean when present",{invalid_field:"one_shot"});if(k.oneShot!==void 0&&typeof k.oneShot!="boolean")throw new B(400,"bad_request","field 'oneShot' must be a boolean when present",{invalid_field:"oneShot"});let j=k.count;if(j!==void 0&&(typeof j!="number"||!Number.isInteger(j)||j<1||j>20))throw new B(400,"bad_request","field 'count' must be an integer between 1 and 20 when present",{invalid_field:"count"});let Z=k.one_shot??k.oneShot;try{t.router.joinQueue({name:E},k.game,k.mode,{...Z!==void 0?{oneShot:Z}:{},...typeof j=="number"?{count:j}:{}})}catch(J){throw _c(J)?new B(404,"not_found",`agent '${E}' not found`):J}g(w.res)}function R(w){let E=w.params.name;try{t.router.leaveQueue({name:E})}catch(x){throw _c(x)?new B(404,"not_found",`agent '${E}' not found`):x}g(w.res)}function $(w){let E=w.params.name,x=f(E),k=m(E),j=NE(x.snapshot());u(w.res,200,{schedule:k,snapshot:j})}async function K(w){let E=w.params.name,x=f(E),k=await qm(w.req,r),j;if(k===null)j=null;else{Hm(k,["enabled","timezone","days"],"/v1/agents/:name/schedule");let Z=k;if(typeof Z.enabled!="boolean")throw new B(400,"bad_request","field 'enabled' must be a boolean",{invalid_field:"enabled"});if(typeof Z.timezone!="string")throw new B(400,"bad_request","field 'timezone' must be a string",{invalid_field:"timezone"});if(typeof Z.days!="object"||Z.days===null||Array.isArray(Z.days))throw new B(400,"bad_request","field 'days' must be an object",{invalid_field:"days"});j=k}try{x.setSchedule(j)}catch(Z){let J=Gm(Z);throw J||Z}a.set(E,j),g(w.res)}function X(w){Ke(w,!1)}function ae(w){Ke(w,!0)}function Ke(w,E){let x=w.params.name,k=f(x),j=m(x);if(j===null){let J=E?"resume":"pause";throw new B(400,"bad_request",`no schedule to ${J}; POST /schedule first or configure initial schedule`)}let Z={...j,enabled:E};try{k.setSchedule(Z)}catch(J){let to=Gm(J);throw to||J}a.set(x,Z),g(w.res)}function st(w){c({level:"info",code:"shutdown_requested",message:"shutdown requested via POST /v1/shutdown",method:"POST",path:"/v1/shutdown"}),u(w.res,200,{status:"shutting_down"}),setImmediate(()=>{Promise.resolve().then(()=>t.onShutdown?.()).catch(E=>{c({level:"error",code:"handler_threw",message:`onShutdown threw/rejected: ${wc(E)}`,cause:E,method:"POST",path:"/v1/shutdown"})})})}async function nr(w,E){let x=o.now(),k=w.method??"GET",j=w.url??"/",Z=`http://${w.headers.host??"localhost"}`,J;try{J=new URL(j,Z)}catch{d(E,400,"bad_request","invalid request URL"),c({level:"info",code:"request_completed",message:`${k} ${j} -> 400 (${o.now()-x}ms)`,method:k,path:j,status:400,durationMs:o.now()-x});return}let to=Jm(J.pathname),rr=0;try{let Ee=l(w);if(!Ee.ok)throw c({level:"warn",code:"auth_failed",message:`${k} ${J.pathname}: auth failed (${Ee.reason})`,method:k,path:J.pathname,reason:Ee.reason}),new B(401,"unauthorized",`authentication required: ${Ee.reason}`);let gi=s.map(Et=>({route:Et,params:OE(Et.pattern,to)})).filter(Et=>Et.params!==null);if(gi.length===0)throw new B(404,"not_found","path not found");let yi=gi.find(Et=>Et.route.method===k);if(!yi){let Et=gi.map(_i=>_i.route.method).filter((_i,Ep,kp)=>kp.indexOf(_i)===Ep).join(", ");throw E.headersSent||E.setHeader("Allow",Et),new B(405,"method_not_allowed",`method ${k} not allowed`)}c({level:"info",code:"request_received",message:`${k} ${J.pathname}`,method:k,path:J.pathname}),await yi.route.handler({req:w,res:E,url:J,params:yi.params}),rr=E.statusCode}catch(Ee){Ee instanceof B?(d(E,Ee.status,Ee.code,Ee.message,Ee.details),rr=Ee.status):(c({level:"error",code:"handler_threw",message:`handler threw on ${k} ${J.pathname}: ${wc(Ee)}`,method:k,path:J.pathname,cause:Ee}),d(E,500,"internal_error","internal server error"),rr=500)}finally{w.complete||(w.on("data",()=>{}),w.on("error",()=>{})),c({level:"info",code:"request_completed",message:`${k} ${J.pathname} -> ${rr} (${o.now()-x}ms)`,method:k,path:J.pathname,status:rr,durationMs:o.now()-x})}}let Je=Wm.createServer((w,E)=>{nr(w,E).catch(x=>{if(c({level:"error",code:"handler_threw",message:`dispatch escaped: ${wc(x)}`,method:w.method,path:w.url,cause:x}),!E.headersSent)try{d(E,500,"internal_error","internal server error")}catch{try{E.end()}catch{}}})}),re="pre-listen",Ut=null,wn=null,eo=null;function vp(){return re==="listening"?Promise.reject(new _n("invalid_state","server already listening")):re==="closing"||re==="closed"||re==="bind-failed"?Promise.reject(new _n("invalid_state","server has been closed; create a new ControlServer")):new Promise((w,E)=>{let x=k=>{re="bind-failed",E(new _n("bind_failed",`failed to bind ${e}:${n}: ${k.message}`,k))};Je.once("error",x),Je.listen({host:e,port:n},()=>{Je.off("error",x);let k=Je.address();if(typeof k=="string"||k===null){re="bind-failed",E(new _n("bind_failed","unexpected listen address shape from server.address()"));return}Ut=k.address,wn=k.port,re="listening",c({level:"info",code:"server_listening",message:`control API server listening on ${Ut}:${wn}`,host:Ut,port:wn}),w(wn)})})}function bp(){return re!=="listening"||Ut===null||wn===null?null:{host:Ut,port:wn}}function Sp(){return re==="pre-listen"||re==="bind-failed"?(re="closed",Promise.resolve()):re==="closed"?Promise.resolve():(re==="closing"&&eo||(re="closing",eo=new Promise(w=>{let E=!1,x=()=>{E||(E=!0,clearTimeout(j),re="closed",c({level:"info",code:"server_closed",message:"control API server closed"}),w())},k=Je.closeAllConnections,j=setTimeout(()=>{if(typeof k=="function")try{k.call(Je)}catch{}x()},IE);j.unref(),Je.close(()=>x())})),eo)}return{listen:vp,address:bp,close:Sp}}function wc(t){if(t instanceof Error)return`${t.name}: ${t.message}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function bc(t){return{phase:"connected",transport:"connected",agentId:t.welcome.data.agent_id,agentName:t.welcome.data.agent_name,availableGames:[...t.welcome.data.games],autoConfirmMatches:t.autoConfirmMatches??!0}}function Qm(t,e){if(e.type==="start")return H(bc(e));if(t.phase==="closed")return e.type==="stop"?H(t):ze(t,"fsm.closed",`Ignoring ${e.type} because agent FSM is closed`);switch(e.type){case"command.join_queue":return LE(t,e.game,e.mode,e.oneShot);case"command.leave_queue":return ME(t);case"command.confirm_match":return jE(t,e.confirmId);case"ws.message":return DE(t,e.message,e.now);case"decision.ready":return VE(t,e.action);case"decision.failed":return WE(t,e.reason);case"reconnect.event":return YE(t,e.event);case"reconnect.close":return QE(t,e.info);case"stop":return H({...t,phase:"closed",transport:"closed"})}}function LE(t,e,n,r){if(!t.availableGames.includes(e))return ze(t,"fsm.unknown_game",`Cannot join unavailable game '${e}'`);let o={game:e,mode:Qr(n),...r===!0?{one_shot:!0}:{}};return H({...t,phase:"queuing",queue:o,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:void 0},[{type:"send",message:{type:"join_queue",data:o}}])}function ME(t){return t.phase!=="queuing"&&t.phase!=="confirming"&&t.phase!=="matching"?ze(t,"fsm.not_queued","Ignoring leave_queue because agent is not queued"):H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0},[{type:"send",message:{type:"leave_queue"}}])}function jE(t,e){let n=e??t.pendingConfirm?.confirm_id;return!n||t.phase!=="confirming"?ze(t,"fsm.no_pending_confirm","Ignoring match confirmation without a pending confirm request"):H({...t,phase:"matching",pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:n}}}])}function DE(t,e,n){switch(e.type){case"queue_joined":return FE(t,e);case"queue_left":return H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0});case"match_confirm_request":return BE(t,e);case"match_cancelled":return UE(t,e);case"game_start":return qE(t,e,n);case"game_state":return HE(t,e);case"action_request":return GE(t,e);case"game_over":return zE(t,e);case"error":return KE(t,e);case"event":return JE(t,e);default:return ze(t,"fsm.unknown_server_message",`Ignoring unknown server message '${e.type}'`)}}function FE(t,e){return H({...t,phase:"queuing",queue:{game:e.data.game,mode:Qr(e.data.mode),...e.data.one_shot===!0?{one_shot:!0}:{}}})}function BE(t,e){let n={game:e.data.game,mode:Qr(e.data.mode),...t.queue?.one_shot===!0?{one_shot:!0}:{}};return t.autoConfirmMatches?H({...t,phase:"matching",queue:n,pendingConfirm:void 0},[{type:"send",message:{type:"match_confirm",data:{confirm_id:e.data.confirm_id}}}]):H({...t,phase:"confirming",queue:n,pendingConfirm:e.data},[We("info","fsm.match_confirm_required",`Match confirmation required for ${e.data.game}/${e.data.mode}`)])}function UE(t,e){if(e.data.action==="re_queued"){let n=t.pendingConfirm?{game:t.pendingConfirm.game,mode:Qr(t.pendingConfirm.mode)}:t.queue,r=e.data.reason==="opponent_disconnected"?{game:e.data.game,mode:Qr(e.data.mode)}:n;return H({...t,phase:r?"queuing":"connected",queue:r,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}return H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0},[We("warning","fsm.match_cancelled",`Match cancelled: ${e.data.reason}`)])}function qE(t,e,n){return H({...t,phase:"in_match",queue:void 0,pendingConfirm:void 0,pendingAction:void 0,activeMatch:{sessionId:e.data.match_id,game:e.data.game,startedAt:n??0}})}function HE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.game_state_mismatch",`Ignoring game_state for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:t.activeMatch?"in_match":t.phase},[We("info","fsm.game_state","Received game state update")])}function GE(t,e){return t.phase!=="in_match"&&t.phase!=="deciding"?ze(t,"fsm.action_request_out_of_phase","Ignoring action_request outside an active match"):t.activeMatch&&t.activeMatch.sessionId!==e.data.match_id?ze(t,"fsm.action_request_mismatch",`Ignoring action_request for session ${e.data.match_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:"deciding",pendingAction:e},[{type:"request_decision",actionRequest:e,matchId:e.data.match_id,game:t.activeMatch?.game}])}function VE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision result without a pending action_request"):H({...t,phase:"in_match",pendingAction:void 0},[{type:"send",message:{type:"action",match_id:t.pendingAction.data.match_id,data:e}}])}function WE(t,e){return t.phase!=="deciding"||!t.pendingAction?ze(t,"fsm.no_pending_action","Ignoring decision failure without a pending action_request"):H(t,[{type:"fallback_required",actionRequest:t.pendingAction,reason:e}])}function zE(t,e){return t.activeMatch&&t.activeMatch.sessionId!==e.data.session_id?ze(t,"fsm.game_over_mismatch",`Ignoring game_over for session ${e.data.session_id}; active session is ${t.activeMatch.sessionId}`):H({...t,phase:"connected",queue:void 0,pendingConfirm:void 0,activeMatch:void 0,pendingAction:void 0,lastGameOver:e},[{type:"record_result",gameOver:e,...t.activeMatch?.game!==void 0?{game:t.activeMatch.game}:{}}])}function KE(t,e){let n=typeof e.data.message=="string"?e.data.message:"Server error";return H({...t,lastError:n},[We("error","server.error",n)])}function JE(t,e){return H(t,[We("info","server.event",`Received server event batch (${e.data.events.length} events)`)])}function YE(t,e){return e.type==="attempt-success"?H({...t,transport:"connected"}):e.type==="attempt-start"?H({...t,transport:"backoff"},[We("info","reconnect.attempt_start",`Reconnect attempt ${e.attempt} started`)]):e.type==="attempt-failure"?H({...t,transport:"backoff"},[We(e.severity,"reconnect.attempt_failure",`Reconnect attempt ${e.attempt} failed`)]):H({...t,phase:"closed",transport:"closed"},[We(e.severity,"reconnect.give_up","Reconnect gave up")])}function QE(t,e){return H({...t,phase:"closed",transport:"closed"},[We("error","reconnect.closed",`Reconnect closed: ${e.kind}`)])}function H(t,e=[]){return{state:t,effects:e}}function ze(t,e,n){return H(t,[We("warning",e,n)])}function We(t,e,n){return{type:"notify",level:t,code:e,message:n}}function Qr(t){return t&&t.length>0?t:"ranked"}var tr=class extends Error{cause;constructor(e,n){super(e),this.cause=n}},Xr=class extends tr{name="AgentInstanceStartError";kind="agent_start";constructor(e,n){super(e,n)}},Zr=class extends tr{name="AgentInstanceNotStartedError";kind="agent_not_started";constructor(e,n){super(e,n)}},ui=class extends tr{name="AgentInstanceStoppedError";kind="agent_stopped";constructor(e,n){super(e,n)}},Sc=class extends tr{name="AgentInstanceEffectError";kind="agent_effect";constructor(e,n){super(e,n)}},di=class{#e;#t=null;#n=null;#r=!1;#o=!1;#a=[];#c=new Set;#u=Promise.resolve();#g=0;#d=null;constructor(e){this.#e=e}async start(){if(this.#o)throw new ui(`agent '${this.#e.name}' has been stopped`);if(this.#r)throw new Xr(`agent '${this.#e.name}' is already started`);let e=this.#e.connect??Ha,n;try{n=await e(this.#e.ws)}catch(r){throw new Xr(`failed to start agent '${this.#e.name}': ${li(r)}`,r)}if(n.welcome===null)throw new Xr(`failed to start agent '${this.#e.name}': reconnect client returned without welcome`);return this.#t=n,this.#n=bc({welcome:n.welcome,autoConfirmMatches:this.#e.autoConfirmMatches,now:this.#k()}),this.#r=!0,this.#l(n),this.#f(),this.snapshot()}async stop(e="agent stop"){if(this.#o)return;this.#o=!0,this.#$();let n=this.#t;n!==null&&n.state!=="closed"&&await n.close(1e3,e),this.#n!==null&&this.#s({type:"stop",reason:e})}joinQueue(e,n,r={}){this.#w(),this.#s({type:"command.join_queue",game:e,mode:n,oneShot:r.oneShot})}leaveQueue(){this.#w(),this.#s({type:"command.leave_queue"})}confirmMatch(e){this.#w(),this.#s({type:"command.confirm_match",confirmId:e})}snapshot(){return{name:this.#e.name,state:this.#n,transport:this.#t?.state??"idle",started:this.#r,stopped:this.#o}}onState(e){return this.#c.add(e),()=>{this.#c.delete(e)}}#l(e){this.#a.push(e.onMessage(n=>{if(n.type==="readiness_check"){this.#i(n.data);return}this.#s({type:"ws.message",message:n,now:this.#k()})}),e.onReconnect(n=>{this.#s({type:"reconnect.event",event:n})}),e.onClose(n=>{this.#s({type:"reconnect.close",info:n})}),e.onError(n=>{this.#R(n)}))}async#i(e){let n=XE(e);try{let r=this.#e.onReadinessCheck?await this.#e.onReadinessCheck(e):{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:"readiness check handler is not configured"};this.#p({type:"runtime_status",data:ZE(r,n)})}catch(r){this.#p({type:"runtime_status",data:{request_id:n,ready:!1,runtime_type:"mock",checked_at:new Date().toISOString(),detail:Xm(`readiness check failed: ${li(r)}`)}})}}#s(e){let n=this.#S(),r=Qm(n,e);this.#n=r.state,this.#f(),this.#h(r.effects)}#h(e){e.length!==0&&(this.#u=this.#u.then(()=>this.#m(e)).catch(n=>{this.#v({level:"error",code:"agent.effect_queue",message:`Agent effect queue failed: ${li(n)}`,cause:n})}))}async#m(e){for(let n of e)await this.#y(n)}async#y(e){switch(e.type){case"send":this.#p(e.message);return;case"request_decision":await this.#_(e);return;case"fallback_required":this.#e.onFallbackRequired?.(e),this.#v({level:"warning",code:"agent.fallback_required",message:`Decision failed for match ${e.actionRequest.data.match_id}; fallback required`,cause:e.reason});return;case"record_result":this.#e.onResult?.(e.gameOver,e.game!==void 0?{game:e.game}:{});return;case"notify":this.#v(e);return}}#p(e){let n=this.#b();try{n.send(e)}catch(r){this.#v({level:"error",code:"agent.send_failed",message:`Failed to send ${e.type}: ${li(r)}`,cause:new Sc(`send ${e.type} failed`,r)})}}async#_(e){let n=++this.#g;this.#d={token:n,matchId:e.matchId};let r=this.#S();try{let o=await this.#e.decisionProvider.decide({actionRequest:e.actionRequest,matchId:e.matchId,game:e.game,state:r});if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision for match ${e.matchId}`});return}this.#s({type:"decision.ready",action:o})}catch(o){if(!this.#E(n,e.matchId)){this.#v({level:"warning",code:"agent.stale_decision",message:`Ignoring stale decision failure for match ${e.matchId}`,cause:o});return}this.#s({type:"decision.failed",reason:o})}}#E(e,n){let r=this.#n;return this.#d?.token===e&&this.#d.matchId===n&&r?.phase==="deciding"&&r.pendingAction?.data.match_id===n}#w(){if(!this.#r||this.#n===null||this.#t===null)throw new Zr(`agent '${this.#e.name}' is not started`);if(this.#o||this.#n.phase==="closed")throw new ui(`agent '${this.#e.name}' is stopped`)}#b(){if(this.#t===null)throw new Zr(`agent '${this.#e.name}' is not started`);return this.#t}#S(){if(this.#n===null)throw new Zr(`agent '${this.#e.name}' is not started`);return this.#n}#f(){let e=this.snapshot();for(let n of[...this.#c])n(e)}#$(){let e=this.#a;this.#a=[];for(let n of e)n()}#R(e){this.#v({level:"error",code:"agent.ws_error",message:e.message,cause:e})}#v(e){this.#e.onNotify?.(e)}#k(){return this.#e.now?.()??Date.now()}};function li(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function XE(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function ZE(t,e){let n=t&&typeof t=="object"?{...t}:{};return typeof n.request_id!="string"&&(n.request_id=e),typeof n.ready!="boolean"&&(n.ready=!1),n.runtime_type!=="openclaw"&&n.runtime_type!=="hermes"&&n.runtime_type!=="mock"&&(n.runtime_type="mock"),typeof n.checked_at!="string"&&(n.checked_at=new Date().toISOString()),typeof n.detail=="string"&&(n.detail=Xm(n.detail)),n}function Xm(t){return t.length>240?t.slice(0,240):t}function Zm(t){return{async decide(e){let n=ok(e.game),r=e.actionRequest.data,o=r.legal_actions??[];if(o.length===0)throw new Error("action_request had no legal actions");let i={game:n,matchId:e.matchId,playerId:ik(r.state),legalActions:o,publicState:r.state,timeoutMs:typeof r.timeout_ms=="number"?r.timeout_ms:0},s;try{s=await t.decide(i)}catch{try{s=await t.decide(i)}catch{return fi(n,o,r.state)}}return ek({game:n,raw:s,legalActions:o,publicState:r.state})}}}function ep(){return{name:"mock",async decide(t){return fi(t.game,t.legalActions,t.publicState)},async healthCheck(){return!0}}}function ek(t){if(typeof t.raw!="string")return rk(t.raw,t.legalActions)??fi(t.game,t.legalActions,t.publicState);let e=tk(t.game,t.raw,t.legalActions);return e!==null?e:fi(t.game,t.legalActions,t.publicState)}function tk(t,e,n){let r=nk(e),o=t==="texas_holdem"?Ja(r,n):t==="liars_dice"?Qa(r,n):Xa(r,n);return o.kind==="ok"?o.action:null}function nk(t){let e=t.trim();if(e.startsWith("{"))return e;let n=e.toLowerCase();return JSON.stringify({action:n})}function rk(t,e){let n=e.find(o=>sk(o,t));if(n)return n;let r=e.find(o=>o.type===t.type);return!t.data&&r?r:null}function fi(t,e,n){return t==="texas_holdem"?Ga({publicState:n,legalActions:e,yourPlayerId:"p0"}):t==="liars_dice"?Wa({publicState:n,legalActions:e,yourPlayerId:"p0"}):za({publicState:n,legalActions:e,yourPlayerId:"p0"})}function ok(t){if(t==="texas_holdem"||t==="liars_dice"||t==="coup")return t;throw new Error(`unsupported game: ${String(t)}`)}function ik(t){if(!t||typeof t!="object")return;let e=t.your_player_id;return typeof e=="string"?e:void 0}function sk(t,e){return JSON.stringify(t)===JSON.stringify(e)}var ak="http://127.0.0.1:18789",ck="openclaw/default";function tp(t){let e=(t.baseUrl??ak).replace(/\/+$/,""),n=t.model??ck,r=t.fetchImpl??globalThis.fetch;return{name:"openclaw",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:lk(t,o),body:JSON.stringify({model:n,input:uk(o)})});if(!i.ok)throw new Error(`OpenClaw request failed with HTTP ${i.status}`);let s=await i.text(),a=dk(s);return fk(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function lk(t,e){return{"Content-Type":"application/json","x-openclaw-session-key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`,...t.token?{Authorization:`Bearer ${t.token}`}:{}}}function uk(t){return["You are an AIFight game-playing agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
|
|
211
|
+
`)}function dk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function fk(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("OpenClaw response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;let n=e.output,r=mk(n);if(r)return r;let o=e.choices,i=pk(o);if(i)return i;throw new Error("OpenClaw response did not contain text")}function mk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
|
|
212
|
+
`):null}function pk(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var hk="http://127.0.0.1:8642",gk="hermes-agent";function np(t){let e=(t.baseUrl??hk).replace(/\/+$/,""),n=t.model??gk,r=t.fetchImpl??globalThis.fetch;return{name:"hermes",async decide(o){let i=await r(`${e}/v1/responses`,{method:"POST",headers:yk(t,o),body:JSON.stringify({model:n,input:_k(o)})});if(!i.ok)throw new Error(`Hermes request failed with HTTP ${i.status}`);let s=await i.text(),a=wk(s);return vk(a)},async healthCheck(){try{return(await r(`${e}/v1/responses`,{method:"POST",headers:{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify({model:n,input:'health check: answer with {"action":"pass"}'})})).ok}catch{return!1}}}}function yk(t,e){return{"Content-Type":"application/json",...t.token?{Authorization:`Bearer ${t.token}`,"X-Hermes-Session-Key":`aifight:${t.agentId}:${e.matchId}:${e.playerId??"unknown"}`}:{}}}function _k(t){return["You are an AIFight game-playing Hermes Agent runtime.","Choose exactly one legal action. Return only JSON in this shape:",'{"action":"<type>","data":{},"summary":"short reason"}',"",JSON.stringify({game:t.game,match_id:t.matchId,player_id:t.playerId??null,state:t.publicState,legal_actions:t.legalActions,timeout_ms:t.timeoutMs})].join(`
|
|
213
|
+
`)}function wk(t){if(t.trim()==="")return"";try{return JSON.parse(t)}catch{return t}}function vk(t){if(typeof t=="string")return t;if(!t||typeof t!="object")throw new Error("Hermes response was not an object");let e=t;if(typeof e.output_text=="string")return e.output_text;if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;let n=e.output,r=bk(n);if(r)return r;let o=e.choices,i=Sk(o);if(i)return i;throw new Error("Hermes response did not contain text")}function bk(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=n.content;if(typeof r=="string"){e.push(r);continue}if(Array.isArray(r))for(let o of r){if(!o||typeof o!="object")continue;let i=o.text;typeof i=="string"&&e.push(i)}}return e.length>0?e.join(`
|
|
214
|
+
`):null}function Sk(t){if(!Array.isArray(t)||t.length===0)return null;let e=t[0];if(typeof e.text=="string")return e.text;let n=e.message;if(n&&typeof n=="object"){let r=n.content;if(typeof r=="string")return r}return null}var mi=class{#e;#t=null;#n=null;constructor(e){this.#e=e}async start(){if(this.#t!==null)return this.#t.snapshot();let e=this.#e.runtimeProvider??Tk(this.#e.config),n={url:this.#e.config.wsUrl,apiKey:this.#e.config.apiKey,expectedProtocolVersion:Xf},r=new di({name:this.#e.config.agentName,ws:n,autoConfirmMatches:!0,decisionProvider:Zm(e),...this.#e.connect!==void 0?{connect:this.#e.connect}:{},onReadinessCheck:async i=>this.#c(e,i),onNotify:i=>{this.#r(i.level,i.code,i.message)},onResult:(i,s)=>{this.#r("info","bridge.match_complete",kk(this.#e.config,i,s.game)),this.#a()},onFallbackRequired:i=>{this.#r("warning","bridge.fallback_required",`No action sent for match ${i.actionRequest.data.match_id}; runtime decision failed`)}});this.#t=r;let o=await r.start();if(this.#r("info","bridge.connected",`Connected ${this.#e.config.agentName}`),this.#e.autoJoinGame){let i=this.#e.autoJoinOneShot===!0;r.joinQueue(this.#e.autoJoinGame,this.#e.autoJoinMode,{oneShot:i}),this.#r("info","bridge.queue_joined",i?`Joined ${this.#e.autoJoinGame} for one manual match`:`Joined ${this.#e.autoJoinGame} for daily automatic matching`)}return o}async stop(){this.#t!==null&&(await this.#t.stop("bridge stop"),this.#t=null,this.#n=null)}snapshot(){return this.#t?.snapshot()??null}joinQueue(e,n,r={}){if(r.oneShot===!0||(r.count??1)>1){this.requestManualMatches(e,n,r.count??1);return}this.#o().joinQueue(e,n),this.#r("info","bridge.queue_joined",`Joined ${e} for ${n??"default"} matching`)}leaveQueue(){let e=this.#o();this.#n=null,e.leaveQueue()}requestManualMatches(e,n="ranked",r=1){if(!Number.isInteger(r)||r<1||r>20)throw new Error("manual match count must be an integer between 1 and 20");let o=this.#o(),i=o.snapshot().state?.phase;if(i==="confirming"||i==="matching"||i==="in_match"||i==="deciding"||i==="reporting")throw new Error("agent is already in or entering a match; try again after the current match completes");this.#n=r>1?{game:e,mode:n,remainingAfterCurrent:r-1}:null,o.joinQueue(e,n,{oneShot:!0}),this.#r("info","bridge.queue_joined",r===1?`Joined ${e} for one manual match`:`Joined ${e} for ${r} manual matches`)}#r(e,n,r){this.#e.onLog?.({level:e,code:n,message:r})}#o(){if(this.#t===null)throw new Error("bridge runner is not started");return this.#t}#a(){let e=this.#n,n=this.#t;if(!(e===null||n===null)){if(e.remainingAfterCurrent<=0){this.#n=null;return}try{n.joinQueue(e.game,e.mode,{oneShot:!0}),e.remainingAfterCurrent-=1,this.#r("info","bridge.queue_joined",e.remainingAfterCurrent===0?`Joined ${e.game} for the final manual match in this request`:`Joined ${e.game} for the next manual match; ${e.remainingAfterCurrent} remaining after this one`)}catch(r){this.#n=null,this.#r("error","bridge.manual_requeue_failed",`Could not request the next manual match: ${r instanceof Error?r.message:String(r)}`)}}}async#c(e,n){let r=Ek(n),o=new Date().toISOString();if(!e.healthCheck)return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:"runtime provider does not expose a health check"};try{let i=await e.healthCheck();return{request_id:r,ready:i,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:i?"ready":"local runtime health check returned false"}}catch(i){return{request_id:r,ready:!1,runtime_type:this.#e.config.runtimeType,runtime_name:e.name,checked_at:o,detail:`local runtime health check failed: ${i instanceof Error?i.message:String(i)}`}}}};function Ek(t){if(!t||typeof t!="object")return"";let e=t.request_id;return typeof e=="string"?e:""}function kk(t,e,n){let r=[`Match complete: ${Ak(n)}`,`Result: ${$k(t.agentId,e)}`],o=Pk(t.baseUrl,e.data.replay_url);return o!==void 0?r.push(`Replay: ${o}`):e.data.forfeit_reason!==void 0&&r.push(`Forfeit reason: ${e.data.forfeit_reason}`),(t.autoDailyLimit??0)===2&&r.push("","Your Agent is set to 2 automatic ranked matches per day.","To compete more often:"," aifight set daily 4"),r.join(`
|
|
215
|
+
`)}function $k(t,e){let n=e.data.players.find(i=>i.agent_id===t);if(n===void 0)return"completed";if(e.data.forfeited_by===n.player_id)return"forfeit";if(e.data.forfeit_reason!==void 0)return"opponent forfeit";if(e.data.result.is_draw)return"draw";let r=e.data.result.payoffs[n.player_id];if(typeof r!="number")return e.data.result.winner===n.player_id?"1st place":"completed";let o=Object.values(e.data.result.payoffs).filter(i=>i>r).length;return`${Rk(o+1)} place`}function Rk(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function Pk(t,e){if(!(e===void 0||e.trim()===""))try{return new URL(e,`${t.replace(/\/+$/,"")}/`).toString()}catch{return e}}function Ak(t){switch(t){case"texas_holdem":return"Texas Hold'em";case"liars_dice":return"Liar's Dice";case"coup":return"Coup";default:return"AIFight match"}}function Tk(t){return t.runtimeType==="mock"?ep():t.runtimeType==="openclaw"?tp({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel}):np({agentId:t.agentId,baseUrl:t.runtimeLocalUrl,token:t.runtimeLocalToken,model:t.runtimeModel})}import{execFile as xk}from"node:child_process";import{promisify as Ck}from"node:util";var Ik="@aifight/aifight@alpha",Ok=10*60*1e3,Nk=6*60*60*1e3,Lk=Ck(xk),Mk=async(t,e)=>{let{stdout:n,stderr:r}=await Lk(t,[...e],{timeout:12e4,maxBuffer:524288});return{stdout:typeof n=="string"?n:n.toString("utf8"),stderr:typeof r=="string"?r:r.toString("utf8")}};function op(t){let e=!1,n=!1,r=null,o=t.intervalMs??Nk,i=t.initialDelayMs??Ok,s=c=>{e||(r=setTimeout(()=>{a()},c))},a=async()=>{if(e||n)return null;n=!0;try{return await jk(t)}finally{n=!1,s(o)}};return s(i),{stop:()=>{e=!0,r!==null&&(clearTimeout(r),r=null)},triggerNow:async()=>(r!==null&&(clearTimeout(r),r=null),a())}}async function jk(t){let e=await je({baseUrl:t.baseUrl,currentVersion:se,fetchImpl:t.fetchImpl});if(e.status==="current"||e.status==="unknown")return{status:e.status,update:e};let r=t.snapshot()?.state?.phase??null;if(!Dk(r))return t.onLog?.({level:"info",code:"bridge.auto_update_busy",message:`Bridge update available, but agent is busy (${r??"not connected"}); will retry later.`}),{status:"busy",phase:r,update:e};t.onLog?.({level:"info",code:"bridge.auto_update_start",message:`Updating AIFight Bridge to ${e.policy?.recommendedVersion??"recommended version"} while idle.`});try{await Ec({execFile:t.execFile})}catch(o){let i=rp(o);return t.onLog?.({level:"warning",code:"bridge.auto_update_failed",message:`Automatic AIFight Bridge update failed: ${i}`}),{status:"failed",update:e,error:i}}t.onLog?.({level:"info",code:"bridge.auto_update_done",message:"AIFight Bridge package updated; restarting service process to use the new version."});try{t.onRestartRequired?.()}catch(o){t.onLog?.({level:"warning",code:"bridge.auto_update_restart_signal_failed",message:`AIFight Bridge package updated, but restart signal failed: ${rp(o)}`})}return{status:"updated",update:e}}async function Ec(t={}){await(t.execFile??Mk)("npm",["install","-g",Ik])}function Dk(t){return t==="connected"||t==="queuing"}function rp(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
|
|
216
|
+
`)[0]:t instanceof Error?t.message:String(t)}var Fk=["usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," If aifight.service is already running, this command refuses unless --force is set."].join(`
|
|
217
|
+
`);async function sp(t,e){W(t,0,0,Fk);let n=t.flags.force===!0;if(!n&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&await Wk(e))throw new U("bridge_already_running","aifight.service is already running.",{hint:"Use `aifight start` to request matches through the running service. Use `aifight run --force` only for advanced debugging."});if(n&&process.stdin.isTTY&&process.env.AIFIGHT_SERVICE_RUN!=="1"&&(e.stdout(["AIFight service may already be running.","Starting a second foreground Bridge can duplicate match handling.",""].join(`
|
|
218
|
+
`)),!await Kk(e,"Continue anyway? [y/N] ")))return 0;let r=ne();return Bk({config:r,env:e})}async function Bk(t){let{config:e,env:n}=t,r=await je({baseUrl:e.baseUrl,currentVersion:se,fetchImpl:n.fetchImpl});if(r.status==="unsupported")return n.stderr(`${r.message}
|
|
219
|
+
`),n.stderr(`Run: aifight update --yes
|
|
220
|
+
`),n.stderr(`Manual npm command: ${r.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
|
|
218
221
|
`),1;r.status==="update_recommended"&&(n.stdout(`[warn] bridge.update: ${r.message}
|
|
219
|
-
`),n.stdout(`[warn] update
|
|
220
|
-
`)),
|
|
221
|
-
`),
|
|
222
|
-
`)
|
|
222
|
+
`),n.stdout(`[warn] update when ready: aifight update --yes
|
|
223
|
+
`)),at(),Fm();let o=null,i=null,s=null,a=new mi({config:e,...Uk(e),onLog:c=>{ip(c,n)}});try{o=Bm(),Dm(process.pid);let c=Lm();n.stdout(Hk(e)),await a.start(),i=Ym({tokenSource:()=>c,router:qk(e,a),onLog:u=>{n.onLog?.({code:`control.${u.code}`,message:u.message})}});let l=await i.listen();return Mm(c),jm(l),process.env.AIFIGHT_SERVICE_RUN==="1"&&(s=op({baseUrl:e.baseUrl,fetchImpl:n.fetchImpl,snapshot:()=>a.snapshot(),execFile:n.bridgeService?.execFile,onLog:u=>ip(u,n),onRestartRequired:()=>{n.stdout(`AIFight Bridge updated; stopping so aifight.service can restart with the new package.
|
|
224
|
+
`),process.kill(process.pid,"SIGTERM")}})),n.stdout(`Bridge online. Press Ctrl-C to stop.
|
|
225
|
+
`),await zk(async()=>{s?.stop(),s=null,await i?.close(),i=null,await a.stop(),yc({onLog:u=>n.stderr(`warning: ${u}
|
|
226
|
+
`)}),o?.release(),o=null}),0}catch(c){throw s?.stop(),await i?.close().catch(()=>{}),await a.stop().catch(()=>{}),yc({onLog:()=>{}}),o?.release(),c instanceof _e?c.kind==="lock_held_by_other"?new U("bridge_already_running",`AIFight Bridge is already running${c.heldByPid!==void 0?` (PID ${c.heldByPid})`:""}.`,{hint:"Use `aifight start` to request matches through the running Bridge."}):new U("bridge_runtime_files_failed",c.message):c}}function Uk(t){let e=(t.autoDailyLimit??0)>0?Vk(t.autoGames):void 0;return e===void 0?{}:{autoJoinGame:e,autoJoinMode:"ranked",autoJoinOneShot:!1}}function qk(t,e){return{listAgents:()=>{let n=e.snapshot();return n===null?[]:[n]},getAgent:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});let r=e.snapshot();if(r===null)throw Object.assign(new Error("bridge runner is not started"),{kind:"router_agent_not_found"});return{snapshot:()=>e.snapshot()??r}},joinQueue:(n,r,o,i)=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});if(!ct(r))throw new Error(`unsupported game '${r}'`);e.joinQueue(r,o,{...i?.oneShot!==void 0?{oneShot:i.oneShot}:{},...i?.count!==void 0?{count:i.count}:{}})},leaveQueue:n=>{if(n.name!==t.agentName&&n.name!=="default")throw Object.assign(new Error(`agent '${n.name}' not found`),{kind:"router_agent_not_found"});e.leaveQueue()}}}function Hk(t){let e=(t.autoDailyLimit??0)>0?`Automatic ranked matches: ${t.autoDailyLimit} per day`:"Automatic ranked matches: disabled; staying online for challenges and manual starts";return`${["Starting AIFight Bridge.","",`Agent: ${t.agentName}`,`Runtime: ${Gk(t.runtimeType)} at ${t.runtimeLocalUrl}`,`AIFight: ${t.baseUrl}`,e,"","Safety boundary: this opens an outbound WebSocket to AIFight and calls your local Agent runtime on localhost.","Your model/provider keys stay inside your local runtime.",""].join(`
|
|
223
227
|
`)}
|
|
224
|
-
`}function
|
|
228
|
+
`}function ip(t,e){if(t.code==="fsm.game_state"||t.code==="server.event"||t.code==="bridge.connected")return;if(t.code==="bridge.queue_joined"){e.stdout(`${t.message}
|
|
225
229
|
`);return}if(t.code==="bridge.match_complete"){e.stdout(`
|
|
226
230
|
${t.message}
|
|
227
231
|
`);return}let r=`${t.level==="error"?"error":t.level==="warning"?"warning":"info"}: ${t.message}
|
|
228
|
-
`;t.level==="error"?e.stderr(r):e.stdout(r)}function
|
|
232
|
+
`;t.level==="error"?e.stderr(r):e.stdout(r)}function Gk(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function Vk(t){let e=(t??he).filter(ct),n=e.length>0?e:he;return n[Math.floor(Math.random()*n.length)]}async function Wk(t){try{let e=await St(t.bridgeService);return e.installed&&e.running===!0}catch(e){return e instanceof Q,!1}}async function zk(t){await new Promise(e=>{let n=!1,r=async()=>{n||(n=!0,process.off("SIGINT",r),process.off("SIGTERM",r),await t(),e())};process.on("SIGINT",r),process.on("SIGTERM",r)})}async function Kk(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var Jk="usage: aifight status",Yk=1500;async function ap(t,e){W(t,0,0,Jk);let n=n$();if(n===void 0)return t.jsonMode?e.stdout(JSON.stringify({status:"not_configured",bridgeVersion:se})+`
|
|
229
233
|
`):(e.stdout(`AIFight status
|
|
230
234
|
|
|
231
235
|
`),e.stdout(`Bridge: not configured
|
|
232
|
-
`),e.stdout(`CLI version: ${
|
|
233
|
-
`),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=
|
|
236
|
+
`),e.stdout(`CLI version: ${se}
|
|
237
|
+
`),e.stdout("Next: run `aifight register` for a new agent, or `aifight connect <PAIRING_CODE>` for an existing agent.\n")),0;let r=Dt(n),o=await je({baseUrl:n.baseUrl,currentVersion:se,fetchImpl:e.fetchImpl}),i=await Qk(n,e.fetchImpl);return t.jsonMode?(e.stdout(JSON.stringify({status:"configured",bridgeVersion:se,update:o,platformAgentStatus:i,config:r})+`
|
|
234
238
|
`),0):(e.stdout(`AIFight status
|
|
235
239
|
|
|
236
240
|
`),e.stdout(`Agent: ${r.agentName}
|
|
237
|
-
`),e.stdout(`Profile: ${
|
|
241
|
+
`),e.stdout(`Profile: ${Zk(i,n)}
|
|
238
242
|
`),i.kind==="unavailable"&&e.stdout(`Profile check: ${i.message}
|
|
239
243
|
`),e.stdout(`Bridge: configured
|
|
240
|
-
`),e.stdout(`CLI version: ${
|
|
244
|
+
`),e.stdout(`CLI version: ${se}
|
|
241
245
|
`),e.stdout(`Update: ${o.message}
|
|
242
|
-
`),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command:
|
|
243
|
-
`),e.stdout(
|
|
244
|
-
`),e.stdout(`
|
|
246
|
+
`),(o.status==="update_recommended"||o.status==="unsupported")&&(e.stdout(`Update command: aifight update --yes
|
|
247
|
+
`),e.stdout(`Manual npm command: ${o.policy?.updateCommand??"npm install -g @aifight/aifight@alpha"}
|
|
248
|
+
`),e.stdout("The update command keeps local credentials and restarts `aifight.service` when it is installed.\n")),e.stdout(`Runtime: ${t$(r.runtimeType)} at ${r.runtimeLocalUrl}
|
|
249
|
+
`),e.stdout(`Automatic ranked matches: ${e$(r.autoDailyLimit)}
|
|
245
250
|
`),e.stdout(`Games: ${r.autoGames?.join(", ")??"texas_holdem, liars_dice, coup"}
|
|
246
251
|
`),e.stdout(`AIFight WebSocket: ${r.wsUrl}
|
|
247
252
|
`),e.stdout(`No secrets are shown here.
|
|
248
|
-
`),0)}async function
|
|
249
|
-
`);async function
|
|
253
|
+
`),0)}async function Qk(t,e=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Yk);try{let o=await e(`${t.baseUrl.replace(/\/+$/,"")}/api/agents/me/status`,{method:"GET",headers:{"X-API-Key":t.apiKey},signal:n.signal});if(!o.ok)return{kind:"unavailable",message:`server returned HTTP ${o.status}`};let i=await o.json().catch(()=>{}),s=Xk(i);return s===null?{kind:"unavailable",message:"server returned an unexpected status response"}:s}catch(o){return{kind:"unavailable",message:o?.name==="AbortError"?"server check timed out":"server check unavailable"}}finally{clearTimeout(r)}}function Xk(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.agent_id!="string"||typeof e.is_claimed!="boolean"||e.identity_status!=="bootstrap"&&e.identity_status!=="official"||e.status!=="ready"&&e.status!=="needs_official_name"&&e.status!=="pending_claim"?null:{kind:"ok",agentId:e.agent_id,isClaimed:e.is_claimed,identityStatus:e.identity_status,status:e.status}}function Zk(t,e){if(t.kind==="unavailable")return e.claimToken!==void 0?"unknown (claim URL saved locally)":"unknown";switch(t.status){case"ready":return"claimed, ready";case"needs_official_name":return"claimed, official name pending";case"pending_claim":return"unclaimed"}}function e$(t){return t===void 0?"not set":t===0?"disabled":`${t} per day`}function t$(t){switch(t){case"openclaw":return"OpenClaw";case"hermes":return"Hermes";case"mock":return"mock"}}function n$(){try{return ne()}catch(t){if((t instanceof Error?t.message:String(t)).includes("bridge is not configured"))return;throw t}}var r$=["usage: aifight update [--yes]"," Update the AIFight CLI package from npm, then restart aifight.service if it is installed."," Use --yes only after the human has approved the local AIFight package update."].join(`
|
|
254
|
+
`),o$="https://aifight.ai",pi="@aifight/aifight@alpha";async function cp(t,e){W(t,0,0,r$);let n=t.flags.yes===!0,r=await je({baseUrl:i$(),currentVersion:se,fetchImpl:e.fetchImpl});if(r.status==="current")return t.jsonMode?e.stdout(JSON.stringify({status:"current",update:r})+`
|
|
255
|
+
`):(e.stdout(`${r.message}
|
|
256
|
+
`),e.stdout(`No npm update is required.
|
|
257
|
+
`)),0;if(!n&&t.jsonMode)throw new U("update_confirmation_required","AIFight CLI update requires explicit confirmation.",{hint:"Run `aifight update --yes` after the human approves the npm package update."});if(t.jsonMode||(e.stdout(`${r.message}
|
|
258
|
+
`),r.policy!==void 0&&(e.stdout(`Latest: ${r.policy.latestVersion}
|
|
259
|
+
`),e.stdout(`Update package: ${pi}
|
|
260
|
+
`))),!n){if(!process.stdin.isTTY)return e.stderr(`aifight: update requires confirmation in non-interactive mode.
|
|
261
|
+
`),e.stderr("Run `aifight update --yes` after the human approves the local package update.\n"),1;if(!await c$(e,"Run npm update now? [y/N] "))return e.stdout(`Update skipped.
|
|
262
|
+
`),0}await s$(e,t.jsonMode);let o=await a$(e,t.jsonMode);return t.jsonMode&&e.stdout(JSON.stringify({status:"updated",package:pi,service:o})+`
|
|
263
|
+
`),0}function i$(){try{return ne().baseUrl}catch{return process.env.AIFIGHT_BASE_URL?.replace(/\/+$/,"")??o$}}async function s$(t,e){e||t.stdout(`Updating AIFight CLI: npm install -g ${pi}
|
|
264
|
+
`);try{await Ec({execFile:t.bridgeService?.execFile})}catch(n){throw new U("update_failed",`npm update failed: ${kc(n)}`,{hint:`Run manually: npm install -g ${pi}`})}e||t.stdout(`AIFight CLI package updated.
|
|
265
|
+
`)}async function a$(t,e){let n;try{n=await St(t.bridgeService)}catch(r){return e||(t.stderr(`warning: could not inspect aifight.service: ${kc(r)}
|
|
266
|
+
`),t.stderr("If you use a foreground Bridge, stop it and run `aifight run` again.\n")),{installed:!1}}if(!n.installed)return e||t.stdout("aifight.service is not installed. If you use a foreground Bridge, stop it and run `aifight run` again.\n"),{installed:!1};if(n.running!==!0)return e||t.stdout("aifight.service is installed but not running. Start it with `aifight service start` when ready.\n"),{installed:!0,restarted:!1,running:n.running,detail:n.detail};e||t.stdout(`Restarting aifight.service so it uses the updated CLI.
|
|
267
|
+
`);try{await zr(t.bridgeService)}catch(r){let o=r instanceof Q?r.hint:void 0;return e||(t.stderr(`warning: aifight.service restart failed: ${kc(r)}
|
|
268
|
+
`),o&&t.stderr(`${o}
|
|
269
|
+
`),t.stderr("Run `aifight service restart` after resolving the service manager issue.\n")),{installed:!0,restarted:!1,running:n.running,detail:n.detail}}return e||t.stdout(`aifight.service restarted.
|
|
270
|
+
`),{installed:!0,restarted:!0,running:!0,detail:"restarted"}}function kc(t){let e=t?.stderr;return typeof e=="string"&&e.trim()!==""?e.trim().split(`
|
|
271
|
+
`)[0]:t instanceof Error?t.message:String(t)}async function c$(t,e){t.stdout(e),process.stdin.resume(),process.stdin.setEncoding("utf8");let n=await new Promise(o=>{process.stdin.once("data",i=>o(String(i)))});process.stdin.pause();let r=n.trim().toLowerCase();return r==="y"||r==="yes"}var $c=["usage: aifight set daily <N>"," aifight set game <game1,game2>",`supported games: ${he.join(", ")}`].join(`
|
|
272
|
+
`);async function lp(t,e){W(t,2,2,$c);let n=t.positional[0];if(n==="daily")return l$(t.positional[1],t,e);if(n==="game")return d$(t.positional[1],t,e);throw new O(`unknown set target '${n}'`,"available: daily | game")}async function l$(t,e,n){if(!/^\d+$/.test(t))throw new O(`daily must be a non-negative integer (got '${t}')`,$c);let r=Number.parseInt(t,10),o=ne();await u$(o,r,n.fetchImpl??globalThis.fetch);let i={...o,autoDailyLimit:r,updatedAt:new Date().toISOString()};return pn(i),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoDailyLimit:r,platformPolicySynced:!0})+`
|
|
250
273
|
`),0):(r===0?n.stdout(`Daily automatic ranked matches disabled. The Agent will not join scheduled matches unless you change this setting or manually start a match.
|
|
251
274
|
`):n.stdout(`Automatic ranked matches set to ${r} per day.
|
|
252
275
|
`),n.stdout(`AIFight platform policy synced.
|
|
253
|
-
`),0)}async function
|
|
276
|
+
`),0)}async function u$(t,e,n){let r=e===0?{auto_requeue:!1}:{max_games_per_day:e,auto_requeue:!0},o=await n(`${t.baseUrl}/api/agents/me/policy`,{method:"PATCH",headers:{"Content-Type":"application/json","X-API-Key":t.apiKey},body:JSON.stringify(r)});if(!o.ok)throw new U("policy_sync_failed",await f$(o,`daily policy sync failed with HTTP ${o.status}`))}function d$(t,e,n){let r=t.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(r.length===0)throw new O("at least one game is required",$c);let o=new Set,i=[];for(let c of r){if(!ct(c))throw new O(`unsupported game '${c}'`,`supported: ${he.join(", ")}`);o.has(c)||(o.add(c),i.push(c))}let a={...ne(),autoGames:i,updatedAt:new Date().toISOString()};return pn(a),e.jsonMode?(n.stdout(JSON.stringify({status:"ok",autoGames:i})+`
|
|
254
277
|
`),0):(n.stdout(`Automatic match games set to: ${i.join(", ")}
|
|
255
|
-
`),0)}async function
|
|
278
|
+
`),0)}async function f$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var up="usage: aifight challenge <texas_holdem|liars_dice|coup>";async function dp(t,e){W(t,1,1,up);let n=t.positional[0];if(n!=="texas_holdem"&&n!=="liars_dice"&&n!=="coup")throw new O(`challenge game must be texas_holdem, liars_dice, or coup (got '${n}')`,up);let r=ne(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":r.apiKey},body:JSON.stringify({game:n,accept_mode:"single"})});if(!o.ok)throw new U("challenge_create_failed",await m$(o,`challenge creation failed with HTTP ${o.status}`));let i=await o.json();if(typeof i.join_url!="string"||i.join_url.length===0)throw new U("challenge_response_invalid","challenge response did not include a join_url");return t.jsonMode?(e.stdout(JSON.stringify(i)+`
|
|
256
279
|
`),0):(e.stdout(`Friendly challenge created.
|
|
257
280
|
|
|
258
281
|
`),e.stdout(`Game: ${n}
|
|
@@ -264,49 +287,50 @@ ${t.message}
|
|
|
264
287
|
|
|
265
288
|
`),e.stdout(`This does not affect ratings or daily auto-play.
|
|
266
289
|
`),n==="texas_holdem"&&e.stdout(`Texas Hold'em challenges start as a direct two-player friendly table; normal matchmaking still starts at four players.
|
|
267
|
-
`),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function
|
|
290
|
+
`),e.stdout("Keep aifight.service running before the other side accepts. For temporary testing, run `aifight run` in another terminal.\n"),0)}async function m$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}var Rc="usage: aifight accept <challenge_url_or_token>";async function fp(t,e){W(t,1,1,Rc);let n=p$(t.positional[0]),r=ne(),o=await(e.fetchImpl??globalThis.fetch)(`${r.baseUrl}/api/challenges/${encodeURIComponent(n)}/accept`,{method:"POST",headers:{"X-API-Key":r.apiKey}});if(!o.ok){let s=await g$(o,`challenge accept failed with HTTP ${o.status}`);throw new U("challenge_accept_failed",h$(o.status,s))}let i=await o.json();return t.jsonMode?(e.stdout(JSON.stringify(i)+`
|
|
268
291
|
`),0):(e.stdout(`Friendly challenge accepted.
|
|
269
292
|
|
|
270
293
|
`),i.match_id&&e.stdout(`Match: ${i.match_id}
|
|
271
294
|
`),i.message&&e.stdout(`${i.message}
|
|
272
|
-
`),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function
|
|
273
|
-
`);async function
|
|
274
|
-
`)),await
|
|
295
|
+
`),e.stdout("Keep aifight.service running so game_start can reach this Agent. For temporary testing, run `aifight run` in another terminal.\n"),0)}function p$(t){let e=t.trim();if(e==="")throw new O("challenge token is required",Rc);if(/^dl_[0-9a-f]{32}$/i.test(e))return e;try{let r=new URL(e).pathname.split("/").filter(Boolean),o=r.findIndex(i=>i==="challenge"||i==="duel");if(o>=0&&r[o+1]!==void 0){let i=r[o+1];if(/^dl_[0-9a-f]{32}$/i.test(i))return i}}catch{}throw new O("invalid challenge URL or token",Rc)}function h$(t,e){return t===425?`${e}. Start the local service first with \`aifight service start\`, then retry accept.`:t===503?`${e}. Ask the challenge creator to keep aifight.service running.`:e}async function g$(t,e){let n=await t.json().catch(()=>{});if(n&&typeof n=="object"){let r=n.error;if(typeof r=="string"&&r.length>0)return r}return e}import hi from"node:fs";var mp="gateway.http.endpoints.responses.enabled",pp=["API_SERVER_ENABLED","API_SERVER_HOST","API_SERVER_PORT","API_SERVER_KEY","API_SERVER_MODEL_NAME"],hp=["usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
|
|
296
|
+
`);async function gp(t,e){if(W(t,0,0,hp),t.jsonMode||!process.stdin.isTTY)throw new O("aifight uninstall requires an interactive terminal",hp);return e.stdout(["This removes local AIFight bridge setup from this machine.","","It can remove:"," - aifight.service, if installed"," - local bridge credentials/config"," - AIFight-recorded OpenClaw/Hermes setup changes, if you approve","","It will not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys.",""].join(`
|
|
297
|
+
`)),await Kr(e,"Continue with local uninstall? [y/N] ")?(await y$(e),await _$(e),em(),pm(),e.stdout(["AIFight local bridge setup removed.","","To remove the CLI package itself, run:"," npm uninstall -g @aifight/aifight",""].join(`
|
|
275
298
|
`)),0):(e.stdout(`Uninstall cancelled.
|
|
276
|
-
`),0)}async function
|
|
277
|
-
`)}catch(e){let n=e instanceof
|
|
278
|
-
`),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function
|
|
279
|
-
`);return}e.openclaw?.responsesEnabledByAIFight&&await
|
|
280
|
-
`)),!await
|
|
281
|
-
`);return}if(!
|
|
282
|
-
`);return}let n=await
|
|
283
|
-
`);return}let r=await
|
|
284
|
-
`)),!await
|
|
285
|
-
`);return}if(!
|
|
286
|
-
`);return}let o=
|
|
287
|
-
`),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function
|
|
299
|
+
`),0)}async function y$(t){try{let e=await ii(t.bridgeService);t.stdout(`aifight.service removed if it existed (${e.platform}).
|
|
300
|
+
`)}catch(e){let n=e instanceof Q||e instanceof Error?e.message:String(e);t.stderr(`warning: could not uninstall aifight.service automatically: ${n}
|
|
301
|
+
`),t.stderr("If you installed it, run `aifight service uninstall` manually before removing the npm package.\n")}}async function _$(t){let e=cc();if(!e){t.stdout(`No AIFight-recorded runtime setup changes found.
|
|
302
|
+
`);return}e.openclaw?.responsesEnabledByAIFight&&await w$(t),e.hermes&&await v$(t,e.hermes.envPath,e.hermes.previous)}async function w$(t){if(t.stdout(["","AIFight previously enabled OpenClaw /v1/responses on this machine.","If no other local tool depends on that endpoint, I can disable it now.",""].join(`
|
|
303
|
+
`)),!await Kr(t,"Disable OpenClaw /v1/responses now? [y/N] ")){t.stdout(`Skipped OpenClaw change. To disable later: openclaw config set ${mp} false --strict-json
|
|
304
|
+
`);return}if(!Ae("openclaw")){t.stderr(`OpenClaw CLI was not found on PATH. Disable the setting manually if needed.
|
|
305
|
+
`);return}let n=await it("openclaw",["config","set",mp,"false","--strict-json"]);if(gn(t,"openclaw config set",n),n.code!==0){t.stderr(`OpenClaw config restore failed. The bridge config was still removed.
|
|
306
|
+
`);return}let r=await it("openclaw",["config","validate"]);gn(t,"openclaw config validate",r),await Xn(t,"openclaw","OpenClaw /v1/responses was disabled during AIFight uninstall.")}async function v$(t,e,n){if(t.stdout(["",`AIFight previously updated Hermes API Server settings in ${e}.`,"I can restore the API_SERVER_* values that were active before AIFight changed them.",""].join(`
|
|
307
|
+
`)),!await Kr(t,"Restore Hermes API_SERVER_* values now? [y/N] ")){t.stdout(`Skipped Hermes .env restore.
|
|
308
|
+
`);return}if(!hi.existsSync(e)){t.stderr(`Hermes .env was not found at ${e}. Nothing to restore.
|
|
309
|
+
`);return}let o=hi.readFileSync(e,"utf8"),i=b$(o,n);if(hi.writeFileSync(e,i,{mode:384}),process.platform!=="win32")try{hi.chmodSync(e,384)}catch{}t.stdout(`Hermes API_SERVER_* values restored in .env.
|
|
310
|
+
`),await Xn(t,"hermes","Hermes API Server settings were restored during AIFight uninstall.")}function b$(t,e){let n=new Set(pp),r=new Set,o=[];for(let i of t.split(/\r?\n/)){let a=i.match(/^(\s*)(#\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[3];if(!a||!n.has(a)){o.push(i);continue}r.add(a);let c=e[a];c?.wasActive&&o.push(`${a}=${c.value??""}`)}for(let i of pp){if(r.has(i))continue;let s=e[i];s?.wasActive&&o.push(`${i}=${s.value??""}`)}return o.join(`
|
|
288
311
|
`).replace(/\n*$/,`
|
|
289
|
-
`)}async function
|
|
290
|
-
`)}function
|
|
291
|
-
`):t.stdout(
|
|
292
|
-
`),0}function
|
|
312
|
+
`)}async function _p(t,e={}){let n={stdout:e.stdout??(l=>process.stdout.write(l)),stderr:e.stderr??(l=>process.stderr.write(l)),...e.hello!==void 0?{hello:e.hello}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{},...e.baseTimeoutMs!==void 0?{baseTimeoutMs:e.baseTimeoutMs}:{},...e.onLog!==void 0?{onLog:e.onLog}:{},...e.bridgeService!==void 0?{bridgeService:e.bridgeService}:{}},r=S$(t)?t.slice(2):t.slice(),i=xc(r,[{name:"json",type:"boolean"},{name:"help",type:"boolean"},{name:"version",type:"boolean"},{name:"runtime-url",type:"string"},{name:"runtime-token",type:"string"},{name:"runtime-model",type:"string"},{name:"runtime",type:"string"},{name:"name",type:"string"},{name:"approved-local-setup",type:"boolean"},{name:"force",type:"boolean"},{name:"aifight-path",type:"string"},{name:"yes",type:"boolean"}]),s=i.flags.json===!0;if(i.errors.length>0)return wp(i.errors[0],n,s);if(i.flags.version===!0)return Za({positional:[],flags:i.flags,jsonMode:s},n);if(i.flags.help===!0)return i.positional.length===0?Pc(n,s):$$(i.positional,n,s);if(i.positional.length===0)return Pc(n,s);let a=i.positional[0],c={positional:i.positional.slice(1),flags:i.flags,jsonMode:s};try{return await E$(a,c,n)}catch(l){return R$(l,n,s)}}function S$(t){if(t.length<2)return!1;let e=t[0]??"",n=t[1]??"";return/(^|[\\/])node(?:\.exe)?$/.test(e)?!0:/(^|[\\/])(aifight|aifight-bridge|bin\.mjs|aifight\.ts)$/.test(n)}async function E$(t,e,n){switch(t){case"version":return Za(e,n);case"doctor":return rm(e,n);case"register":return Em(e,n);case"connect":return Am(e,n);case"start":return Cm(e,n);case"run":return sp(e,n);case"status":return ap(e,n);case"update":return cp(e,n);case"service":return um(e,n);case"uninstall":return gp(e,n);case"set":return lp(e,n);case"challenge":return dp(e,n);case"accept":return fp(e,n);default:throw new O(`unknown command '${t}'`)}}function yp(){return["aifight \u2014 AIFight CLI","","Commands:"," aifight register Create a private bootstrap identity and save credentials"," aifight connect <PAIRING_CODE> Authorize this machine for an existing claimed agent"," aifight start [game] [N] Request manual ranked match(es)"," aifight status Show local bridge config with secrets redacted"," aifight update Update the CLI package and restart service if installed"," aifight service <command> Install or manage aifight.service"," aifight uninstall Remove local AIFight setup from this machine"," aifight doctor Troubleshoot local bridge and runtime issues"," aifight set daily <N> Set daily automatic match preference"," aifight set game <game1,game2> Set automatic match game preference"," aifight challenge <game> Create a one-use friendly challenge URL"," aifight accept <url_or_token> Accept a received challenge URL"," aifight version Print version","","Global flags:"," --json Emit machine-readable JSON instead of human text"," --version, -v Print version"," --help, -h Print this help (or per-command help when after a command)"," --runtime-url <url> Bridge register/connect only: local Agent runtime URL"," --runtime-token <token> Bridge register/connect only: local Agent runtime token"," --runtime-model <model> Bridge register/connect only: local Agent runtime model"," --runtime <type> Bridge register only: openclaw or hermes"," --name <suggested_name> Bridge register only: suggested future public name"," --approved-local-setup Bridge register only: skip repeated local prompts after user-approved Agent setup"," --yes Update only: run npm update without an interactive confirmation","",`Supported games for manual matches: ${he.join(", ")}`,"Challenge games in this release: texas_holdem, liars_dice, coup"].join(`
|
|
313
|
+
`)}function Pc(t,e){return e?t.stdout(JSON.stringify({help:yp()})+`
|
|
314
|
+
`):t.stdout(yp()+`
|
|
315
|
+
`),0}function k$(t){switch(t[0]){case"version":return`Usage: aifight version
|
|
293
316
|
Print the AIFight CLI version.`;case"doctor":return["Usage: aifight doctor"," Diagnose local bridge config, package version policy, and runtime endpoint reachability."].join(`
|
|
294
|
-
`);case"register":return["Usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Check the local Agent runtime, then create a private bootstrap AIFight identity and save local match credentials."," In human interactive mode, register asks which local runtime to use when none is specified."," In human mode, register asks before changing OpenClaw/Hermes local runtime settings."," --approved-local-setup is for Agent-assisted setup after the human has approved the local runtime/service scope."," With --approved-local-setup, register auto-detects OpenClaw/Hermes when possible and does not ask again."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Normal use requires a long-running local Bridge; register
|
|
317
|
+
`);case"register":return["Usage: aifight register [openclaw|hermes] [--name <suggested_name>] [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>] [--approved-local-setup]"," Check the local Agent runtime, then create a private bootstrap AIFight identity and save local match credentials."," In human interactive mode, register asks which local runtime to use when none is specified."," In human mode, register asks before changing OpenClaw/Hermes local runtime settings."," --approved-local-setup is for Agent-assisted setup after the human has approved the local runtime/service scope."," With --approved-local-setup, register auto-detects OpenClaw/Hermes when possible and does not ask again."," --runtime-url must point to localhost, 127.0.0.1, or [::1]."," Normal use requires a long-running local Bridge; register installs or reloads aifight.service when approved."," If local runtime auth is enabled, register stores the runtime token only in local bridge credentials."," Claim the agent and confirm its official Dashboard name before it can play matches or friendly challenges."," Claiming also enables dashboard management, profile settings, and recovery."," If service install is declined or unavailable, the agent is registered but not online yet."," Finish setup later with `aifight service install`, or self-manage `aifight run` as an advanced path."," Use --json for scripting; JSON mode registers and exits without service setup or foreground run prompts."," JSON/non-interactive mode defaults to openclaw when no runtime is specified."].join(`
|
|
295
318
|
`);case"connect":return["Usage: aifight connect <PAIRING_CODE> [--runtime-url <url>] [--runtime-token <token>] [--runtime-model <model>]"," Exchange a one-time dashboard pairing code and save local bridge config."," The AIFight agent key is stored locally; runtime LLM keys are not uploaded."," Runtime token/model/url are local-only overrides; --runtime-url must point to localhost, 127.0.0.1, or [::1]."].join(`
|
|
296
|
-
`);case"start":return["Usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running Bridge."," Manual starts do not consume the daily automatic match limit."," If no game is given, AIFight uses your configured game preference or picks a supported game."," N must be between 1 and 20.",` supported games: ${
|
|
319
|
+
`);case"start":return["Usage: aifight start [game] [N]"," aifight start [N]"," Request manual ranked match(es) through the running Bridge."," Manual starts do not consume the daily automatic match limit."," If no game is given, AIFight uses your configured game preference or picks a supported game."," N must be between 1 and 20.",` supported games: ${he.join(", ")}`].join(`
|
|
297
320
|
`);case"run":return["Usage: aifight run [--force]"," Advanced: run the outbound Bridge in this terminal."," Normal installs should use aifight.service; use `aifight start` to request matches."," If aifight.service is already running, run refuses unless --force is set."].join(`
|
|
298
321
|
`);case"status":return["Usage: aifight status"," Show local bridge config with API key and runtime token redacted."].join(`
|
|
322
|
+
`);case"update":return["Usage: aifight update [--yes]"," Update the AIFight CLI package from npm, then restart aifight.service if it is installed."," Use --yes only after the human has approved the local AIFight package update."," Updating does not require register, claim, or a new pairing code."].join(`
|
|
299
323
|
`);case"service":return["Usage: aifight service <install|status|start|stop|restart|uninstall>"," aifight service install [--aifight-path <path>]"," Manage the local background service named aifight.service."," The service runs `aifight run` so this Agent comes back online after reboot."," --aifight-path is an advanced install-only override for the CLI binary path."].join(`
|
|
300
324
|
`);case"uninstall":return["Usage: aifight uninstall"," Remove local AIFight bridge setup from this machine."," This removes local credentials/config and aifight.service if installed."," It can also restore AIFight-recorded OpenClaw/Hermes setup changes with your approval."," It does not delete your AIFight Agent, ratings, match history, OpenClaw, Hermes, or provider keys."," To remove the CLI package itself, run `npm uninstall -g @aifight/aifight` after local cleanup."].join(`
|
|
301
|
-
`);case"set":return["Usage: aifight set daily <N>"," aifight set game <game1,game2>"," daily 0 means the agent no longer joins daily automatic matches."," Manual matches and challenges are explicit user actions and are not daily automatic matches.",` supported games: ${
|
|
325
|
+
`);case"set":return["Usage: aifight set daily <N>"," aifight set game <game1,game2>"," daily 0 means the agent no longer joins daily automatic matches."," Manual matches and challenges are explicit user actions and are not daily automatic matches.",` supported games: ${he.join(", ")}`].join(`
|
|
302
326
|
`);case"challenge":return["Usage: aifight challenge <texas_holdem|liars_dice|coup>"," Create a one-use friendly challenge URL to forward to another human or Agent."," Texas Hold'em challenges start as a direct two-player friendly table."," Challenges do not affect ratings or daily automatic match preferences."].join(`
|
|
303
327
|
`);case"accept":return["Usage: aifight accept <challenge_url_or_token>"," Accept a challenge URL that someone sent to this human or Agent."," The local bridge must be online so game_start can be delivered."].join(`
|
|
304
|
-
`);default:return}}function
|
|
328
|
+
`);default:return}}function $$(t,e,n){let r=k$(t);return r===void 0?Pc(e,n):(n?e.stdout(JSON.stringify({help:r})+`
|
|
305
329
|
`):e.stdout(r+`
|
|
306
|
-
`),0)}function
|
|
330
|
+
`),0)}function wp(t,e,n,r){return n?e.stderr(no("client_usage_error",t,r!==void 0?{hint:r}:void 0)):(e.stderr(`aifight: ${t}
|
|
307
331
|
`),r!==void 0&&e.stderr(`${r}
|
|
308
|
-
`)),2}function
|
|
332
|
+
`)),2}function R$(t,e,n){if(t instanceof O)return wp(t.message,e,n,t.hint);if(t instanceof U)return n?e.stderr(no(t.code,t.message,t.hint!==void 0?{hint:t.hint}:void 0)):(e.stderr(`aifight: ${t.message}
|
|
309
333
|
`),t.hint!==void 0&&e.stderr(`${t.hint}
|
|
310
|
-
`)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(
|
|
311
|
-
`),99}
|
|
334
|
+
`)),t.exitCode;let r=t instanceof Error?t.message:String(t);return n?e.stderr(no("client_unexpected_error",r)):e.stderr(`aifight: unexpected error: ${r}
|
|
335
|
+
`),99}_p(process.argv).then(t=>process.exit(t),t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`aifight: unexpected fatal: ${e}
|
|
312
336
|
`),process.exit(99)});
|