@toloka-platform/sdk 0.1.0-preview.3 → 0.1.0-preview.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,104 +1,104 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun @bytecode @bun-cjs
3
- (function(exports, require, module, __filename, __dirname) {var Qy=Object.create;var{getPrototypeOf:Yy,defineProperty:ks,getOwnPropertyNames:Xy}=Object;var Zy=Object.prototype.hasOwnProperty;function e_(e){return this[e]}var t_,r_,xe=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?t_??=new WeakMap:r_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?Qy(Yy(e)):{};let o=t||!e||!e.__esModule?ks(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Xy(e))if(!Zy.call(o,a))ks(o,a,{get:e_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var i_=(e)=>e;function n_(e,t){this[e]=i_.bind(null,t)}var s_=(e,t)=>{for(var r in t)ks(e,r,{get:t[r],enumerable:!0,configurable:!0,set:n_.bind(t,r)})};var Kr=b(function(M){Object.defineProperty(M,"__esModule",{value:!0});M.regexpCode=M.getEsmExportName=M.getProperty=M.safeStringify=M.stringify=M.strConcat=M.addCodeArg=M.str=M._=M.nil=M._Code=M.Name=M.IDENTIFIER=M._CodeOrName=void 0;class en{}M._CodeOrName=en;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class tr extends en{constructor(e){super();if(!M.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}M.Name=tr;class De extends en{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((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof tr)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=De;M.nil=new De("");function _d(e,...t){let r=[e[0]],i=0;while(i<t.length)Zs(r,t[i]),r.push(e[++i]);return new De(r)}M._=_d;var Xs=new De("+");function Pd(e,...t){let r=[Vr(e[0])],i=0;while(i<t.length)r.push(Xs),Zs(r,t[i]),r.push(Xs,Vr(e[++i]));return hv(r),new De(r)}M.str=Pd;function Zs(e,t){if(t instanceof De)e.push(...t._items);else if(t instanceof tr)e.push(t);else e.push(_v(t))}M.addCodeArg=Zs;function hv(e){let t=1;while(t<e.length-1){if(e[t]===Xs){let r=gv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function gv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof tr||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof tr))return`"${e}${t.slice(1)}`;return}function yv(e,t){return t.emptyStr()?e:e.emptyStr()?t:Pd`${e}${t}`}M.strConcat=yv;function _v(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Vr(Array.isArray(e)?e.join(","):e)}function Pv(e){return new De(Vr(e))}M.stringify=Pv;function Vr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Vr;function bv(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new De(`.${e}`):_d`[${e}]`}M.getProperty=bv;function vv(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new De(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=vv;function wv(e){return new De(e.toString())}M.regexpCode=wv});var ro=b(function(_e){Object.defineProperty(_e,"__esModule",{value:!0});_e.ValueScope=_e.ValueScopeName=_e.Scope=_e.varKinds=_e.UsedValueState=void 0;var ye=Kr();class bd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var tn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(tn||(_e.UsedValueState=tn={}));_e.varKinds={const:new ye.Name("const"),let:new ye.Name("let"),var:new ye.Name("var")};class eo{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ye.Name?e:this.name(e)}name(e){return new ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}_e.Scope=eo;class to extends ye.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=ye._`.${new ye.Name(t)}[${r}]`}}_e.ValueScopeName=to;var $v=ye._`\n`;class vd extends eo{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$v:ye.nil}}get(){return this._scope}name(e){return new to(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:n}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[n];if(o){let u=o.get(s);if(u)return u}else o=this._values[n]=new Map;o.set(s,i);let a=this._scope[n]||(this._scope[n]=[]),c=a.length;return a[c]=t.ref,i.setValue(t,{property:n,itemIndex:c}),i}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return ye._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(i)=>{if(i.value===void 0)throw Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let n=ye.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((c)=>{if(a.has(c))return;a.set(c,tn.Started);let u=t(c);if(u){let l=this.opts.es5?_e.varKinds.var:_e.varKinds.const;n=ye._`${n}${l} ${c} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(c))n=ye._`${n}${u}${this.opts._n}`;else throw new bd(c);a.set(c,tn.Completed)})}return n}}_e.ValueScope=vd});var F=b(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=Kr(),Ne=ro(),mt=Kr();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return mt._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return mt.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return mt.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return mt.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return mt.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return mt.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return mt.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return mt.Name}});var ln=ro();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return ln.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return ln.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return ln.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return ln.varKinds}});A.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("+")};class ht{optimizeNodes(){return this}optimizeNames(e,t){return this}}class wd extends ht{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?Ne.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ir(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class so extends ht{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ir(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return an(e,this.rhs)}}class $d extends so{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Ed extends ht{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Id extends ht{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Sd extends ht{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class xd extends ht{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ir(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class cn extends ht{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;while(i--){let n=r[i];if(n.optimizeNames(e,t))continue;Ev(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Ct(e,t.names),{})}}class gt extends cn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Rd extends cn{}class zr extends gt{}zr.kind="else";class st extends gt{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new zr(r):r}if(t){if(e===!1)return t instanceof st?t:t.nodes;if(this.nodes.length)return this;return new st(Td(e),t instanceof st?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ir(this.condition,e,t),this}get names(){let e=super.names;if(an(e,this.condition),this.else)Ct(e,this.else.names);return e}}st.kind="if";class rr extends gt{}rr.kind="for";class Cd extends rr{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ir(this.iteration,e,t),this}get names(){return Ct(super.names,this.iteration.names)}}class jd extends rr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?Ne.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=an(super.names,this.from);return an(e,this.to)}}class io extends rr{constructor(e,t,r,i){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ir(this.iterable,e,t),this}get names(){return Ct(super.names,this.iterable.names)}}class rn extends gt{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}rn.kind="func";class nn extends cn{render(e){return"return "+super.render(e)}}nn.kind="return";class Fd extends gt{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)Ct(e,this.catch.names);if(this.finally)Ct(e,this.finally.names);return e}}class sn extends gt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}sn.kind="catch";class on extends gt{render(e){return"finally"+super.render(e)}}on.kind="finally";class Od{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
4
- `:""},this._extScope=e,this._scope=new Ne.Scope({parent:e}),this._nodes=[new Rd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let n=this._scope.toName(t);if(r!==void 0&&i)this._constants[n.str]=r;return this._leafNode(new wd(e,n,r)),n}const(e,t,r){return this._def(Ne.varKinds.const,e,t,r)}let(e,t,r){return this._def(Ne.varKinds.let,e,t,r)}var(e,t,r){return this._def(Ne.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new so(e,t,r))}add(e,t){return this._leafNode(new $d(e,A.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new xd(e));return this}object(...e){let t=["{"];for(let[r,i]of e){if(t.length>1)t.push(",");if(t.push(r),r!==i||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,i)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new st(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new st(e))}else(){return this._elseNode(new zr)}endIf(){return this._endBlockNode(st,zr)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Cd(e),t)}forRange(e,t,r,i,n=this.opts.es5?Ne.varKinds.var:Ne.varKinds.let){let s=this._scope.toName(e);return this._for(new jd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=Ne.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let s=t instanceof N.Name?t:this.var("_arr",t);return this.forRange("_i",0,N._`${s}.length`,(o)=>{this.var(n,N._`${s}[${o}]`),r(n)})}return this._for(new io("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let n=this._scope.toName(e);return this._for(new io("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Ed(e))}break(e){return this._leafNode(new Id(e))}return(e){let t=new nn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(nn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Fd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new sn(n),t(n)}if(r)this._currNode=i.finally=new on,this.code(r);return this._endBlockNode(sn,on)}throw(e){return this._leafNode(new Sd(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=N.nil,r,i){if(this._blockNode(new rn(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(rn)}optimize(e=1){while(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,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof st))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}A.CodeGen=Od;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function an(e,t){return t instanceof N._CodeOrName?Ct(e,t.names):e}function ir(e,t,r){if(e instanceof N.Name)return i(e);if(!n(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=i(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function i(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function n(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Ev(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Td(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${no(e)}`}A.not=Td;var Iv=Ad(A.operators.AND);function Sv(...e){return e.reduce(Iv)}A.and=Sv;var xv=Ad(A.operators.OR);function Rv(...e){return e.reduce(xv)}A.or=Rv;function Ad(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${no(t)} ${e} ${no(r)}`}function no(e){return e instanceof N.Name?e:N._`(${e})`}});var D=b(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.checkStrictMode=k.getErrorPath=k.Type=k.useFunc=k.setEvaluated=k.evaluatedPropsToName=k.mergeEvaluated=k.eachItem=k.unescapeJsonPointer=k.escapeJsonPointer=k.escapeFragment=k.unescapeFragment=k.schemaRefOrVal=k.schemaHasRulesButRef=k.schemaHasRules=k.checkUnknownRules=k.alwaysValidSchema=k.toHash=void 0;var G=F(),Cv=Kr();function jv(e){let t={};for(let r of e)t[r]=!0;return t}k.toHash=jv;function Fv(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Nd(e,t),!Ld(t,e.self.RULES.all)}k.alwaysValidSchema=Fv;function Nd(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let n=i.RULES.keywords;for(let s in t)if(!n[s])Ud(e,`unknown keyword: "${s}"`)}k.checkUnknownRules=Nd;function Ld(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}k.schemaHasRules=Ld;function Ov(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}k.schemaHasRulesButRef=Ov;function Tv({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(i)}`}k.schemaRefOrVal=Tv;function Av(e){return qd(decodeURIComponent(e))}k.unescapeFragment=Av;function kv(e){return encodeURIComponent(ao(e))}k.escapeFragment=kv;function ao(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}k.escapeJsonPointer=ao;function qd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}k.unescapeJsonPointer=qd;function Dv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}k.eachItem=Dv;function kd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let c=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(n,s,o):t(n,s,o),o):s instanceof G.Name?(t(n,o,s),s):r(s,o);return a===G.Name&&!(c instanceof G.Name)?i(n,c):c}}k.mergeEvaluated={props:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>{e.if(G._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,G._`${r} || {}`).code(G._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,G._`${r} || {}`),lo(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Md}),items:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,G._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>e.assign(r,t===!0?!0:G._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Md(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)lo(e,r,t);return r}k.evaluatedPropsToName=Md;function lo(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}k.setEvaluated=lo;var Dd={};function Nv(e,t){return e.scopeValue("func",{ref:t,code:Dd[t.code]||(Dd[t.code]=new Cv._Code(t.code))})}k.useFunc=Nv;var oo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oo||(k.Type=oo={}));function Lv(e,t,r){if(e instanceof G.Name){let i=t===oo.Num;return r?i?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:i?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+ao(e)}k.getErrorPath=Lv;function Ud(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}k.checkStrictMode=Ud});var Re=b(function(co){Object.defineProperty(co,"__esModule",{value:!0});var ae=F(),qv={data:new ae.Name("data"),valCxt:new ae.Name("valCxt"),instancePath:new ae.Name("instancePath"),parentData:new ae.Name("parentData"),parentDataProperty:new ae.Name("parentDataProperty"),rootData:new ae.Name("rootData"),dynamicAnchors:new ae.Name("dynamicAnchors"),vErrors:new ae.Name("vErrors"),errors:new ae.Name("errors"),this:new ae.Name("this"),self:new ae.Name("self"),scope:new ae.Name("scope"),json:new ae.Name("json"),jsonPos:new ae.Name("jsonPos"),jsonLen:new ae.Name("jsonLen"),jsonPart:new ae.Name("jsonPart")};co.default=qv});var Wr=b(function(le){Object.defineProperty(le,"__esModule",{value:!0});le.extendErrors=le.resetErrorsCount=le.reportExtraError=le.reportError=le.keyword$DataError=le.keywordError=void 0;var L=F(),dn=D(),ue=Re();le.keywordError={message:({keyword:e})=>L.str`must pass "${e}" keyword validation`};le.keyword$DataError={message:({keyword:e,schemaType:t})=>t?L.str`"${e}" keyword must be ${t} ($data)`:L.str`"${e}" keyword is invalid ($data)`};function Mv(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,c=Vd(e,t,r);if(i!==null&&i!==void 0?i:o||a)Bd(s,c);else Gd(n,L._`[${c}]`)}le.reportError=Mv;function Uv(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=Vd(e,t,r);if(Bd(n,a),!(s||o))Gd(i,ue.default.vErrors)}le.reportExtraError=Uv;function Bv(e,t){e.assign(ue.default.errors,t),e.if(L._`${ue.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${ue.default.vErrors}.length`,t),()=>e.assign(ue.default.vErrors,null)))}le.resetErrorsCount=Bv;function Gv({gen:e,keyword:t,schemaValue:r,data:i,errsCount:n,it:s}){if(n===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",n,ue.default.errors,(a)=>{if(e.const(o,L._`${ue.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(ue.default.instancePath,s.errorPath))),e.assign(L._`${o}.schemaPath`,L.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(L._`${o}.schema`,r),e.assign(L._`${o}.data`,i)})}le.extendErrors=Gv;function Bd(e,t){let r=e.const("err",t);e.if(L._`${ue.default.vErrors} === null`,()=>e.assign(ue.default.vErrors,L._`[${r}]`),L._`${ue.default.vErrors}.push(${r})`),e.code(L._`${ue.default.errors}++`)}function Gd(e,t){let{gen:r,validateName:i,schemaEnv:n}=e;if(n.$async)r.throw(L._`new ${e.ValidationError}(${t})`);else r.assign(L._`${i}.errors`,t),r.return(!1)}var jt={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 Vd(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Vv(e,t,r)}function Vv(e,t,r={}){let{gen:i,it:n}=e,s=[Kv(n,r),zv(e,r)];return Wv(e,t,s),i.object(...s)}function Kv({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,dn.getErrorPath)(t,dn.Type.Str)}`:e;return[ue.default.instancePath,(0,L.strConcat)(ue.default.instancePath,r)]}function zv({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,dn.getErrorPath)(r,dn.Type.Str)}`;return[jt.schemaPath,n]}function Wv(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;if(i.push([jt.keyword,n],[jt.params,typeof t=="function"?t(e):t||L._`{}`]),c.messages)i.push([jt.message,typeof r=="function"?r(e):r]);if(c.verbose)i.push([jt.schema,o],[jt.parentSchema,L._`${l}${d}`],[ue.default.data,s]);if(u)i.push([jt.propertyName,u])}});var zd=b(function(nr){Object.defineProperty(nr,"__esModule",{value:!0});nr.boolOrEmptySchema=nr.topBoolOrEmptySchema=void 0;var Hv=Wr(),Jv=F(),Qv=Re(),Yv={message:"boolean schema is false"};function Xv(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)Kd(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Qv.default.data);else t.assign(Jv._`${i}.errors`,null),t.return(!0)}nr.topBoolOrEmptySchema=Xv;function Zv(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),Kd(e);else r.var(t,!0)}nr.boolOrEmptySchema=Zv;function Kd(e,t){let{gen:r,data:i}=e,n={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Hv.reportError)(n,Yv,void 0,t)}});var uo=b(function(sr){Object.defineProperty(sr,"__esModule",{value:!0});sr.getRules=sr.isJSONType=void 0;var ew=["string","number","integer","boolean","null","object","array"],tw=new Set(ew);function rw(e){return typeof e=="string"&&tw.has(e)}sr.isJSONType=rw;function iw(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}sr.getRules=iw});var po=b(function(yt){Object.defineProperty(yt,"__esModule",{value:!0});yt.shouldUseRule=yt.shouldUseGroup=yt.schemaHasRulesForType=void 0;function nw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&Wd(e,i)}yt.schemaHasRulesForType=nw;function Wd(e,t){return t.rules.some((r)=>Hd(e,r))}yt.shouldUseGroup=Wd;function Hd(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((i)=>e[i]!==void 0))}yt.shouldUseRule=Hd});var Hr=b(function(ce){Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;var sw=uo(),ow=po(),aw=Wr(),O=F(),Jd=D(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ce.DataType=or={}));function lw(e){let t=Qd(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}ce.getSchemaTypes=lw;function Qd(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(sw.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=Qd;function cw(e,t){let{gen:r,data:i,opts:n}=e,s=dw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,ow.schemaHasRulesForType)(e,t[0]));if(o){let a=mo(t,i,n.strictNumbers,or.Wrong);r.if(a,()=>{if(s.length)uw(e,t,s);else ho(e)})}return o}ce.coerceAndCheckDataType=cw;var Yd=new Set(["string","number","integer","boolean","null"]);function dw(e,t){return t?e.filter((r)=>Yd.has(r)||t==="array"&&r==="array"):[]}function uw(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",O._`typeof ${n}`),a=i.let("coerced",O._`undefined`);if(s.coerceTypes==="array")i.if(O._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,O._`${n}[0]`).assign(o,O._`typeof ${n}`).if(mo(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(O._`${a} !== undefined`);for(let u of r)if(Yd.has(u)||u==="array"&&s.coerceTypes==="array")c(u);i.else(),ho(e),i.endIf(),i.if(O._`${a} !== undefined`,()=>{i.assign(n,a),pw(e,a)});function c(u){switch(u){case"string":i.elseIf(O._`${o} == "number" || ${o} == "boolean"`).assign(a,O._`"" + ${n}`).elseIf(O._`${n} === null`).assign(a,O._`""`);return;case"number":i.elseIf(O._`${o} == "boolean" || ${n} === null
3
+ (function(exports, require, module, __filename, __dirname) {var Yy=Object.create;var{getPrototypeOf:Xy,defineProperty:ks,getOwnPropertyNames:Zy}=Object;var e_=Object.prototype.hasOwnProperty;function t_(e){return this[e]}var r_,i_,xe=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?r_??=new WeakMap:i_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?Yy(Xy(e)):{};let o=t||!e||!e.__esModule?ks(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Zy(e))if(!e_.call(o,a))ks(o,a,{get:t_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var n_=(e)=>e;function s_(e,t){this[e]=n_.bind(null,t)}var o_=(e,t)=>{for(var r in t)ks(e,r,{get:t[r],enumerable:!0,configurable:!0,set:s_.bind(t,r)})};var Kr=b(function(M){Object.defineProperty(M,"__esModule",{value:!0});M.regexpCode=M.getEsmExportName=M.getProperty=M.safeStringify=M.stringify=M.strConcat=M.addCodeArg=M.str=M._=M.nil=M._Code=M.Name=M.IDENTIFIER=M._CodeOrName=void 0;class en{}M._CodeOrName=en;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class tr extends en{constructor(e){super();if(!M.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}M.Name=tr;class De extends en{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((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof tr)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=De;M.nil=new De("");function _d(e,...t){let r=[e[0]],i=0;while(i<t.length)Zs(r,t[i]),r.push(e[++i]);return new De(r)}M._=_d;var Xs=new De("+");function Pd(e,...t){let r=[Vr(e[0])],i=0;while(i<t.length)r.push(Xs),Zs(r,t[i]),r.push(Xs,Vr(e[++i]));return gv(r),new De(r)}M.str=Pd;function Zs(e,t){if(t instanceof De)e.push(...t._items);else if(t instanceof tr)e.push(t);else e.push(Pv(t))}M.addCodeArg=Zs;function gv(e){let t=1;while(t<e.length-1){if(e[t]===Xs){let r=yv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function yv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof tr||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof tr))return`"${e}${t.slice(1)}`;return}function _v(e,t){return t.emptyStr()?e:e.emptyStr()?t:Pd`${e}${t}`}M.strConcat=_v;function Pv(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Vr(Array.isArray(e)?e.join(","):e)}function bv(e){return new De(Vr(e))}M.stringify=bv;function Vr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Vr;function vv(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new De(`.${e}`):_d`[${e}]`}M.getProperty=vv;function wv(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new De(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=wv;function $v(e){return new De(e.toString())}M.regexpCode=$v});var ro=b(function(_e){Object.defineProperty(_e,"__esModule",{value:!0});_e.ValueScope=_e.ValueScopeName=_e.Scope=_e.varKinds=_e.UsedValueState=void 0;var ye=Kr();class bd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var tn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(tn||(_e.UsedValueState=tn={}));_e.varKinds={const:new ye.Name("const"),let:new ye.Name("let"),var:new ye.Name("var")};class eo{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ye.Name?e:this.name(e)}name(e){return new ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}_e.Scope=eo;class to extends ye.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=ye._`.${new ye.Name(t)}[${r}]`}}_e.ValueScopeName=to;var Ev=ye._`\n`;class vd extends eo{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Ev:ye.nil}}get(){return this._scope}name(e){return new to(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:n}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[n];if(o){let u=o.get(s);if(u)return u}else o=this._values[n]=new Map;o.set(s,i);let a=this._scope[n]||(this._scope[n]=[]),c=a.length;return a[c]=t.ref,i.setValue(t,{property:n,itemIndex:c}),i}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return ye._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(i)=>{if(i.value===void 0)throw Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let n=ye.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((c)=>{if(a.has(c))return;a.set(c,tn.Started);let u=t(c);if(u){let l=this.opts.es5?_e.varKinds.var:_e.varKinds.const;n=ye._`${n}${l} ${c} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(c))n=ye._`${n}${u}${this.opts._n}`;else throw new bd(c);a.set(c,tn.Completed)})}return n}}_e.ValueScope=vd});var F=b(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=Kr(),Ne=ro(),ht=Kr();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return ht._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return ht.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return ht.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return ht.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return ht.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return ht.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return ht.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return ht.Name}});var ln=ro();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return ln.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return ln.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return ln.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return ln.varKinds}});A.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("+")};class gt{optimizeNodes(){return this}optimizeNames(e,t){return this}}class wd extends gt{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?Ne.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ir(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class so extends gt{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ir(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return an(e,this.rhs)}}class $d extends so{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Ed extends gt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Id extends gt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Sd extends gt{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class xd extends gt{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ir(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class cn extends gt{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;while(i--){let n=r[i];if(n.optimizeNames(e,t))continue;Iv(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Ct(e,t.names),{})}}class yt extends cn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Rd extends cn{}class zr extends yt{}zr.kind="else";class nt extends yt{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new zr(r):r}if(t){if(e===!1)return t instanceof nt?t:t.nodes;if(this.nodes.length)return this;return new nt(Td(e),t instanceof nt?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ir(this.condition,e,t),this}get names(){let e=super.names;if(an(e,this.condition),this.else)Ct(e,this.else.names);return e}}nt.kind="if";class rr extends yt{}rr.kind="for";class Cd extends rr{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ir(this.iteration,e,t),this}get names(){return Ct(super.names,this.iteration.names)}}class jd extends rr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?Ne.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=an(super.names,this.from);return an(e,this.to)}}class io extends rr{constructor(e,t,r,i){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ir(this.iterable,e,t),this}get names(){return Ct(super.names,this.iterable.names)}}class rn extends yt{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}rn.kind="func";class nn extends cn{render(e){return"return "+super.render(e)}}nn.kind="return";class Fd extends yt{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)Ct(e,this.catch.names);if(this.finally)Ct(e,this.finally.names);return e}}class sn extends yt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}sn.kind="catch";class on extends yt{render(e){return"finally"+super.render(e)}}on.kind="finally";class Od{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
4
+ `:""},this._extScope=e,this._scope=new Ne.Scope({parent:e}),this._nodes=[new Rd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let n=this._scope.toName(t);if(r!==void 0&&i)this._constants[n.str]=r;return this._leafNode(new wd(e,n,r)),n}const(e,t,r){return this._def(Ne.varKinds.const,e,t,r)}let(e,t,r){return this._def(Ne.varKinds.let,e,t,r)}var(e,t,r){return this._def(Ne.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new so(e,t,r))}add(e,t){return this._leafNode(new $d(e,A.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new xd(e));return this}object(...e){let t=["{"];for(let[r,i]of e){if(t.length>1)t.push(",");if(t.push(r),r!==i||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,i)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new nt(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new nt(e))}else(){return this._elseNode(new zr)}endIf(){return this._endBlockNode(nt,zr)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Cd(e),t)}forRange(e,t,r,i,n=this.opts.es5?Ne.varKinds.var:Ne.varKinds.let){let s=this._scope.toName(e);return this._for(new jd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=Ne.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let s=t instanceof N.Name?t:this.var("_arr",t);return this.forRange("_i",0,N._`${s}.length`,(o)=>{this.var(n,N._`${s}[${o}]`),r(n)})}return this._for(new io("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let n=this._scope.toName(e);return this._for(new io("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Ed(e))}break(e){return this._leafNode(new Id(e))}return(e){let t=new nn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(nn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Fd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new sn(n),t(n)}if(r)this._currNode=i.finally=new on,this.code(r);return this._endBlockNode(sn,on)}throw(e){return this._leafNode(new Sd(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=N.nil,r,i){if(this._blockNode(new rn(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(rn)}optimize(e=1){while(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,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof nt))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}A.CodeGen=Od;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function an(e,t){return t instanceof N._CodeOrName?Ct(e,t.names):e}function ir(e,t,r){if(e instanceof N.Name)return i(e);if(!n(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=i(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function i(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function n(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Iv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Td(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${no(e)}`}A.not=Td;var Sv=Ad(A.operators.AND);function xv(...e){return e.reduce(Sv)}A.and=xv;var Rv=Ad(A.operators.OR);function Cv(...e){return e.reduce(Rv)}A.or=Cv;function Ad(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${no(t)} ${e} ${no(r)}`}function no(e){return e instanceof N.Name?e:N._`(${e})`}});var D=b(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.checkStrictMode=k.getErrorPath=k.Type=k.useFunc=k.setEvaluated=k.evaluatedPropsToName=k.mergeEvaluated=k.eachItem=k.unescapeJsonPointer=k.escapeJsonPointer=k.escapeFragment=k.unescapeFragment=k.schemaRefOrVal=k.schemaHasRulesButRef=k.schemaHasRules=k.checkUnknownRules=k.alwaysValidSchema=k.toHash=void 0;var G=F(),jv=Kr();function Fv(e){let t={};for(let r of e)t[r]=!0;return t}k.toHash=Fv;function Ov(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Nd(e,t),!Ld(t,e.self.RULES.all)}k.alwaysValidSchema=Ov;function Nd(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let n=i.RULES.keywords;for(let s in t)if(!n[s])Ud(e,`unknown keyword: "${s}"`)}k.checkUnknownRules=Nd;function Ld(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}k.schemaHasRules=Ld;function Tv(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}k.schemaHasRulesButRef=Tv;function Av({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(i)}`}k.schemaRefOrVal=Av;function kv(e){return qd(decodeURIComponent(e))}k.unescapeFragment=kv;function Dv(e){return encodeURIComponent(ao(e))}k.escapeFragment=Dv;function ao(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}k.escapeJsonPointer=ao;function qd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}k.unescapeJsonPointer=qd;function Nv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}k.eachItem=Nv;function kd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let c=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(n,s,o):t(n,s,o),o):s instanceof G.Name?(t(n,o,s),s):r(s,o);return a===G.Name&&!(c instanceof G.Name)?i(n,c):c}}k.mergeEvaluated={props:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>{e.if(G._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,G._`${r} || {}`).code(G._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,G._`${r} || {}`),lo(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Md}),items:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,G._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>e.assign(r,t===!0?!0:G._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Md(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)lo(e,r,t);return r}k.evaluatedPropsToName=Md;function lo(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}k.setEvaluated=lo;var Dd={};function Lv(e,t){return e.scopeValue("func",{ref:t,code:Dd[t.code]||(Dd[t.code]=new jv._Code(t.code))})}k.useFunc=Lv;var oo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oo||(k.Type=oo={}));function qv(e,t,r){if(e instanceof G.Name){let i=t===oo.Num;return r?i?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:i?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+ao(e)}k.getErrorPath=qv;function Ud(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}k.checkStrictMode=Ud});var Re=b(function(co){Object.defineProperty(co,"__esModule",{value:!0});var ae=F(),Mv={data:new ae.Name("data"),valCxt:new ae.Name("valCxt"),instancePath:new ae.Name("instancePath"),parentData:new ae.Name("parentData"),parentDataProperty:new ae.Name("parentDataProperty"),rootData:new ae.Name("rootData"),dynamicAnchors:new ae.Name("dynamicAnchors"),vErrors:new ae.Name("vErrors"),errors:new ae.Name("errors"),this:new ae.Name("this"),self:new ae.Name("self"),scope:new ae.Name("scope"),json:new ae.Name("json"),jsonPos:new ae.Name("jsonPos"),jsonLen:new ae.Name("jsonLen"),jsonPart:new ae.Name("jsonPart")};co.default=Mv});var Wr=b(function(le){Object.defineProperty(le,"__esModule",{value:!0});le.extendErrors=le.resetErrorsCount=le.reportExtraError=le.reportError=le.keyword$DataError=le.keywordError=void 0;var L=F(),dn=D(),ue=Re();le.keywordError={message:({keyword:e})=>L.str`must pass "${e}" keyword validation`};le.keyword$DataError={message:({keyword:e,schemaType:t})=>t?L.str`"${e}" keyword must be ${t} ($data)`:L.str`"${e}" keyword is invalid ($data)`};function Uv(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,c=Vd(e,t,r);if(i!==null&&i!==void 0?i:o||a)Bd(s,c);else Gd(n,L._`[${c}]`)}le.reportError=Uv;function Bv(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=Vd(e,t,r);if(Bd(n,a),!(s||o))Gd(i,ue.default.vErrors)}le.reportExtraError=Bv;function Gv(e,t){e.assign(ue.default.errors,t),e.if(L._`${ue.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${ue.default.vErrors}.length`,t),()=>e.assign(ue.default.vErrors,null)))}le.resetErrorsCount=Gv;function Vv({gen:e,keyword:t,schemaValue:r,data:i,errsCount:n,it:s}){if(n===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",n,ue.default.errors,(a)=>{if(e.const(o,L._`${ue.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(ue.default.instancePath,s.errorPath))),e.assign(L._`${o}.schemaPath`,L.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(L._`${o}.schema`,r),e.assign(L._`${o}.data`,i)})}le.extendErrors=Vv;function Bd(e,t){let r=e.const("err",t);e.if(L._`${ue.default.vErrors} === null`,()=>e.assign(ue.default.vErrors,L._`[${r}]`),L._`${ue.default.vErrors}.push(${r})`),e.code(L._`${ue.default.errors}++`)}function Gd(e,t){let{gen:r,validateName:i,schemaEnv:n}=e;if(n.$async)r.throw(L._`new ${e.ValidationError}(${t})`);else r.assign(L._`${i}.errors`,t),r.return(!1)}var jt={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 Vd(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Kv(e,t,r)}function Kv(e,t,r={}){let{gen:i,it:n}=e,s=[zv(n,r),Wv(e,r)];return Hv(e,t,s),i.object(...s)}function zv({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,dn.getErrorPath)(t,dn.Type.Str)}`:e;return[ue.default.instancePath,(0,L.strConcat)(ue.default.instancePath,r)]}function Wv({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,dn.getErrorPath)(r,dn.Type.Str)}`;return[jt.schemaPath,n]}function Hv(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;if(i.push([jt.keyword,n],[jt.params,typeof t=="function"?t(e):t||L._`{}`]),c.messages)i.push([jt.message,typeof r=="function"?r(e):r]);if(c.verbose)i.push([jt.schema,o],[jt.parentSchema,L._`${l}${d}`],[ue.default.data,s]);if(u)i.push([jt.propertyName,u])}});var zd=b(function(nr){Object.defineProperty(nr,"__esModule",{value:!0});nr.boolOrEmptySchema=nr.topBoolOrEmptySchema=void 0;var Jv=Wr(),Qv=F(),Yv=Re(),Xv={message:"boolean schema is false"};function Zv(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)Kd(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Yv.default.data);else t.assign(Qv._`${i}.errors`,null),t.return(!0)}nr.topBoolOrEmptySchema=Zv;function ew(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),Kd(e);else r.var(t,!0)}nr.boolOrEmptySchema=ew;function Kd(e,t){let{gen:r,data:i}=e,n={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Jv.reportError)(n,Xv,void 0,t)}});var uo=b(function(sr){Object.defineProperty(sr,"__esModule",{value:!0});sr.getRules=sr.isJSONType=void 0;var tw=["string","number","integer","boolean","null","object","array"],rw=new Set(tw);function iw(e){return typeof e=="string"&&rw.has(e)}sr.isJSONType=iw;function nw(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}sr.getRules=nw});var po=b(function(_t){Object.defineProperty(_t,"__esModule",{value:!0});_t.shouldUseRule=_t.shouldUseGroup=_t.schemaHasRulesForType=void 0;function sw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&Wd(e,i)}_t.schemaHasRulesForType=sw;function Wd(e,t){return t.rules.some((r)=>Hd(e,r))}_t.shouldUseGroup=Wd;function Hd(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((i)=>e[i]!==void 0))}_t.shouldUseRule=Hd});var Hr=b(function(ce){Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;var ow=uo(),aw=po(),lw=Wr(),O=F(),Jd=D(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ce.DataType=or={}));function cw(e){let t=Qd(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}ce.getSchemaTypes=cw;function Qd(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(ow.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=Qd;function dw(e,t){let{gen:r,data:i,opts:n}=e,s=uw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,aw.schemaHasRulesForType)(e,t[0]));if(o){let a=mo(t,i,n.strictNumbers,or.Wrong);r.if(a,()=>{if(s.length)pw(e,t,s);else ho(e)})}return o}ce.coerceAndCheckDataType=dw;var Yd=new Set(["string","number","integer","boolean","null"]);function uw(e,t){return t?e.filter((r)=>Yd.has(r)||t==="array"&&r==="array"):[]}function pw(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",O._`typeof ${n}`),a=i.let("coerced",O._`undefined`);if(s.coerceTypes==="array")i.if(O._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,O._`${n}[0]`).assign(o,O._`typeof ${n}`).if(mo(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(O._`${a} !== undefined`);for(let u of r)if(Yd.has(u)||u==="array"&&s.coerceTypes==="array")c(u);i.else(),ho(e),i.endIf(),i.if(O._`${a} !== undefined`,()=>{i.assign(n,a),fw(e,a)});function c(u){switch(u){case"string":i.elseIf(O._`${o} == "number" || ${o} == "boolean"`).assign(a,O._`"" + ${n}`).elseIf(O._`${n} === null`).assign(a,O._`""`);return;case"number":i.elseIf(O._`${o} == "boolean" || ${n} === null
5
5
  || (${o} == "string" && ${n} && ${n} == +${n})`).assign(a,O._`+${n}`);return;case"integer":i.elseIf(O._`${o} === "boolean" || ${n} === null
6
6
  || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,O._`+${n}`);return;case"boolean":i.elseIf(O._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf(O._`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":i.elseIf(O._`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(a,null);return;case"array":i.elseIf(O._`${o} === "string" || ${o} === "number"
7
- || ${o} === "boolean" || ${n} === null`).assign(a,O._`[${n}]`)}}}function pw({gen:e,parentData:t,parentDataProperty:r},i){e.if(O._`${t} !== undefined`,()=>e.assign(O._`${t}[${r}]`,i))}function fo(e,t,r,i=or.Correct){let n=i===or.Correct?O.operators.EQ:O.operators.NEQ,s;switch(e){case"null":return O._`${t} ${n} null`;case"array":s=O._`Array.isArray(${t})`;break;case"object":s=O._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(O._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return O._`typeof ${t} ${n} ${e}`}return i===or.Correct?s:(0,O.not)(s);function o(a=O.nil){return(0,O.and)(O._`typeof ${t} == "number"`,a,r?O._`isFinite(${t})`:O.nil)}}ce.checkDataType=fo;function mo(e,t,r,i){if(e.length===1)return fo(e[0],t,r,i);let n,s=(0,Jd.toHash)(e);if(s.array&&s.object){let o=O._`typeof ${t} != "object"`;n=s.null?o:O._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=O.nil;if(s.number)delete s.integer;for(let o in s)n=(0,O.and)(n,fo(o,t,r,i));return n}ce.checkDataTypes=mo;var fw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?O._`{type: ${e}}`:O._`{type: ${t}}`};function ho(e){let t=mw(e);(0,aw.reportError)(t,fw)}ce.reportTypeError=ho;function mw(e){let{gen:t,data:r,schema:i}=e,n=(0,Jd.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var Zd=b(function(un){Object.defineProperty(un,"__esModule",{value:!0});un.assignDefaults=void 0;var ar=F(),hw=D();function gw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)Xd(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>Xd(e,s,n.default))}un.assignDefaults=gw;function Xd(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=ar._`${s}${(0,ar.getProperty)(t)}`;if(n){(0,hw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=ar._`${a} === undefined`;if(o.useDefaults==="empty")c=ar._`${c} || ${a} === null || ${a} === ""`;i.if(c,ar._`${a} = ${(0,ar.stringify)(r)}`)}});var Ce=b(function(B){Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var K=F(),go=D(),_t=Re(),yw=D();function _w(e,t){let{gen:r,data:i,it:n}=e;r.if(_o(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=_w;function Pw({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(_o(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=Pw;function bw(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=bw;function eu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=eu;function yo(e,t,r){return K._`${eu(e)}.call(${t}, ${r})`}B.isOwnProperty=yo;function vw(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${yo(e,t,r)}`:n}B.propertyInData=vw;function _o(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(yo(e,t,r))):n}B.noPropertyInData=_o;function tu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=tu;function ww(e,t){return tu(t).filter((r)=>!(0,go.alwaysValidSchema)(e,t[r]))}B.schemaProperties=ww;function $w({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,c,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,d=[[_t.default.instancePath,(0,K.strConcat)(_t.default.instancePath,s)],[_t.default.parentData,o.parentData],[_t.default.parentDataProperty,o.parentDataProperty],[_t.default.rootData,_t.default.rootData]];if(o.opts.dynamicRef)d.push([_t.default.dynamicAnchors,_t.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...d)}`;return c!==K.nil?K._`${a}.call(${c}, ${p})`:K._`${a}(${p})`}B.callValidateCode=$w;var Ew=K._`new RegExp`;function Iw({gen:e,it:{opts:t}},r){let i=t.unicodeRegExp?"u":"",{regExp:n}=t.code,s=n(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${n.code==="new RegExp"?Ew:(0,yw.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=Iw;function Sw(e){let{gen:t,data:r,keyword:i,it:n}=e,s=t.name("valid");if(n.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",K._`${r}.length`);t.forRange("i",0,c,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:go.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=Sw;function xw(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>(0,go.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:i,schemaProp:u,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(l,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=xw});var nu=b(function(Ve){Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateKeywordUsage=Ve.validSchemaType=Ve.funcKeywordCode=Ve.macroKeywordCode=void 0;var pe=F(),Ft=Re(),Rw=Ce(),Cw=Wr();function jw(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),c=iu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:pe.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ve.macroKeywordCode=jw;function Fw(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:c}=e;Tw(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,l=iu(i,n,u),d=i.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1){if(h(),t.modifying)ru(e);g(()=>e.error())}else{let y=t.async?f():m();if(t.modifying)ru(e);g(()=>Ow(e,y))}}function f(){let y=i.let("ruleErrs",null);return i.try(()=>h(pe._`await `),(P)=>i.assign(d,!1).if(pe._`${P} instanceof ${c.ValidationError}`,()=>i.assign(y,pe._`${P}.errors`),()=>i.throw(P))),y}function m(){let y=pe._`${l}.errors`;return i.assign(y,null),h(pe.nil),y}function h(y=t.async?pe._`await `:pe.nil){let P=c.opts.passContext?Ft.default.this:Ft.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(d,pe._`${y}${(0,Rw.callValidateCode)(e,l,P,v)}`,t.modifying)}function g(y){var P;i.if((0,pe.not)((P=t.valid)!==null&&P!==void 0?P:d),y)}}Ve.funcKeywordCode=Fw;function ru(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,pe._`${i.parentData}[${i.parentDataProperty}]`))}function Ow(e,t){let{gen:r}=e;r.if(pe._`Array.isArray(${t})`,()=>{r.assign(Ft.default.vErrors,pe._`${Ft.default.vErrors} === null ? ${t} : ${Ft.default.vErrors}.concat(${t})`).assign(Ft.default.errors,pe._`${Ft.default.vErrors}.length`),(0,Cw.extendErrors)(e)},()=>e.error())}function Tw({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function iu(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,pe.stringify)(r)})}function Aw(e,t,r=!1){return!t.length||t.some((i)=>i==="array"?Array.isArray(e):i==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==i||r&&typeof e>"u")}Ve.validSchemaType=Aw;function kw({schema:e,opts:t,self:r,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw Error("ajv implementation error");let o=n.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}Ve.validateKeywordUsage=kw});var ou=b(function(Pt){Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendSubschemaMode=Pt.extendSubschemaData=Pt.getSubschema=void 0;var Ke=F(),su=D();function Dw(e,{keyword:t,schemaProp:r,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&i!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}${(0,Ke.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,su.escapeFragment)(r)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}Pt.getSubschema=Dw;function Nw(e,t,{dataProp:r,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",Ke._`${t.data}${(0,Ke.getProperty)(r)}`,!0);c(p),e.errorPath=Ke.str`${u}${(0,su.getErrorPath)(r,i,d.jsPropertySyntax)}`,e.parentDataProperty=Ke._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Ke.Name?n:a.let("data",n,!0);if(c(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}Pt.extendSubschemaData=Nw;function Lw(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:n,allErrors:s}){if(i!==void 0)e.compositeRule=i;if(n!==void 0)e.createErrors=n;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}Pt.extendSubschemaMode=Lw});var Po=b(function(gA,au){au.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if(i=t.length,i!=r.length)return!1;for(n=i;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),i=s.length,i!==Object.keys(r).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var cu=b(function(yA,lu){var bt=lu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var i=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};pn(t,i,n,e,"",e)};bt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};bt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};bt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};bt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function pn(e,t,r,i,n,s,o,a,c,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,c,u);for(var l in i){var d=i[l];if(Array.isArray(d)){if(l in bt.arrayKeywords)for(var p=0;p<d.length;p++)pn(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in bt.propsKeywords){if(d&&typeof d=="object")for(var f in d)pn(e,t,r,d[f],n+"/"+l+"/"+qw(f),s,n,l,i,f)}else if(l in bt.keywords||e.allKeys&&!(l in bt.skipKeywords))pn(e,t,r,d,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,c,u)}}function qw(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Jr=b(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getSchemaRefs=Pe.resolveUrl=Pe.normalizeId=Pe._getFullPath=Pe.getFullPath=Pe.inlineRef=void 0;var Mw=D(),Uw=Po(),Bw=cu(),Gw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Vw(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!bo(e);if(!t)return!1;return du(e)<=t}Pe.inlineRef=Vw;var Kw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bo(e){for(let t in e){if(Kw.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(bo))return!0;if(typeof r=="object"&&bo(r))return!0}return!1}function du(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,Gw.has(r))continue;if(typeof e[r]=="object")(0,Mw.eachItem)(e[r],(i)=>t+=du(i));if(t===1/0)return 1/0}return t}function uu(e,t="",r){if(r!==!1)t=lr(t);let i=e.parse(t);return pu(e,i)}Pe.getFullPath=uu;function pu(e,t){return e.serialize(t).split("#")[0]+"#"}Pe._getFullPath=pu;var zw=/#\/?$/;function lr(e){return e?e.replace(zw,""):""}Pe.normalizeId=lr;function Ww(e,t,r){return r=lr(r),e.resolve(t,r)}Pe.resolveUrl=Ww;var Hw=/^[a-z_][-a-z0-9._]*$/i;function Jw(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=lr(e[r]||t),s={"":n},o=uu(i,n,!1),a={},c=new Set;return Bw(e,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof d[r]=="string")g=y.call(this,d[r]);P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[p]=g;function y(v){let w=this.opts.uriResolver.resolve;if(v=lr(g?w(g,v):v),c.has(v))throw l(v);c.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(d,I.schema,v);else if(v!==lr(h))if(v[0]==="#")u(d,a[v],v),a[v]=d;else this.refs[v]=h;return v}function P(v){if(typeof v=="string"){if(!Hw.test(v))throw Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Uw(d,p))throw l(f)}function l(d){return Error(`reference "${d}" resolves to more than one schema`)}}Pe.getSchemaRefs=Jw});var cr=b(function(vt){Object.defineProperty(vt,"__esModule",{value:!0});vt.getData=vt.KeywordCxt=vt.validateFunctionCode=void 0;var yu=zd(),fu=Hr(),wo=po(),fn=Hr(),Qw=Zd(),Yr=nu(),vo=ou(),S=F(),j=Re(),Yw=Jr(),ot=D(),Qr=Wr();function Xw(e){if(bu(e)){if(vu(e),Pu(e)){t$(e);return}}_u(e,()=>(0,yu.topBoolOrEmptySchema)(e))}vt.validateFunctionCode=Xw;function _u({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${j.default.data}, ${j.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${mu(r,n)}`),e$(e,n),e.code(s)});else e.func(t,S._`${j.default.data}, ${Zw(n)}`,i.$async,()=>e.code(mu(r,n)).code(s))}function Zw(e){return S._`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?S._`, ${j.default.dynamicAnchors}={}`:S.nil}}={}`}function e$(e,t){e.if(j.default.valCxt,()=>{if(e.var(j.default.instancePath,S._`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,S._`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,S._`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,S._`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{if(e.var(j.default.instancePath,S._`""`),e.var(j.default.parentData,S._`undefined`),e.var(j.default.parentDataProperty,S._`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`{}`)})}function t$(e){let{schema:t,opts:r,gen:i}=e;_u(e,()=>{if(r.$comment&&t.$comment)$u(e);if(o$(e),i.let(j.default.vErrors,null),i.let(j.default.errors,0),r.unevaluated)r$(e);wu(e),c$(e)});return}function r$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",S._`${r}.evaluated`),t.if(S._`${e.evaluated}.dynamicProps`,()=>t.assign(S._`${e.evaluated}.props`,S._`undefined`)),t.if(S._`${e.evaluated}.dynamicItems`,()=>t.assign(S._`${e.evaluated}.items`,S._`undefined`))}function mu(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function i$(e,t){if(bu(e)){if(vu(e),Pu(e)){n$(e,t);return}}(0,yu.boolOrEmptySchema)(e,t)}function Pu({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function bu(e){return typeof e.schema!="boolean"}function n$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)$u(e);a$(e),l$(e);let s=i.const("_errs",j.default.errors);wu(e,s),i.var(t,S._`${s} === ${j.default.errors}`)}function vu(e){(0,ot.checkUnknownRules)(e),s$(e)}function wu(e,t){if(e.opts.jtd)return hu(e,[],!1,t);let r=(0,fu.getSchemaTypes)(e.schema),i=(0,fu.coerceAndCheckDataType)(e,r);hu(e,r,!i,t)}function s$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function o$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,ot.checkStrictMode)(e,"default is ignored in the schema root")}function a$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,Yw.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function l$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function $u({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${j.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=S.str`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${j.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function c$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw(S._`new ${n}(${j.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,j.default.vErrors),s.unevaluated)d$(e);t.return(S._`${j.default.errors} === 0`)}}function d$({gen:e,evaluated:t,props:r,items:i}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(i instanceof S.Name)e.assign(S._`${t}.items`,i)}function hu(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(s,l))){n.block(()=>Iu(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)u$(e,t);n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){if(!(0,wo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,fn.checkDataType)(p.type,o,c.strictNumbers)),gu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,fn.reportTypeError)(e);n.endIf()}else gu(e,p);if(!a)n.if(S._`${j.default.errors} === ${i||0}`)}}function gu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,Qw.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,wo.shouldUseRule)(i,s))Iu(e,s.keyword,s.definition,t.type)})}function u$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(p$(e,t),!e.opts.allowUnionTypes)f$(e,t);m$(e,e.dataTypes)}function p$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Eu(e.dataTypes,r))$o(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),g$(e,t)}function f$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))$o(e,"use allowUnionTypes to allow union type keyword")}function m$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,wo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>h$(t,o)))$o(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function h$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Eu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function g$(e,t){let r=[];for(let i of e.dataTypes)if(Eu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function $o(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ot.checkStrictMode)(e,t,e.opts.strictTypes)}class Eo{constructor(e,t,r){if((0,Yr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ot.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Su(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Yr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",j.default.errors)}result(e,t,r){this.failResult((0,S.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,S.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(S._`${t} !== undefined && (${(0,S.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?Qr.reportExtraError:Qr.reportError)(this,this.def.error,t)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Qr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=S.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=S.nil,t=S.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:n,def:s}=this;if(r.if((0,S.or)(S._`${i} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(n.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:n}=this;return(0,S.or)(s(),o());function s(){if(r.length){if(!(t instanceof S.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return S._`${(0,fn.checkDataTypes)(a,t,n.opts.strictNumbers,fn.DataType.Wrong)}`}return S.nil}function o(){if(i.validateSchema){let a=e.scopeValue("validate$data",{ref:i.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,vo.getSubschema)(this.it,e);(0,vo.extendSubschemaData)(r,this.it,e),(0,vo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return i$(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=ot.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=ot.mergeEvaluated.items(i,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}vt.KeywordCxt=Eo;function Iu(e,t,r,i){let n=new Eo(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,Yr.funcKeywordCode)(n,r);else if("macro"in r)(0,Yr.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,Yr.funcKeywordCode)(n,r)}var y$=/^\/(?:[^~]|~0|~1)*$/,_$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Su(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!y$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=j.default.rootData}else{let u=_$.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(c("property/index",l));return i[t-l]}if(l>t)throw Error(c("data",l));if(s=r[t-l],!n)return s}let o=s,a=n.split("/");for(let u of a)if(u)s=S._`${s}${(0,S.getProperty)((0,ot.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}vt.getData=Su});var Xr=b(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});class xu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Io.default=xu});var dr=b(function(xo){Object.defineProperty(xo,"__esModule",{value:!0});var So=Jr();class Ru extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,So.resolveUrl)(e,t,r),this.missingSchema=(0,So.normalizeId)((0,So.getFullPath)(e,this.missingRef))}}xo.default=Ru});var ei=b(function(je){Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Le=F(),P$=Xr(),Ot=Re(),qe=Jr(),Cu=D(),b$=cr();class Zr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,qe.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}je.SchemaEnv=Zr;function Co(e){let t=ju.call(this,e);if(t)return t;let r=(0,qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Le.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:P$.default,code:Le._`require("ajv/dist/runtime/validation_error").default`});let c=o.scopeName("validate");e.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Ot.default.data,parentData:Ot.default.parentData,parentDataProperty:Ot.default.parentDataProperty,dataNames:[Ot.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Le._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,b$.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();if(l=`${o.scopeRefs(Ot.default.scope)}return ${d}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Ot.default.self}`,`${Ot.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:c,validateCode:d,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Le.Name?void 0:m,items:h instanceof Le.Name?void 0:h,dynamicProps:m instanceof Le.Name,dynamicItems:h instanceof Le.Name},f.source)f.source.evaluated=(0,Le.stringify)(f.evaluated)}return e.validate=f,e}catch(d){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw d}finally{this._compilations.delete(e)}}je.compileSchema=Co;function v$(e,t,r){var i;r=(0,qe.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=E$.call(this,e,r);if(s===void 0){let o=(i=e.localRefs)===null||i===void 0?void 0:i[r],{schemaId:a}=this.opts;if(o)s=new Zr({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=w$.call(this,s)}je.resolveRef=v$;function w$(e){if((0,qe.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Co.call(this,e)}function ju(e){for(let t of this._compilations)if($$(t,e))return t}je.getCompilingSchema=ju;function $$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function E$(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||mn.call(this,e,t)}function mn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,qe._getFullPath)(this.opts.uriResolver,r),n=(0,qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return Ro.call(this,r,e);let s=(0,qe.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=mn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Ro.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Co.call(this,o);if(s===(0,qe.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];if(u)n=(0,qe.resolveUrl)(this.opts.uriResolver,n,u);return new Zr({schema:a,schemaId:c,root:e,baseId:n})}return Ro.call(this,r,o)}je.resolveSchema=mn;var I$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ro(e,{baseId:t,schema:r,root:i}){var n;if(((n=e.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[(0,Cu.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r==="object"&&r[this.opts.schemaId];if(!I$.has(a)&&u)t=(0,qe.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cu.schemaHasRulesButRef)(r,this.RULES)){let a=(0,qe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=mn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new Zr({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Fu=b(function($A,S$){S$.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 Fo=b(function(EA,ku){var x$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tu=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 jo(e){let t="",r=0,i=0;for(i=0;i<e.length;i++){if(r=e[i].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i];break}for(i+=1;i<e.length;i++){if(r=e[i].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i]}return t}var R$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ou(e){return e.length=0,!0}function C$(e,t,r){if(e.length){let i=jo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function j$(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=C$;for(let c=0;c<e.length;c++){let u=e[c];if(u==="["||u==="]")continue;if(u===":"){if(s===!0)o=!0;if(!a(n,i,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Ou}else{n.push(u);continue}}if(n.length)if(a===Ou)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(jo(n));return r.address=i.join(""),r}function Au(e){if(F$(e,":")<2)return{host:e,isIPV6:!1};let t=j$(e);if(!t.error){let{address:r,address:i}=t;if(t.zone)r+="%"+t.zone,i+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:i}}else return{host:e,isIPV6:!1}}function F$(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function O$(e){let t=e,r=[],i=-1,n=0;while(n=t.length){if(n===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(n===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(n===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((i=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,i)),t=t.slice(i)}return r.join("")}function T$(e,t){let r=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=r(e.scheme);if(e.userinfo!==void 0)e.userinfo=r(e.userinfo);if(e.host!==void 0)e.host=r(e.host);if(e.path!==void 0)e.path=r(e.path);if(e.query!==void 0)e.query=r(e.query);if(e.fragment!==void 0)e.fragment=r(e.fragment);return e}function A$(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!Tu(r)){let i=Au(r);if(i.isIPV6===!0)r=`[${i.escapedHost}]`;else r=e.host}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}ku.exports={nonSimpleDomain:R$,recomposeAuthority:A$,normalizeComponentEncoding:T$,removeDotSegments:O$,isIPv4:Tu,isUUID:x$,normalizeIPv6:Au,stringArrayToHexStripped:jo}});var Mu=b(function(IA,qu){var{isUUID:k$}=Fo(),D$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,N$=["http","https","ws","wss","urn","urn:uuid"];function L$(e){return N$.indexOf(e)!==-1}function Oo(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function Du(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Nu(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function q$(e){return e.secure=Oo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function M$(e){if(e.port===(Oo(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function U$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(D$);if(r){let i=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let n=`${i}:${t.nid||e.nid}`,s=To(n);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function B$(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),n=`${r}:${t.nid||i}`,s=To(n);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${i||t.nid}:${a}`,t.skipEscape=!0,o}function G$(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!k$(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function V$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Lu={scheme:"http",domainHost:!0,parse:Du,serialize:Nu},K$={scheme:"https",domainHost:Lu.domainHost,parse:Du,serialize:Nu},hn={scheme:"ws",domainHost:!0,parse:q$,serialize:M$},z$={scheme:"wss",domainHost:hn.domainHost,parse:hn.parse,serialize:hn.serialize},W$={scheme:"urn",parse:U$,serialize:B$,skipNormalize:!0},H$={scheme:"urn:uuid",parse:G$,serialize:V$,skipNormalize:!0},gn={http:Lu,https:K$,ws:hn,wss:z$,urn:W$,"urn:uuid":H$};Object.setPrototypeOf(gn,null);function To(e){return e&&(gn[e]||gn[e.toLowerCase()])||void 0}qu.exports={wsIsSecure:Oo,SCHEMES:gn,isValidSchemeName:L$,getSchemeHandler:To}});var Gu=b(function(SA,_n){var{normalizeIPv6:J$,removeDotSegments:ti,recomposeAuthority:Q$,normalizeComponentEncoding:yn,isIPv4:Y$,nonSimpleDomain:X$}=Fo(),{SCHEMES:Z$,getSchemeHandler:Uu}=Mu();function eE(e,t){if(typeof e==="string")e=ze(at(e,t),t);else if(typeof e==="object")e=at(ze(e,t),t);return e}function tE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Bu(at(e,i),at(t,i),i,!0);return i.skipEscape=!0,ze(n,i)}function Bu(e,t,r,i){let n={};if(!i)e=at(ze(e,r),r),t=at(ze(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(!t.path)if(n.path=e.path,t.query!==void 0)n.query=t.query;else n.query=e.query;else{if(t.path[0]==="/")n.path=ti(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)n.path="/"+t.path;else if(!e.path)n.path=t.path;else n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;n.path=ti(n.path)}n.query=t.query}n.userinfo=e.userinfo,n.host=e.host,n.port=e.port}n.scheme=e.scheme}return n.fragment=t.fragment,n}function rE(e,t,r){if(typeof e==="string")e=unescape(e),e=ze(yn(at(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=ze(yn(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ze(yn(at(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=ze(yn(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ze(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},t),n=[],s=Uu(i.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,i);if(r.path!==void 0)if(!i.skipEscape){if(r.path=escape(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=unescape(r.path);if(i.reference!=="suffix"&&r.scheme)n.push(r.scheme,":");let o=Q$(r);if(o!==void 0){if(i.reference!=="suffix")n.push("//");if(n.push(o),r.path&&r.path[0]!=="/")n.push("/")}if(r.path!==void 0){let a=r.path;if(!i.absolutePath&&(!s||!s.absolutePath))a=ti(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);n.push(a)}if(r.query!==void 0)n.push("?",r.query);if(r.fragment!==void 0)n.push("#",r.fragment);return n.join("")}var iE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function at(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(iE);if(s){if(i.scheme=s[1],i.userinfo=s[3],i.host=s[4],i.port=parseInt(s[5],10),i.path=s[6]||"",i.query=s[7],i.fragment=s[8],isNaN(i.port))i.port=s[5];if(i.host)if(Y$(i.host)===!1){let c=J$(i.host);i.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;if(i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path)i.reference="same-document";else if(i.scheme===void 0)i.reference="relative";else if(i.fragment===void 0)i.reference="absolute";else i.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==i.reference)i.error=i.error||"URI is not a "+r.reference+" reference.";let o=Uu(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&X$(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(a){i.error=i.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(i.scheme!==void 0)i.scheme=unescape(i.scheme);if(i.host!==void 0)i.host=unescape(i.host)}if(i.path)i.path=escape(unescape(i.path));if(i.fragment)i.fragment=encodeURI(decodeURIComponent(i.fragment))}if(o&&o.parse)o.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}var Ao={SCHEMES:Z$,normalize:eE,resolve:tE,resolveComponent:Bu,equal:rE,serialize:ze,parse:at};_n.exports=Ao;_n.exports.default=Ao;_n.exports.fastUri=Ao});var Ku=b(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});var Vu=Gu();Vu.code='require("ajv/dist/runtime/uri").default';ko.default=Vu});var Lo=b(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var nE=cr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return nE.KeywordCxt}});var ur=F();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var sE=Xr(),Qu=dr(),oE=uo(),ri=ei(),aE=F(),ii=Jr(),Pn=Hr(),No=D(),zu=Fu(),lE=Ku(),Yu=(e,t)=>new RegExp(e,t);Yu.code="new RegExp";var cE=["removeAdditional","useDefaults","coerceTypes"],dE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),uE={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."},pE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wu=200;function fE(e){var t,r,i,n,s,o,a,c,u,l,d,p,f,m,h,g,y,P,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,X=J===!0||J===void 0?1:J||0,Se=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:Yu,qr=(n=e.uriResolver)!==null&&n!==void 0?n:lE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:V)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:V)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:X,regExp:Se}:{optimize:X,regExp:Se},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Wu,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Wu,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(P=e.messages)!==null&&P!==void 0?P:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(x=e.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(R=e.int32range)!==null&&R!==void 0?R:!0,uriResolver:qr}}class bn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...fE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new aE.ValueScope({scope:{},prefixes:dE,es5:t,lines:r}),this.logger=PE(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,oE.getRules)(),Hu.call(this,uE,e,"NOT SUPPORTED"),Hu.call(this,pE,e,"DEPRECATED","warn"),this._metaOpts=yE.call(this),e.formats)hE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)gE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);mE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=zu;if(r==="id")i={...zu},i.id=i.$id,delete i.$id;if(t&&e)this.addMetaSchema(i,i[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);if(!("$async"in r))this.errors=r.errors;return i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(u,l){await n.call(this,u.$schema);let d=this._addSchema(u,l);return d.validate||s.call(this,d)}async function n(u){if(u&&!this.getSchema(u))await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(l){if(!(l instanceof Qu.default))throw l;return o.call(this,l),await a.call(this,l.missingSchema),s.call(this,u)}}function o({missingSchema:u,missingRef:l}){if(this.refs[u])throw Error(`AnySchema ${u} is loaded but ${l} cannot be resolved`)}async function a(u){let l=await c.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function c(u){let l=this._loading[u];if(l)return l;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let n;if(typeof e==="object"){let{schemaId:s}=this.opts;if(n=e[s],n!==void 0&&typeof n!="string")throw Error(`schema ${s} must be string`)}return t=(0,ii.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw 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 i=this.validate(r,e);if(!i&&t){let n="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(n);else throw Error(n)}return i}getSchema(e){let t;while(typeof(t=Ju.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ri.SchemaEnv({schema:{},schemaId:r});if(t=ri.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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 t=Ju.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=(0,ii.normalizeId)(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(vE.call(this,r,t),!t)return(0,No.eachItem)(r,(n)=>Do.call(this,n)),this;$E.call(this,t);let i={...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)};return(0,No.eachItem)(r,i.type.length===0?(n)=>Do.call(this,n,i):(n)=>i.type.forEach((s)=>Do.call(this,n,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex((n)=>n.keyword===e);if(i>=0)r.rules.splice(i,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((i)=>`${r}${i.instancePath} ${i.message}`).reduce((i,n)=>i+t+n)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let n=i.split("/").slice(1),s=e;for(let o of n)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:c}=a.definition,u=s[o];if(c&&u)s[o]=Xu(u)}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];if(!t||t.test(r)){if(typeof i=="string")delete e[r];else if(i&&!i.meta)this._cache.delete(i.schema),delete e[r]}}}_addSchema(e,t,r,i=this.opts.validateSchema,n=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=(0,ii.normalizeId)(s||r);let c=ii.getSchemaRefs.call(this,e,r);if(a=new ri.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),n&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(i)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else ri.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{ri.compileSchema.call(this,e)}finally{this.opts=t}}}bn.ValidationError=sE.default;bn.MissingRefError=Qu.default;ie.default=bn;function Hu(e,t,r,i="error"){for(let n in e){let s=n;if(s in t)this.logger[i](`${r}: option ${n}. ${e[s]}`)}}function Ju(e){return e=(0,ii.normalizeId)(e),this.schemas[e]||this.refs[e]}function mE(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function hE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function gE(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function yE(){let e={...this.opts};for(let t of cE)delete e[t];return e}var _E={log(){},warn(){},error(){}};function PE(e){if(e===!1)return _E;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var bE=/^[a-z_$][a-z0-9_$:-]*$/i;function vE(e,t){let{RULES:r}=this;if((0,No.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!bE.test(i))throw Error(`Keyword ${i} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function Do(e,t,r){var i;let n=t===null||t===void 0?void 0:t.post;if(r&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:c})=>c===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)}};if(t.before)wE.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((c)=>this.addKeyword(c))}function wE(e,t,r){let i=e.rules.findIndex((n)=>n.keyword===r);if(i>=0)e.rules.splice(i,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function $E(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Xu(t);e.validateSchema=this.compile(t,!0)}var EE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xu(e){return{anyOf:[e,EE]}}});var Zu=b(function(qo){Object.defineProperty(qo,"__esModule",{value:!0});var IE={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qo.default=IE});var $n=b(function(Tt){Object.defineProperty(Tt,"__esModule",{value:!0});Tt.callRef=Tt.getValidate=void 0;var SE=dr(),ep=Ce(),be=F(),pr=Re(),tp=ei(),vn=D(),xE={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:c}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=tp.resolveRef.call(c,u,n,r);if(l===void 0)throw new SE.default(i.opts.uriResolver,n,r);if(l instanceof tp.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return wn(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return wn(e,be._`${m}.validate`,u,u.$async)}function p(m){let h=rp(e,m);wn(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,be.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:be.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function rp(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):be._`${r.scopeValue("wrapper",{ref:t})}.validate`}Tt.getValidate=rp;function wn(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,u=c.passContext?pr.default.this:be.nil;if(i)l();else d();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(be._`await ${(0,ep.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(be._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function d(){e.result((0,ep.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=be._`${m}.errors`;n.assign(pr.default.vErrors,be._`${pr.default.vErrors} === null ? ${h} : ${pr.default.vErrors}.concat(${h})`),n.assign(pr.default.errors,be._`${pr.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=vn.mergeEvaluated.props(n,g.props,s.props)}else{let y=n.var("props",be._`${m}.evaluated.props`);s.props=vn.mergeEvaluated.props(n,y,s.props,be.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=vn.mergeEvaluated.items(n,g.items,s.items)}else{let y=n.var("items",be._`${m}.evaluated.items`);s.items=vn.mergeEvaluated.items(n,y,s.items,be.Name)}}}Tt.callRef=wn;Tt.default=xE});var Uo=b(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});var RE=Zu(),CE=$n(),jE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",RE.default,CE.default];Mo.default=jE});var ip=b(function(Bo){Object.defineProperty(Bo,"__esModule",{value:!0});var En=F(),wt=En.operators,In={maximum:{okStr:"<=",ok:wt.LTE,fail:wt.GT},minimum:{okStr:">=",ok:wt.GTE,fail:wt.LT},exclusiveMaximum:{okStr:"<",ok:wt.LT,fail:wt.GTE},exclusiveMinimum:{okStr:">",ok:wt.GT,fail:wt.LTE}},FE={message:({keyword:e,schemaCode:t})=>En.str`must be ${In[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>En._`{comparison: ${In[e].okStr}, limit: ${t}}`},OE={keyword:Object.keys(In),type:"number",schemaType:"number",$data:!0,error:FE,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(En._`${r} ${In[t].fail} ${i} || isNaN(${r})`)}};Bo.default=OE});var np=b(function(Go){Object.defineProperty(Go,"__esModule",{value:!0});var ni=F(),TE={message:({schemaCode:e})=>ni.str`must be multiple of ${e}`,params:({schemaCode:e})=>ni._`{multipleOf: ${e}}`},AE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:TE,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?ni._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:ni._`${o} !== parseInt(${o})`;e.fail$data(ni._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Go.default=AE});var op=b(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});function sp(e){let t=e.length,r=0,i=0,n;while(i<t)if(r++,n=e.charCodeAt(i++),n>=55296&&n<=56319&&i<t){if(n=e.charCodeAt(i),(n&64512)===56320)i++}return r}Vo.default=sp;sp.code='require("ajv/dist/runtime/ucs2length").default'});var ap=b(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});var At=F(),kE=D(),DE=op(),NE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return At.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>At._`{limit: ${e}}`},LE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:NE,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?At.operators.GT:At.operators.LT,o=n.opts.unicode===!1?At._`${r}.length`:At._`${(0,kE.useFunc)(e.gen,DE.default)}(${r})`;e.fail$data(At._`${o} ${s} ${i}`)}};Ko.default=LE});var lp=b(function(zo){Object.defineProperty(zo,"__esModule",{value:!0});var qE=Ce(),Sn=F(),ME={message:({schemaCode:e})=>Sn.str`must match pattern "${e}"`,params:({schemaCode:e})=>Sn._`{pattern: ${e}}`},UE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ME,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?Sn._`(new RegExp(${n}, ${o}))`:(0,qE.usePattern)(e,i);e.fail$data(Sn._`!${a}.test(${t})`)}};zo.default=UE});var cp=b(function(Wo){Object.defineProperty(Wo,"__esModule",{value:!0});var si=F(),BE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return si.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>si._`{limit: ${e}}`},GE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:BE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?si.operators.GT:si.operators.LT;e.fail$data(si._`Object.keys(${r}).length ${n} ${i}`)}};Wo.default=GE});var dp=b(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var oi=Ce(),ai=F(),VE=D(),KE={message:({params:{missingProperty:e}})=>ai.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>ai._`{missingProperty: ${e}}`},zE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:KE,code(e){let{gen:t,schema:r,schemaCode:i,data:n,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors)u();else l();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,VE.checkStrictMode)(o,y,o.opts.strictRequired)}}function u(){if(c||s)e.block$data(ai.nil,d);else for(let f of r)(0,oi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(c||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,oi.checkMissingProp)(e,r,f)),(0,oi.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,oi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,oi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,ai.not)(m),()=>{e.error(),t.break()})},ai.nil)}}};Ho.default=zE});var up=b(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var li=F(),WE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return li.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>li._`{limit: ${e}}`},HE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:WE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?li.operators.GT:li.operators.LT;e.fail$data(li._`${r}.length ${n} ${i}`)}};Jo.default=HE});var xn=b(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});var pp=Po();pp.code='require("ajv/dist/runtime/equal").default';Qo.default=pp});var fp=b(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var Yo=Hr(),ne=F(),JE=D(),QE=xn(),YE={message:({params:{i:e,j:t}})=>ne.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>ne._`{i: ${e}, j: ${t}}`},XE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:YE,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let c=t.let("valid"),u=s.items?(0,Yo.getSchemaTypes)(s.items):[];e.block$data(c,l,ne._`${o} === false`),e.ok(c);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if(ne._`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),y=(0,Yo.checkDataTypes)(u,g,a.opts.strictNumbers,Yo.DataType.Wrong),P=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(y,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${P}[${g}] == "number"`,()=>{t.assign(h,ne._`${P}[${g}]`),e.error(),t.assign(c,!1).break()}).code(ne._`${P}[${g}] = ${m}`)})}function f(m,h){let g=(0,JE.useFunc)(t,QE.default),y=t.name("outer");t.label(y).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};Xo.default=XE});var mp=b(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Zo=F(),ZE=D(),eI=xn(),tI={message:"must be equal to constant",params:({schemaCode:e})=>Zo._`{allowedValue: ${e}}`},rI={keyword:"const",$data:!0,error:tI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(Zo._`!${(0,ZE.useFunc)(t,eI.default)}(${r}, ${n})`);else e.fail(Zo._`${s} !== ${r}`)}};ea.default=rI});var hp=b(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var ci=F(),iI=D(),nI=xn(),sI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>ci._`{allowedValues: ${e}}`},oI={keyword:"enum",schemaType:"array",$data:!0,error:sI,code(e){let{gen:t,data:r,$data:i,schema:n,schemaCode:s,it:o}=e;if(!i&&n.length===0)throw Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,c,u=()=>c!==null&&c!==void 0?c:c=(0,iI.useFunc)(t,nI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,ci.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(ci._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?ci._`${u()}(${r}, ${f}[${m}])`:ci._`${r} === ${h}`}}};ta.default=oI});var ia=b(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var aI=ip(),lI=np(),cI=ap(),dI=lp(),uI=cp(),pI=dp(),fI=up(),mI=fp(),hI=mp(),gI=hp(),yI=[aI.default,lI.default,cI.default,dI.default,uI.default,pI.default,fI.default,mI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},hI.default,gI.default];ra.default=yI});var sa=b(function(di){Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var kt=F(),na=D(),_I={message:({params:{len:e}})=>kt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>kt._`{limit: ${e}}`},PI={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_I,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,na.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gp(e,i)}};function gp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",kt._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(kt._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,na.alwaysValidSchema)(o,i)){let u=r.var("valid",kt._`${a} <= ${t.length}`);r.if((0,kt.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:na.Type.Num},u),!o.allErrors)r.if((0,kt.not)(u),()=>r.break())})}}di.validateAdditionalItems=gp;di.default=PI});var oa=b(function(ui){Object.defineProperty(ui,"__esModule",{value:!0});ui.validateTuple=void 0;var yp=F(),Rn=D(),bI=Ce(),vI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _p(e,"additionalItems",t);if(r.items=!0,(0,Rn.alwaysValidSchema)(r,t))return;e.ok((0,bI.validateArray)(e))}};function _p(e,t,r=e.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=e;if(l(n),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Rn.mergeEvaluated.items(i,r.length,a.items);let c=i.name("valid"),u=i.const("len",yp._`${s}.length`);r.forEach((d,p)=>{if((0,Rn.alwaysValidSchema)(a,d))return;i.if(yp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},c)),e.ok(c)});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Rn.checkStrictMode)(a,g,p.strictTuples)}}}ui.validateTuple=_p;ui.default=vI});var Pp=b(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var wI=oa(),$I={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,wI.validateTuple)(e,"items")};aa.default=$I});var vp=b(function(la){Object.defineProperty(la,"__esModule",{value:!0});var bp=F(),EI=D(),II=Ce(),SI=sa(),xI={message:({params:{len:e}})=>bp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>bp._`{limit: ${e}}`},RI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xI,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,EI.alwaysValidSchema)(i,t))return;if(n)(0,SI.validateAdditionalItems)(e,n);else e.ok((0,II.validateArray)(e))}};la.default=RI});var wp=b(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var Fe=F(),Cn=D(),CI={message:({params:{min:e,max:t}})=>t===void 0?Fe.str`must contain at least ${e} valid item(s)`:Fe.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Fe._`{minContains: ${e}}`:Fe._`{minContains: ${e}, maxContains: ${t}}`},jI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:CI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:c,maxContains:u}=i;if(s.opts.next)o=c===void 0?1:c,a=u;else o=1;let l=t.const("len",Fe._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Cn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Cn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Cn.alwaysValidSchema)(s,r)){let h=Fe._`${l} >= ${o}`;if(a!==void 0)h=Fe._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let d=t.name("valid");if(a===void 0&&o===1)f(d,()=>t.if(d,()=>t.break()));else if(o===0){if(t.let(d,!0),a!==void 0)t.if(Fe._`${n}.length > 0`,p)}else t.let(d,!1),p();e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,l,(y)=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Cn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Fe._`${h}++`),a===void 0)t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0).break());else if(t.if(Fe._`${h} > ${a}`,()=>t.assign(d,!1).break()),o===1)t.assign(d,!0);else t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0))}}};ca.default=jI});var jn=b(function(We){Object.defineProperty(We,"__esModule",{value:!0});We.validateSchemaDeps=We.validatePropertyDeps=We.error=void 0;var da=F(),FI=D(),pi=Ce();We.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return da.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>da._`{property: ${e},
7
+ || ${o} === "boolean" || ${n} === null`).assign(a,O._`[${n}]`)}}}function fw({gen:e,parentData:t,parentDataProperty:r},i){e.if(O._`${t} !== undefined`,()=>e.assign(O._`${t}[${r}]`,i))}function fo(e,t,r,i=or.Correct){let n=i===or.Correct?O.operators.EQ:O.operators.NEQ,s;switch(e){case"null":return O._`${t} ${n} null`;case"array":s=O._`Array.isArray(${t})`;break;case"object":s=O._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(O._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return O._`typeof ${t} ${n} ${e}`}return i===or.Correct?s:(0,O.not)(s);function o(a=O.nil){return(0,O.and)(O._`typeof ${t} == "number"`,a,r?O._`isFinite(${t})`:O.nil)}}ce.checkDataType=fo;function mo(e,t,r,i){if(e.length===1)return fo(e[0],t,r,i);let n,s=(0,Jd.toHash)(e);if(s.array&&s.object){let o=O._`typeof ${t} != "object"`;n=s.null?o:O._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=O.nil;if(s.number)delete s.integer;for(let o in s)n=(0,O.and)(n,fo(o,t,r,i));return n}ce.checkDataTypes=mo;var mw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?O._`{type: ${e}}`:O._`{type: ${t}}`};function ho(e){let t=hw(e);(0,lw.reportError)(t,mw)}ce.reportTypeError=ho;function hw(e){let{gen:t,data:r,schema:i}=e,n=(0,Jd.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var Zd=b(function(un){Object.defineProperty(un,"__esModule",{value:!0});un.assignDefaults=void 0;var ar=F(),gw=D();function yw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)Xd(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>Xd(e,s,n.default))}un.assignDefaults=yw;function Xd(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=ar._`${s}${(0,ar.getProperty)(t)}`;if(n){(0,gw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=ar._`${a} === undefined`;if(o.useDefaults==="empty")c=ar._`${c} || ${a} === null || ${a} === ""`;i.if(c,ar._`${a} = ${(0,ar.stringify)(r)}`)}});var Ce=b(function(B){Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var K=F(),go=D(),Pt=Re(),_w=D();function Pw(e,t){let{gen:r,data:i,it:n}=e;r.if(_o(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=Pw;function bw({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(_o(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=bw;function vw(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=vw;function eu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=eu;function yo(e,t,r){return K._`${eu(e)}.call(${t}, ${r})`}B.isOwnProperty=yo;function ww(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${yo(e,t,r)}`:n}B.propertyInData=ww;function _o(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(yo(e,t,r))):n}B.noPropertyInData=_o;function tu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=tu;function $w(e,t){return tu(t).filter((r)=>!(0,go.alwaysValidSchema)(e,t[r]))}B.schemaProperties=$w;function Ew({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,c,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,d=[[Pt.default.instancePath,(0,K.strConcat)(Pt.default.instancePath,s)],[Pt.default.parentData,o.parentData],[Pt.default.parentDataProperty,o.parentDataProperty],[Pt.default.rootData,Pt.default.rootData]];if(o.opts.dynamicRef)d.push([Pt.default.dynamicAnchors,Pt.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...d)}`;return c!==K.nil?K._`${a}.call(${c}, ${p})`:K._`${a}(${p})`}B.callValidateCode=Ew;var Iw=K._`new RegExp`;function Sw({gen:e,it:{opts:t}},r){let i=t.unicodeRegExp?"u":"",{regExp:n}=t.code,s=n(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${n.code==="new RegExp"?Iw:(0,_w.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=Sw;function xw(e){let{gen:t,data:r,keyword:i,it:n}=e,s=t.name("valid");if(n.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",K._`${r}.length`);t.forRange("i",0,c,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:go.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=xw;function Rw(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>(0,go.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:i,schemaProp:u,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(l,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=Rw});var nu=b(function(Ve){Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateKeywordUsage=Ve.validSchemaType=Ve.funcKeywordCode=Ve.macroKeywordCode=void 0;var pe=F(),Ft=Re(),Cw=Ce(),jw=Wr();function Fw(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),c=iu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:pe.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ve.macroKeywordCode=Fw;function Ow(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:c}=e;Aw(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,l=iu(i,n,u),d=i.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1){if(h(),t.modifying)ru(e);g(()=>e.error())}else{let y=t.async?f():m();if(t.modifying)ru(e);g(()=>Tw(e,y))}}function f(){let y=i.let("ruleErrs",null);return i.try(()=>h(pe._`await `),(P)=>i.assign(d,!1).if(pe._`${P} instanceof ${c.ValidationError}`,()=>i.assign(y,pe._`${P}.errors`),()=>i.throw(P))),y}function m(){let y=pe._`${l}.errors`;return i.assign(y,null),h(pe.nil),y}function h(y=t.async?pe._`await `:pe.nil){let P=c.opts.passContext?Ft.default.this:Ft.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(d,pe._`${y}${(0,Cw.callValidateCode)(e,l,P,v)}`,t.modifying)}function g(y){var P;i.if((0,pe.not)((P=t.valid)!==null&&P!==void 0?P:d),y)}}Ve.funcKeywordCode=Ow;function ru(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,pe._`${i.parentData}[${i.parentDataProperty}]`))}function Tw(e,t){let{gen:r}=e;r.if(pe._`Array.isArray(${t})`,()=>{r.assign(Ft.default.vErrors,pe._`${Ft.default.vErrors} === null ? ${t} : ${Ft.default.vErrors}.concat(${t})`).assign(Ft.default.errors,pe._`${Ft.default.vErrors}.length`),(0,jw.extendErrors)(e)},()=>e.error())}function Aw({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function iu(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,pe.stringify)(r)})}function kw(e,t,r=!1){return!t.length||t.some((i)=>i==="array"?Array.isArray(e):i==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==i||r&&typeof e>"u")}Ve.validSchemaType=kw;function Dw({schema:e,opts:t,self:r,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw Error("ajv implementation error");let o=n.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}Ve.validateKeywordUsage=Dw});var ou=b(function(bt){Object.defineProperty(bt,"__esModule",{value:!0});bt.extendSubschemaMode=bt.extendSubschemaData=bt.getSubschema=void 0;var Ke=F(),su=D();function Nw(e,{keyword:t,schemaProp:r,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&i!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}${(0,Ke.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,su.escapeFragment)(r)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}bt.getSubschema=Nw;function Lw(e,t,{dataProp:r,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",Ke._`${t.data}${(0,Ke.getProperty)(r)}`,!0);c(p),e.errorPath=Ke.str`${u}${(0,su.getErrorPath)(r,i,d.jsPropertySyntax)}`,e.parentDataProperty=Ke._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Ke.Name?n:a.let("data",n,!0);if(c(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}bt.extendSubschemaData=Lw;function qw(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:n,allErrors:s}){if(i!==void 0)e.compositeRule=i;if(n!==void 0)e.createErrors=n;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}bt.extendSubschemaMode=qw});var Po=b(function(yA,au){au.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if(i=t.length,i!=r.length)return!1;for(n=i;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),i=s.length,i!==Object.keys(r).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var cu=b(function(_A,lu){var vt=lu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var i=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};pn(t,i,n,e,"",e)};vt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function pn(e,t,r,i,n,s,o,a,c,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,c,u);for(var l in i){var d=i[l];if(Array.isArray(d)){if(l in vt.arrayKeywords)for(var p=0;p<d.length;p++)pn(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in vt.propsKeywords){if(d&&typeof d=="object")for(var f in d)pn(e,t,r,d[f],n+"/"+l+"/"+Mw(f),s,n,l,i,f)}else if(l in vt.keywords||e.allKeys&&!(l in vt.skipKeywords))pn(e,t,r,d,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,c,u)}}function Mw(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Jr=b(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getSchemaRefs=Pe.resolveUrl=Pe.normalizeId=Pe._getFullPath=Pe.getFullPath=Pe.inlineRef=void 0;var Uw=D(),Bw=Po(),Gw=cu(),Vw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Kw(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!bo(e);if(!t)return!1;return du(e)<=t}Pe.inlineRef=Kw;var zw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bo(e){for(let t in e){if(zw.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(bo))return!0;if(typeof r=="object"&&bo(r))return!0}return!1}function du(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,Vw.has(r))continue;if(typeof e[r]=="object")(0,Uw.eachItem)(e[r],(i)=>t+=du(i));if(t===1/0)return 1/0}return t}function uu(e,t="",r){if(r!==!1)t=lr(t);let i=e.parse(t);return pu(e,i)}Pe.getFullPath=uu;function pu(e,t){return e.serialize(t).split("#")[0]+"#"}Pe._getFullPath=pu;var Ww=/#\/?$/;function lr(e){return e?e.replace(Ww,""):""}Pe.normalizeId=lr;function Hw(e,t,r){return r=lr(r),e.resolve(t,r)}Pe.resolveUrl=Hw;var Jw=/^[a-z_][-a-z0-9._]*$/i;function Qw(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=lr(e[r]||t),s={"":n},o=uu(i,n,!1),a={},c=new Set;return Gw(e,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof d[r]=="string")g=y.call(this,d[r]);P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[p]=g;function y(v){let w=this.opts.uriResolver.resolve;if(v=lr(g?w(g,v):v),c.has(v))throw l(v);c.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(d,I.schema,v);else if(v!==lr(h))if(v[0]==="#")u(d,a[v],v),a[v]=d;else this.refs[v]=h;return v}function P(v){if(typeof v=="string"){if(!Jw.test(v))throw Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Bw(d,p))throw l(f)}function l(d){return Error(`reference "${d}" resolves to more than one schema`)}}Pe.getSchemaRefs=Qw});var cr=b(function(wt){Object.defineProperty(wt,"__esModule",{value:!0});wt.getData=wt.KeywordCxt=wt.validateFunctionCode=void 0;var yu=zd(),fu=Hr(),wo=po(),fn=Hr(),Yw=Zd(),Yr=nu(),vo=ou(),S=F(),j=Re(),Xw=Jr(),st=D(),Qr=Wr();function Zw(e){if(bu(e)){if(vu(e),Pu(e)){r$(e);return}}_u(e,()=>(0,yu.topBoolOrEmptySchema)(e))}wt.validateFunctionCode=Zw;function _u({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${j.default.data}, ${j.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${mu(r,n)}`),t$(e,n),e.code(s)});else e.func(t,S._`${j.default.data}, ${e$(n)}`,i.$async,()=>e.code(mu(r,n)).code(s))}function e$(e){return S._`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?S._`, ${j.default.dynamicAnchors}={}`:S.nil}}={}`}function t$(e,t){e.if(j.default.valCxt,()=>{if(e.var(j.default.instancePath,S._`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,S._`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,S._`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,S._`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{if(e.var(j.default.instancePath,S._`""`),e.var(j.default.parentData,S._`undefined`),e.var(j.default.parentDataProperty,S._`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`{}`)})}function r$(e){let{schema:t,opts:r,gen:i}=e;_u(e,()=>{if(r.$comment&&t.$comment)$u(e);if(a$(e),i.let(j.default.vErrors,null),i.let(j.default.errors,0),r.unevaluated)i$(e);wu(e),d$(e)});return}function i$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",S._`${r}.evaluated`),t.if(S._`${e.evaluated}.dynamicProps`,()=>t.assign(S._`${e.evaluated}.props`,S._`undefined`)),t.if(S._`${e.evaluated}.dynamicItems`,()=>t.assign(S._`${e.evaluated}.items`,S._`undefined`))}function mu(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function n$(e,t){if(bu(e)){if(vu(e),Pu(e)){s$(e,t);return}}(0,yu.boolOrEmptySchema)(e,t)}function Pu({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function bu(e){return typeof e.schema!="boolean"}function s$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)$u(e);l$(e),c$(e);let s=i.const("_errs",j.default.errors);wu(e,s),i.var(t,S._`${s} === ${j.default.errors}`)}function vu(e){(0,st.checkUnknownRules)(e),o$(e)}function wu(e,t){if(e.opts.jtd)return hu(e,[],!1,t);let r=(0,fu.getSchemaTypes)(e.schema),i=(0,fu.coerceAndCheckDataType)(e,r);hu(e,r,!i,t)}function o$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,st.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function a$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,st.checkStrictMode)(e,"default is ignored in the schema root")}function l$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,Xw.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function c$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function $u({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${j.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=S.str`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${j.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function d$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw(S._`new ${n}(${j.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,j.default.vErrors),s.unevaluated)u$(e);t.return(S._`${j.default.errors} === 0`)}}function u$({gen:e,evaluated:t,props:r,items:i}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(i instanceof S.Name)e.assign(S._`${t}.items`,i)}function hu(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,st.schemaHasRulesButRef)(s,l))){n.block(()=>Iu(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)p$(e,t);n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){if(!(0,wo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,fn.checkDataType)(p.type,o,c.strictNumbers)),gu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,fn.reportTypeError)(e);n.endIf()}else gu(e,p);if(!a)n.if(S._`${j.default.errors} === ${i||0}`)}}function gu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,Yw.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,wo.shouldUseRule)(i,s))Iu(e,s.keyword,s.definition,t.type)})}function p$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(f$(e,t),!e.opts.allowUnionTypes)m$(e,t);h$(e,e.dataTypes)}function f$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Eu(e.dataTypes,r))$o(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),y$(e,t)}function m$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))$o(e,"use allowUnionTypes to allow union type keyword")}function h$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,wo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>g$(t,o)))$o(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function g$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Eu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y$(e,t){let r=[];for(let i of e.dataTypes)if(Eu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function $o(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,st.checkStrictMode)(e,t,e.opts.strictTypes)}class Eo{constructor(e,t,r){if((0,Yr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,st.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Su(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Yr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",j.default.errors)}result(e,t,r){this.failResult((0,S.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,S.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(S._`${t} !== undefined && (${(0,S.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?Qr.reportExtraError:Qr.reportError)(this,this.def.error,t)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Qr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=S.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=S.nil,t=S.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:n,def:s}=this;if(r.if((0,S.or)(S._`${i} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(n.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:n}=this;return(0,S.or)(s(),o());function s(){if(r.length){if(!(t instanceof S.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return S._`${(0,fn.checkDataTypes)(a,t,n.opts.strictNumbers,fn.DataType.Wrong)}`}return S.nil}function o(){if(i.validateSchema){let a=e.scopeValue("validate$data",{ref:i.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,vo.getSubschema)(this.it,e);(0,vo.extendSubschemaData)(r,this.it,e),(0,vo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return n$(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=st.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=st.mergeEvaluated.items(i,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}wt.KeywordCxt=Eo;function Iu(e,t,r,i){let n=new Eo(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,Yr.funcKeywordCode)(n,r);else if("macro"in r)(0,Yr.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,Yr.funcKeywordCode)(n,r)}var _$=/^\/(?:[^~]|~0|~1)*$/,P$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Su(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!_$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=j.default.rootData}else{let u=P$.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(c("property/index",l));return i[t-l]}if(l>t)throw Error(c("data",l));if(s=r[t-l],!n)return s}let o=s,a=n.split("/");for(let u of a)if(u)s=S._`${s}${(0,S.getProperty)((0,st.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}wt.getData=Su});var Xr=b(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});class xu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Io.default=xu});var dr=b(function(xo){Object.defineProperty(xo,"__esModule",{value:!0});var So=Jr();class Ru extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,So.resolveUrl)(e,t,r),this.missingSchema=(0,So.normalizeId)((0,So.getFullPath)(e,this.missingRef))}}xo.default=Ru});var ei=b(function(je){Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Le=F(),b$=Xr(),Ot=Re(),qe=Jr(),Cu=D(),v$=cr();class Zr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,qe.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}je.SchemaEnv=Zr;function Co(e){let t=ju.call(this,e);if(t)return t;let r=(0,qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Le.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:b$.default,code:Le._`require("ajv/dist/runtime/validation_error").default`});let c=o.scopeName("validate");e.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Ot.default.data,parentData:Ot.default.parentData,parentDataProperty:Ot.default.parentDataProperty,dataNames:[Ot.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Le._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,v$.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();if(l=`${o.scopeRefs(Ot.default.scope)}return ${d}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Ot.default.self}`,`${Ot.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:c,validateCode:d,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Le.Name?void 0:m,items:h instanceof Le.Name?void 0:h,dynamicProps:m instanceof Le.Name,dynamicItems:h instanceof Le.Name},f.source)f.source.evaluated=(0,Le.stringify)(f.evaluated)}return e.validate=f,e}catch(d){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw d}finally{this._compilations.delete(e)}}je.compileSchema=Co;function w$(e,t,r){var i;r=(0,qe.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=I$.call(this,e,r);if(s===void 0){let o=(i=e.localRefs)===null||i===void 0?void 0:i[r],{schemaId:a}=this.opts;if(o)s=new Zr({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=$$.call(this,s)}je.resolveRef=w$;function $$(e){if((0,qe.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Co.call(this,e)}function ju(e){for(let t of this._compilations)if(E$(t,e))return t}je.getCompilingSchema=ju;function E$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function I$(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||mn.call(this,e,t)}function mn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,qe._getFullPath)(this.opts.uriResolver,r),n=(0,qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return Ro.call(this,r,e);let s=(0,qe.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=mn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Ro.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Co.call(this,o);if(s===(0,qe.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];if(u)n=(0,qe.resolveUrl)(this.opts.uriResolver,n,u);return new Zr({schema:a,schemaId:c,root:e,baseId:n})}return Ro.call(this,r,o)}je.resolveSchema=mn;var S$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ro(e,{baseId:t,schema:r,root:i}){var n;if(((n=e.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[(0,Cu.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r==="object"&&r[this.opts.schemaId];if(!S$.has(a)&&u)t=(0,qe.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cu.schemaHasRulesButRef)(r,this.RULES)){let a=(0,qe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=mn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new Zr({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Fu=b(function(EA,x$){x$.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 Fo=b(function(IA,ku){var R$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tu=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 jo(e){let t="",r=0,i=0;for(i=0;i<e.length;i++){if(r=e[i].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i];break}for(i+=1;i<e.length;i++){if(r=e[i].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i]}return t}var C$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ou(e){return e.length=0,!0}function j$(e,t,r){if(e.length){let i=jo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function F$(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=j$;for(let c=0;c<e.length;c++){let u=e[c];if(u==="["||u==="]")continue;if(u===":"){if(s===!0)o=!0;if(!a(n,i,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Ou}else{n.push(u);continue}}if(n.length)if(a===Ou)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(jo(n));return r.address=i.join(""),r}function Au(e){if(O$(e,":")<2)return{host:e,isIPV6:!1};let t=F$(e);if(!t.error){let{address:r,address:i}=t;if(t.zone)r+="%"+t.zone,i+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:i}}else return{host:e,isIPV6:!1}}function O$(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function T$(e){let t=e,r=[],i=-1,n=0;while(n=t.length){if(n===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(n===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(n===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((i=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,i)),t=t.slice(i)}return r.join("")}function A$(e,t){let r=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=r(e.scheme);if(e.userinfo!==void 0)e.userinfo=r(e.userinfo);if(e.host!==void 0)e.host=r(e.host);if(e.path!==void 0)e.path=r(e.path);if(e.query!==void 0)e.query=r(e.query);if(e.fragment!==void 0)e.fragment=r(e.fragment);return e}function k$(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!Tu(r)){let i=Au(r);if(i.isIPV6===!0)r=`[${i.escapedHost}]`;else r=e.host}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}ku.exports={nonSimpleDomain:C$,recomposeAuthority:k$,normalizeComponentEncoding:A$,removeDotSegments:T$,isIPv4:Tu,isUUID:R$,normalizeIPv6:Au,stringArrayToHexStripped:jo}});var Mu=b(function(SA,qu){var{isUUID:D$}=Fo(),N$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,L$=["http","https","ws","wss","urn","urn:uuid"];function q$(e){return L$.indexOf(e)!==-1}function Oo(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function Du(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Nu(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function M$(e){return e.secure=Oo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function U$(e){if(e.port===(Oo(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function B$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(N$);if(r){let i=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let n=`${i}:${t.nid||e.nid}`,s=To(n);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function G$(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),n=`${r}:${t.nid||i}`,s=To(n);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${i||t.nid}:${a}`,t.skipEscape=!0,o}function V$(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!D$(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function K$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Lu={scheme:"http",domainHost:!0,parse:Du,serialize:Nu},z$={scheme:"https",domainHost:Lu.domainHost,parse:Du,serialize:Nu},hn={scheme:"ws",domainHost:!0,parse:M$,serialize:U$},W$={scheme:"wss",domainHost:hn.domainHost,parse:hn.parse,serialize:hn.serialize},H$={scheme:"urn",parse:B$,serialize:G$,skipNormalize:!0},J$={scheme:"urn:uuid",parse:V$,serialize:K$,skipNormalize:!0},gn={http:Lu,https:z$,ws:hn,wss:W$,urn:H$,"urn:uuid":J$};Object.setPrototypeOf(gn,null);function To(e){return e&&(gn[e]||gn[e.toLowerCase()])||void 0}qu.exports={wsIsSecure:Oo,SCHEMES:gn,isValidSchemeName:q$,getSchemeHandler:To}});var Gu=b(function(xA,_n){var{normalizeIPv6:Q$,removeDotSegments:ti,recomposeAuthority:Y$,normalizeComponentEncoding:yn,isIPv4:X$,nonSimpleDomain:Z$}=Fo(),{SCHEMES:eE,getSchemeHandler:Uu}=Mu();function tE(e,t){if(typeof e==="string")e=ze(ot(e,t),t);else if(typeof e==="object")e=ot(ze(e,t),t);return e}function rE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Bu(ot(e,i),ot(t,i),i,!0);return i.skipEscape=!0,ze(n,i)}function Bu(e,t,r,i){let n={};if(!i)e=ot(ze(e,r),r),t=ot(ze(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(!t.path)if(n.path=e.path,t.query!==void 0)n.query=t.query;else n.query=e.query;else{if(t.path[0]==="/")n.path=ti(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)n.path="/"+t.path;else if(!e.path)n.path=t.path;else n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;n.path=ti(n.path)}n.query=t.query}n.userinfo=e.userinfo,n.host=e.host,n.port=e.port}n.scheme=e.scheme}return n.fragment=t.fragment,n}function iE(e,t,r){if(typeof e==="string")e=unescape(e),e=ze(yn(ot(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=ze(yn(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ze(yn(ot(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=ze(yn(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ze(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},t),n=[],s=Uu(i.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,i);if(r.path!==void 0)if(!i.skipEscape){if(r.path=escape(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=unescape(r.path);if(i.reference!=="suffix"&&r.scheme)n.push(r.scheme,":");let o=Y$(r);if(o!==void 0){if(i.reference!=="suffix")n.push("//");if(n.push(o),r.path&&r.path[0]!=="/")n.push("/")}if(r.path!==void 0){let a=r.path;if(!i.absolutePath&&(!s||!s.absolutePath))a=ti(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);n.push(a)}if(r.query!==void 0)n.push("?",r.query);if(r.fragment!==void 0)n.push("#",r.fragment);return n.join("")}var nE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ot(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(nE);if(s){if(i.scheme=s[1],i.userinfo=s[3],i.host=s[4],i.port=parseInt(s[5],10),i.path=s[6]||"",i.query=s[7],i.fragment=s[8],isNaN(i.port))i.port=s[5];if(i.host)if(X$(i.host)===!1){let c=Q$(i.host);i.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;if(i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path)i.reference="same-document";else if(i.scheme===void 0)i.reference="relative";else if(i.fragment===void 0)i.reference="absolute";else i.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==i.reference)i.error=i.error||"URI is not a "+r.reference+" reference.";let o=Uu(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&Z$(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(a){i.error=i.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(i.scheme!==void 0)i.scheme=unescape(i.scheme);if(i.host!==void 0)i.host=unescape(i.host)}if(i.path)i.path=escape(unescape(i.path));if(i.fragment)i.fragment=encodeURI(decodeURIComponent(i.fragment))}if(o&&o.parse)o.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}var Ao={SCHEMES:eE,normalize:tE,resolve:rE,resolveComponent:Bu,equal:iE,serialize:ze,parse:ot};_n.exports=Ao;_n.exports.default=Ao;_n.exports.fastUri=Ao});var Ku=b(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});var Vu=Gu();Vu.code='require("ajv/dist/runtime/uri").default';ko.default=Vu});var Lo=b(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var sE=cr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return sE.KeywordCxt}});var ur=F();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var oE=Xr(),Qu=dr(),aE=uo(),ri=ei(),lE=F(),ii=Jr(),Pn=Hr(),No=D(),zu=Fu(),cE=Ku(),Yu=(e,t)=>new RegExp(e,t);Yu.code="new RegExp";var dE=["removeAdditional","useDefaults","coerceTypes"],uE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),pE={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."},fE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wu=200;function mE(e){var t,r,i,n,s,o,a,c,u,l,d,p,f,m,h,g,y,P,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,X=J===!0||J===void 0?1:J||0,Se=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:Yu,qr=(n=e.uriResolver)!==null&&n!==void 0?n:cE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:V)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:V)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:X,regExp:Se}:{optimize:X,regExp:Se},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Wu,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Wu,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(P=e.messages)!==null&&P!==void 0?P:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(x=e.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(R=e.int32range)!==null&&R!==void 0?R:!0,uriResolver:qr}}class bn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...mE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new lE.ValueScope({scope:{},prefixes:uE,es5:t,lines:r}),this.logger=bE(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,aE.getRules)(),Hu.call(this,pE,e,"NOT SUPPORTED"),Hu.call(this,fE,e,"DEPRECATED","warn"),this._metaOpts=_E.call(this),e.formats)gE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)yE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);hE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=zu;if(r==="id")i={...zu},i.id=i.$id,delete i.$id;if(t&&e)this.addMetaSchema(i,i[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);if(!("$async"in r))this.errors=r.errors;return i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(u,l){await n.call(this,u.$schema);let d=this._addSchema(u,l);return d.validate||s.call(this,d)}async function n(u){if(u&&!this.getSchema(u))await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(l){if(!(l instanceof Qu.default))throw l;return o.call(this,l),await a.call(this,l.missingSchema),s.call(this,u)}}function o({missingSchema:u,missingRef:l}){if(this.refs[u])throw Error(`AnySchema ${u} is loaded but ${l} cannot be resolved`)}async function a(u){let l=await c.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function c(u){let l=this._loading[u];if(l)return l;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let n;if(typeof e==="object"){let{schemaId:s}=this.opts;if(n=e[s],n!==void 0&&typeof n!="string")throw Error(`schema ${s} must be string`)}return t=(0,ii.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw 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 i=this.validate(r,e);if(!i&&t){let n="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(n);else throw Error(n)}return i}getSchema(e){let t;while(typeof(t=Ju.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ri.SchemaEnv({schema:{},schemaId:r});if(t=ri.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}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 t=Ju.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=(0,ii.normalizeId)(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(wE.call(this,r,t),!t)return(0,No.eachItem)(r,(n)=>Do.call(this,n)),this;EE.call(this,t);let i={...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)};return(0,No.eachItem)(r,i.type.length===0?(n)=>Do.call(this,n,i):(n)=>i.type.forEach((s)=>Do.call(this,n,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex((n)=>n.keyword===e);if(i>=0)r.rules.splice(i,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((i)=>`${r}${i.instancePath} ${i.message}`).reduce((i,n)=>i+t+n)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let n=i.split("/").slice(1),s=e;for(let o of n)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:c}=a.definition,u=s[o];if(c&&u)s[o]=Xu(u)}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];if(!t||t.test(r)){if(typeof i=="string")delete e[r];else if(i&&!i.meta)this._cache.delete(i.schema),delete e[r]}}}_addSchema(e,t,r,i=this.opts.validateSchema,n=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=(0,ii.normalizeId)(s||r);let c=ii.getSchemaRefs.call(this,e,r);if(a=new ri.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),n&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(i)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else ri.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{ri.compileSchema.call(this,e)}finally{this.opts=t}}}bn.ValidationError=oE.default;bn.MissingRefError=Qu.default;ie.default=bn;function Hu(e,t,r,i="error"){for(let n in e){let s=n;if(s in t)this.logger[i](`${r}: option ${n}. ${e[s]}`)}}function Ju(e){return e=(0,ii.normalizeId)(e),this.schemas[e]||this.refs[e]}function hE(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function gE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function yE(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function _E(){let e={...this.opts};for(let t of dE)delete e[t];return e}var PE={log(){},warn(){},error(){}};function bE(e){if(e===!1)return PE;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var vE=/^[a-z_$][a-z0-9_$:-]*$/i;function wE(e,t){let{RULES:r}=this;if((0,No.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!vE.test(i))throw Error(`Keyword ${i} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function Do(e,t,r){var i;let n=t===null||t===void 0?void 0:t.post;if(r&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:c})=>c===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)}};if(t.before)$E.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((c)=>this.addKeyword(c))}function $E(e,t,r){let i=e.rules.findIndex((n)=>n.keyword===r);if(i>=0)e.rules.splice(i,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function EE(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Xu(t);e.validateSchema=this.compile(t,!0)}var IE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xu(e){return{anyOf:[e,IE]}}});var Zu=b(function(qo){Object.defineProperty(qo,"__esModule",{value:!0});var SE={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qo.default=SE});var $n=b(function(Tt){Object.defineProperty(Tt,"__esModule",{value:!0});Tt.callRef=Tt.getValidate=void 0;var xE=dr(),ep=Ce(),be=F(),pr=Re(),tp=ei(),vn=D(),RE={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:c}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=tp.resolveRef.call(c,u,n,r);if(l===void 0)throw new xE.default(i.opts.uriResolver,n,r);if(l instanceof tp.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return wn(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return wn(e,be._`${m}.validate`,u,u.$async)}function p(m){let h=rp(e,m);wn(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,be.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:be.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function rp(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):be._`${r.scopeValue("wrapper",{ref:t})}.validate`}Tt.getValidate=rp;function wn(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,u=c.passContext?pr.default.this:be.nil;if(i)l();else d();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(be._`await ${(0,ep.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(be._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function d(){e.result((0,ep.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=be._`${m}.errors`;n.assign(pr.default.vErrors,be._`${pr.default.vErrors} === null ? ${h} : ${pr.default.vErrors}.concat(${h})`),n.assign(pr.default.errors,be._`${pr.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=vn.mergeEvaluated.props(n,g.props,s.props)}else{let y=n.var("props",be._`${m}.evaluated.props`);s.props=vn.mergeEvaluated.props(n,y,s.props,be.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=vn.mergeEvaluated.items(n,g.items,s.items)}else{let y=n.var("items",be._`${m}.evaluated.items`);s.items=vn.mergeEvaluated.items(n,y,s.items,be.Name)}}}Tt.callRef=wn;Tt.default=RE});var Uo=b(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});var CE=Zu(),jE=$n(),FE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CE.default,jE.default];Mo.default=FE});var ip=b(function(Bo){Object.defineProperty(Bo,"__esModule",{value:!0});var En=F(),$t=En.operators,In={maximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},minimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},exclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},exclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},OE={message:({keyword:e,schemaCode:t})=>En.str`must be ${In[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>En._`{comparison: ${In[e].okStr}, limit: ${t}}`},TE={keyword:Object.keys(In),type:"number",schemaType:"number",$data:!0,error:OE,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(En._`${r} ${In[t].fail} ${i} || isNaN(${r})`)}};Bo.default=TE});var np=b(function(Go){Object.defineProperty(Go,"__esModule",{value:!0});var ni=F(),AE={message:({schemaCode:e})=>ni.str`must be multiple of ${e}`,params:({schemaCode:e})=>ni._`{multipleOf: ${e}}`},kE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AE,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?ni._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:ni._`${o} !== parseInt(${o})`;e.fail$data(ni._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Go.default=kE});var op=b(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});function sp(e){let t=e.length,r=0,i=0,n;while(i<t)if(r++,n=e.charCodeAt(i++),n>=55296&&n<=56319&&i<t){if(n=e.charCodeAt(i),(n&64512)===56320)i++}return r}Vo.default=sp;sp.code='require("ajv/dist/runtime/ucs2length").default'});var ap=b(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});var At=F(),DE=D(),NE=op(),LE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return At.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>At._`{limit: ${e}}`},qE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LE,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?At.operators.GT:At.operators.LT,o=n.opts.unicode===!1?At._`${r}.length`:At._`${(0,DE.useFunc)(e.gen,NE.default)}(${r})`;e.fail$data(At._`${o} ${s} ${i}`)}};Ko.default=qE});var lp=b(function(zo){Object.defineProperty(zo,"__esModule",{value:!0});var ME=Ce(),Sn=F(),UE={message:({schemaCode:e})=>Sn.str`must match pattern "${e}"`,params:({schemaCode:e})=>Sn._`{pattern: ${e}}`},BE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UE,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?Sn._`(new RegExp(${n}, ${o}))`:(0,ME.usePattern)(e,i);e.fail$data(Sn._`!${a}.test(${t})`)}};zo.default=BE});var cp=b(function(Wo){Object.defineProperty(Wo,"__esModule",{value:!0});var si=F(),GE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return si.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>si._`{limit: ${e}}`},VE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?si.operators.GT:si.operators.LT;e.fail$data(si._`Object.keys(${r}).length ${n} ${i}`)}};Wo.default=VE});var dp=b(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var oi=Ce(),ai=F(),KE=D(),zE={message:({params:{missingProperty:e}})=>ai.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>ai._`{missingProperty: ${e}}`},WE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:zE,code(e){let{gen:t,schema:r,schemaCode:i,data:n,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors)u();else l();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,KE.checkStrictMode)(o,y,o.opts.strictRequired)}}function u(){if(c||s)e.block$data(ai.nil,d);else for(let f of r)(0,oi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(c||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,oi.checkMissingProp)(e,r,f)),(0,oi.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,oi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,oi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,ai.not)(m),()=>{e.error(),t.break()})},ai.nil)}}};Ho.default=WE});var up=b(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var li=F(),HE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return li.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>li._`{limit: ${e}}`},JE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:HE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?li.operators.GT:li.operators.LT;e.fail$data(li._`${r}.length ${n} ${i}`)}};Jo.default=JE});var xn=b(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});var pp=Po();pp.code='require("ajv/dist/runtime/equal").default';Qo.default=pp});var fp=b(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var Yo=Hr(),ne=F(),QE=D(),YE=xn(),XE={message:({params:{i:e,j:t}})=>ne.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>ne._`{i: ${e}, j: ${t}}`},ZE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XE,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let c=t.let("valid"),u=s.items?(0,Yo.getSchemaTypes)(s.items):[];e.block$data(c,l,ne._`${o} === false`),e.ok(c);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if(ne._`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),y=(0,Yo.checkDataTypes)(u,g,a.opts.strictNumbers,Yo.DataType.Wrong),P=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(y,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${P}[${g}] == "number"`,()=>{t.assign(h,ne._`${P}[${g}]`),e.error(),t.assign(c,!1).break()}).code(ne._`${P}[${g}] = ${m}`)})}function f(m,h){let g=(0,QE.useFunc)(t,YE.default),y=t.name("outer");t.label(y).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};Xo.default=ZE});var mp=b(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Zo=F(),eI=D(),tI=xn(),rI={message:"must be equal to constant",params:({schemaCode:e})=>Zo._`{allowedValue: ${e}}`},iI={keyword:"const",$data:!0,error:rI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(Zo._`!${(0,eI.useFunc)(t,tI.default)}(${r}, ${n})`);else e.fail(Zo._`${s} !== ${r}`)}};ea.default=iI});var hp=b(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var ci=F(),nI=D(),sI=xn(),oI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>ci._`{allowedValues: ${e}}`},aI={keyword:"enum",schemaType:"array",$data:!0,error:oI,code(e){let{gen:t,data:r,$data:i,schema:n,schemaCode:s,it:o}=e;if(!i&&n.length===0)throw Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,c,u=()=>c!==null&&c!==void 0?c:c=(0,nI.useFunc)(t,sI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,ci.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(ci._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?ci._`${u()}(${r}, ${f}[${m}])`:ci._`${r} === ${h}`}}};ta.default=aI});var ia=b(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var lI=ip(),cI=np(),dI=ap(),uI=lp(),pI=cp(),fI=dp(),mI=up(),hI=fp(),gI=mp(),yI=hp(),_I=[lI.default,cI.default,dI.default,uI.default,pI.default,fI.default,mI.default,hI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},gI.default,yI.default];ra.default=_I});var sa=b(function(di){Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var kt=F(),na=D(),PI={message:({params:{len:e}})=>kt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>kt._`{limit: ${e}}`},bI={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PI,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,na.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gp(e,i)}};function gp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",kt._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(kt._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,na.alwaysValidSchema)(o,i)){let u=r.var("valid",kt._`${a} <= ${t.length}`);r.if((0,kt.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:na.Type.Num},u),!o.allErrors)r.if((0,kt.not)(u),()=>r.break())})}}di.validateAdditionalItems=gp;di.default=bI});var oa=b(function(ui){Object.defineProperty(ui,"__esModule",{value:!0});ui.validateTuple=void 0;var yp=F(),Rn=D(),vI=Ce(),wI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _p(e,"additionalItems",t);if(r.items=!0,(0,Rn.alwaysValidSchema)(r,t))return;e.ok((0,vI.validateArray)(e))}};function _p(e,t,r=e.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=e;if(l(n),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Rn.mergeEvaluated.items(i,r.length,a.items);let c=i.name("valid"),u=i.const("len",yp._`${s}.length`);r.forEach((d,p)=>{if((0,Rn.alwaysValidSchema)(a,d))return;i.if(yp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},c)),e.ok(c)});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Rn.checkStrictMode)(a,g,p.strictTuples)}}}ui.validateTuple=_p;ui.default=wI});var Pp=b(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var $I=oa(),EI={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,$I.validateTuple)(e,"items")};aa.default=EI});var vp=b(function(la){Object.defineProperty(la,"__esModule",{value:!0});var bp=F(),II=D(),SI=Ce(),xI=sa(),RI={message:({params:{len:e}})=>bp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>bp._`{limit: ${e}}`},CI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RI,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,II.alwaysValidSchema)(i,t))return;if(n)(0,xI.validateAdditionalItems)(e,n);else e.ok((0,SI.validateArray)(e))}};la.default=CI});var wp=b(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var Fe=F(),Cn=D(),jI={message:({params:{min:e,max:t}})=>t===void 0?Fe.str`must contain at least ${e} valid item(s)`:Fe.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Fe._`{minContains: ${e}}`:Fe._`{minContains: ${e}, maxContains: ${t}}`},FI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:c,maxContains:u}=i;if(s.opts.next)o=c===void 0?1:c,a=u;else o=1;let l=t.const("len",Fe._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Cn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Cn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Cn.alwaysValidSchema)(s,r)){let h=Fe._`${l} >= ${o}`;if(a!==void 0)h=Fe._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let d=t.name("valid");if(a===void 0&&o===1)f(d,()=>t.if(d,()=>t.break()));else if(o===0){if(t.let(d,!0),a!==void 0)t.if(Fe._`${n}.length > 0`,p)}else t.let(d,!1),p();e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,l,(y)=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Cn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Fe._`${h}++`),a===void 0)t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0).break());else if(t.if(Fe._`${h} > ${a}`,()=>t.assign(d,!1).break()),o===1)t.assign(d,!0);else t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0))}}};ca.default=FI});var jn=b(function(We){Object.defineProperty(We,"__esModule",{value:!0});We.validateSchemaDeps=We.validatePropertyDeps=We.error=void 0;var da=F(),OI=D(),pi=Ce();We.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return da.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>da._`{property: ${e},
8
8
  missingProperty: ${i},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var OI={keyword:"dependencies",type:"object",schemaType:"object",error:We.error,code(e){let[t,r]=TI(e);$p(e,t),Ep(e,r)}};function TI({schema:e}){let t={},r={};for(let i in e){if(i==="__proto__")continue;let n=Array.isArray(e[i])?t:r;n[i]=e[i]}return[t,r]}function $p(e,t=e.schema){let{gen:r,data:i,it:n}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,pi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(c,()=>{for(let u of a)(0,pi.checkReportMissingProp)(e,u)});else r.if(da._`${c} && (${(0,pi.checkMissingProp)(e,a,s)})`),(0,pi.reportMissingProp)(e,s),r.else()}}We.validatePropertyDeps=$p;function Ep(e,t=e.schema){let{gen:r,data:i,keyword:n,it:s}=e,o=r.name("valid");for(let a in t){if((0,FI.alwaysValidSchema)(s,t[a]))continue;r.if((0,pi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}We.validateSchemaDeps=Ep;We.default=OI});var Sp=b(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var Ip=F(),AI=D(),kI={message:"property name must be valid",params:({params:e})=>Ip._`{propertyName: ${e.propertyName}}`},DI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kI,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,AI.alwaysValidSchema)(n,r))return;let s=t.name("valid");t.forIn("key",i,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,Ip.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};ua.default=DI});var fa=b(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});var Fn=Ce(),Me=F(),NI=Re(),On=D(),LI={message:"must NOT have additional properties",params:({params:e})=>Me._`{additionalProperty: ${e.additionalProperty}}`},qI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:LI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,On.alwaysValidSchema)(o,r))return;let u=(0,Fn.allSchemaProperties)(i.properties),l=(0,Fn.allSchemaProperties)(i.patternProperties);d(),e.ok(Me._`${s} === ${NI.default.errors}`);function d(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let P=(0,On.schemaRefOrVal)(o,i.properties,"properties");y=(0,Fn.isOwnProperty)(t,P,g)}else if(u.length)y=(0,Me.or)(...u.map((P)=>Me._`${g} === ${P}`));else y=Me.nil;if(l.length)y=(0,Me.or)(y,...l.map((P)=>Me._`${(0,Fn.usePattern)(e,P)}.test(${g})`));return(0,Me.not)(y)}function f(g){t.code(Me._`delete ${n}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,On.alwaysValidSchema)(o,r)){let y=t.name("valid");if(c.removeAdditional==="failing")h(g,y,!1),t.if((0,Me.not)(y),()=>{e.reset(),f(g)});else if(h(g,y),!a)t.if((0,Me.not)(y),()=>t.break())}}function h(g,y,P){let v={keyword:"additionalProperties",dataProp:g,dataPropType:On.Type.Str};if(P===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,y)}}};pa.default=qI});var Cp=b(function(ha){Object.defineProperty(ha,"__esModule",{value:!0});var MI=cr(),xp=Ce(),ma=D(),Rp=fa(),UI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e;if(s.opts.removeAdditional==="all"&&i.additionalProperties===void 0)Rp.default.code(new MI.KeywordCxt(s,Rp.default,"additionalProperties"));let o=(0,xp.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=ma.mergeEvaluated.props(t,(0,ma.toHash)(o),s.props);let a=o.filter((d)=>!(0,ma.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a){if(u(d))l(d);else{if(t.if((0,xp.propertyInData)(t,n,d,s.opts.ownProperties)),l(d),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(d),e.ok(c)}function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ha.default=UI});var Tp=b(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var jp=Ce(),Tn=F(),Fp=D(),Op=D(),BI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:i,parentSchema:n,it:s}=e,{opts:o}=s,a=(0,jp.allSchemaProperties)(r),c=a.filter((h)=>(0,Fp.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&n.properties,l=t.name("valid");if(s.props!==!0&&!(s.props instanceof Tn.Name))s.props=(0,Op.evaluatedPropsToName)(t,s.props);let{props:d}=s;p();function p(){for(let h of a){if(u)f(h);if(s.allErrors)m(h);else t.var(l,!0),m(h),t.if(l)}}function f(h){for(let g in u)if(new RegExp(h).test(g))(0,Fp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Tn._`${(0,jp.usePattern)(e,h)}.test(${g})`,()=>{let y=c.includes(h);if(!y)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Op.Type.Str},l);if(s.opts.unevaluated&&d!==!0)t.assign(Tn._`${d}[${g}]`,!0);else if(!y&&!s.allErrors)t.if((0,Tn.not)(l),()=>t.break())})})}}};ga.default=BI});var Ap=b(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var GI=D(),VI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,GI.alwaysValidSchema)(i,r)){e.fail();return}let n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ya.default=VI});var kp=b(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var KI=Ce(),zI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:KI.validateUnion,error:{message:"must match a schema in anyOf"}};_a.default=zI});var Dp=b(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var An=F(),WI=D(),HI={message:"must match exactly one schema in oneOf",params:({params:e})=>An._`{passingSchemas: ${e.passing}}`},JI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:HI,code(e){let{gen:t,schema:r,parentSchema:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;if((0,WI.alwaysValidSchema)(n,l))t.var(c,!0);else p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c);if(d>0)t.if(An._`${c} && ${o}`).assign(o,!1).assign(a,An._`[${a}, ${d}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,d),p)e.mergeEvaluated(p,An.Name)})})}}};Pa.default=JI});var Np=b(function(ba){Object.defineProperty(ba,"__esModule",{value:!0});var QI=D(),YI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((s,o)=>{if((0,QI.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};ba.default=YI});var Mp=b(function(va){Object.defineProperty(va,"__esModule",{value:!0});var kn=F(),qp=D(),XI={message:({params:e})=>kn.str`must match "${e.ifClause}" schema`,params:({params:e})=>kn._`{failingKeyword: ${e.ifClause}}`},ZI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:XI,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,qp.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=Lp(i,"then"),s=Lp(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),n&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else if(n)t.if(a,u("then"));else t.if((0,kn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),d)t.assign(d,kn._`${l}`);else e.setParams({ifClause:l})}}}};function Lp(e,t){let r=e.schema[t];return r!==void 0&&!(0,qp.alwaysValidSchema)(e,r)}va.default=ZI});var Up=b(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});var eS=D(),tS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,eS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wa.default=tS});var Ea=b(function($a){Object.defineProperty($a,"__esModule",{value:!0});var rS=sa(),iS=Pp(),nS=oa(),sS=vp(),oS=wp(),aS=jn(),lS=Sp(),cS=fa(),dS=Cp(),uS=Tp(),pS=Ap(),fS=kp(),mS=Dp(),hS=Np(),gS=Mp(),yS=Up();function _S(e=!1){let t=[pS.default,fS.default,mS.default,hS.default,gS.default,yS.default,lS.default,cS.default,aS.default,dS.default,uS.default];if(e)t.push(iS.default,sS.default);else t.push(rS.default,nS.default);return t.push(oS.default),t}$a.default=_S});var Sa=b(function(fi){Object.defineProperty(fi,"__esModule",{value:!0});fi.dynamicAnchor=void 0;var Ia=F(),PS=Re(),Bp=ei(),bS=$n(),vS={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>Gp(e,e.schema)};function Gp(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=Ia._`${PS.default.dynamicAnchors}${(0,Ia.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:wS(e);r.if(Ia._`!${n}`,()=>r.assign(n,s))}fi.dynamicAnchor=Gp;function wS(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:c}=i.opts,u=new Bp.SchemaEnv({schema:r,schemaId:c,root:n,baseId:s,localRefs:o,meta:a});return Bp.compileSchema.call(i,u),(0,bS.getValidate)(e,u)}fi.default=vS});var xa=b(function(mi){Object.defineProperty(mi,"__esModule",{value:!0});mi.dynamicRef=void 0;var Vp=F(),$S=Re(),Kp=$n(),ES={keyword:"$dynamicRef",schemaType:"string",code:(e)=>zp(e,e.schema)};function zp(e,t){let{gen:r,keyword:i,it:n}=e;if(t[0]!=="#")throw Error(`"${i}" only supports hash fragment reference`);let s=t.slice(1);if(n.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",Vp._`${$S.default.dynamicAnchors}${(0,Vp.getProperty)(s)}`);r.if(u,a(u,c),a(n.validateName,c))}else a(n.validateName,c)()}function a(c,u){return u?()=>r.block(()=>{(0,Kp.callRef)(e,c),r.let(u,!0)}):()=>(0,Kp.callRef)(e,c)}}mi.dynamicRef=zp;mi.default=ES});var Wp=b(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var IS=Sa(),SS=D(),xS={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,IS.dynamicAnchor)(e,"");else(0,SS.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ra.default=xS});var Hp=b(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var RS=xa(),CS={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,RS.dynamicRef)(e,e.schema)};Ca.default=CS});var Jp=b(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var jS=Sa(),FS=xa(),OS=Wp(),TS=Hp(),AS=[jS.default,FS.default,OS.default,TS.default];ja.default=AS});var Yp=b(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var Qp=jn(),kS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Qp.error,code:(e)=>(0,Qp.validatePropertyDeps)(e)};Fa.default=kS});var Xp=b(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var DS=jn(),NS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,DS.validateSchemaDeps)(e)};Oa.default=NS});var Zp=b(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});var LS=D(),qS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,LS.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ta.default=qS});var ef=b(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});var MS=Yp(),US=Xp(),BS=Zp(),GS=[MS.default,US.default,BS.default];Aa.default=GS});var rf=b(function(ka){Object.defineProperty(ka,"__esModule",{value:!0});var $t=F(),tf=D(),VS=Re(),KS={message:"must NOT have unevaluated properties",params:({params:e})=>$t._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},zS={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:KS,code(e){let{gen:t,schema:r,data:i,errsCount:n,it:s}=e;if(!n)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof $t.Name)t.if($t._`${a} !== true`,()=>t.forIn("key",i,(d)=>t.if(u(a,d),()=>c(d))));else if(a!==!0)t.forIn("key",i,(d)=>a===void 0?c(d):t.if(l(a,d),()=>c(d)));s.props=!0,e.ok($t._`${n} === ${VS.default.errors}`);function c(d){if(r===!1){if(e.setParams({unevaluatedProperty:d}),e.error(),!o)t.break();return}if(!(0,tf.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tf.Type.Str},p),!o)t.if((0,$t.not)(p),()=>t.break())}}function u(d,p){return $t._`!${d} || !${d}[${p}]`}function l(d,p){let f=[];for(let m in d)if(d[m]===!0)f.push($t._`${p} !== ${m}`);return(0,$t.and)(...f)}}};ka.default=zS});var sf=b(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});var Dt=F(),nf=D(),WS={message:({params:{len:e}})=>Dt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dt._`{limit: ${e}}`},HS={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:WS,code(e){let{gen:t,schema:r,data:i,it:n}=e,s=n.items||0;if(s===!0)return;let o=t.const("len",Dt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Dt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,nf.alwaysValidSchema)(n,r)){let c=t.var("valid",Dt._`${o} <= ${s}`);t.if((0,Dt.not)(c),()=>a(c,s)),e.ok(c)}n.items=!0;function a(c,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:nf.Type.Num},c),!n.allErrors)t.if((0,Dt.not)(c),()=>t.break())})}}};Da.default=HS});var of=b(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var JS=rf(),QS=sf(),YS=[JS.default,QS.default];Na.default=YS});var af=b(function(La){Object.defineProperty(La,"__esModule",{value:!0});var Q=F(),XS={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},ZS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XS,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),y=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(y,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(y,h)),e.fail$data((0,Q.or)(P(),v()));function P(){if(c.strictSchema===!1)return Q.nil;return Q._`${o} && !${y}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${y}(${i}) : ${y}(${i}))`:Q._`${y}(${i})`,I=Q._`(typeof ${y} == "function" ? ${w} : ${y}.test(${i}))`;return Q._`${y} && ${y} !== true && ${g} === ${t} && !${I}`}}function f(){let m=d.formats[s];if(!m){P();return}if(m===!0)return;let[h,g,y]=v(m);if(h===t)e.pass(w());function P(){if(c.strictSchema===!1){d.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(I){let E=I instanceof RegExp?(0,Q.regexpCode)(I):c.code.formats?Q._`${c.code.formats}${(0,Q.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:I,code:E});if(typeof I=="object"&&!(I instanceof RegExp))return[I.type||"string",I.validate,Q._`${x}.validate`];return["string",I,x]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw Error("async format in sync schema");return Q._`await ${y}(${i})`}return typeof g=="function"?Q._`${y}(${i})`:Q._`${y}.test(${i})`}}}};La.default=ZS});var Ma=b(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var ex=af(),tx=[ex.default];qa.default=tx});var Ua=b(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cf=b(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var rx=Uo(),ix=ia(),nx=Ea(),sx=Jp(),ox=ef(),ax=of(),lx=Ma(),lf=Ua(),cx=[sx.default,rx.default,ix.default,(0,nx.default)(!0),lx.default,lf.metadataVocabulary,lf.contentVocabulary,ox.default,ax.default];Ba.default=cx});var uf=b(function(Dn){Object.defineProperty(Dn,"__esModule",{value:!0});Dn.DiscrError=void 0;var df;(function(e){e.Tag="tag",e.Mapping="mapping"})(df||(Dn.DiscrError=df={}))});var Ka=b(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var mr=F(),Ga=uf(),pf=ei(),dx=dr(),ux=D(),px={message:({params:{discrError:e,tagName:t}})=>e===Ga.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>mr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},fx={keyword:"discriminator",type:"object",schemaType:"object",error:px,code(e){let{gen:t,data:r,schema:i,parentSchema:n,it:s}=e,{oneOf:o}=n;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(i.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",mr._`${r}${(0,mr.getProperty)(a)}`);t.if(mr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ga.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(mr._`${u} === ${m}`),t.assign(c,d(f[m]));t.else(),e.error(!1,{discrError:Ga.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,mr.Name),m}function p(){var f;let m={},h=y(n),g=!0;for(let w=0;w<o.length;w++){let I=o[w];if((I===null||I===void 0?void 0:I.$ref)&&!(0,ux.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=pf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof pf.SchemaEnv)I=I.schema;if(I===void 0)throw new dx.default(s.opts.uriResolver,s.baseId,x)}let E=(f=I===null||I===void 0?void 0:I.properties)===null||f===void 0?void 0:f[a];if(typeof E!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(I)),P(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function P(w,I){if(w.const)v(w.const,I);else if(w.enum)for(let E of w.enum)v(E,I);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(w,I){if(typeof w!="string"||w in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[w]=I}}}};Va.default=fx});var ff=b(function(Sk,mx){mx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var mf=b(function(xk,hx){hx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hf=b(function(Rk,gx){gx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var gf=b(function(Ck,yx){yx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var yf=b(function(jk,_x){_x.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var _f=b(function(Fk,Px){Px.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Pf=b(function(Ok,bx){bx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var bf=b(function(Tk,vx){vx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vf=b(function(za){Object.defineProperty(za,"__esModule",{value:!0});var wx=ff(),$x=mf(),Ex=hf(),Ix=gf(),Sx=yf(),xx=_f(),Rx=Pf(),Cx=bf(),jx=["/properties"];function Fx(e){return[wx,$x,Ex,Ix,Sx,t(this,xx),Rx,t(this,Cx)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,jx):i}}za.default=Fx});var Ja=b(function(z,Ha){Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv2020=void 0;var Ox=Lo(),Tx=cf(),Ax=Ka(),kx=vf(),Wa="https://json-schema.org/draft/2020-12/schema";class hi extends Ox.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),Tx.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(Ax.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;kx.default.call(this,e),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}}z.Ajv2020=hi;Ha.exports=z=hi;Ha.exports.Ajv2020=hi;Object.defineProperty(z,"__esModule",{value:!0});z.default=hi;var Dx=cr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return Dx.KeywordCxt}});var hr=F();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var Nx=Xr();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return Nx.default}});var Lx=dr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return Lx.default}})});var Zh=b(function(et){Object.defineProperty(et,"__esModule",{value:!0});et.formatNames=et.fastFormats=et.fullFormats=void 0;function Ze(e,t){return{validate:e,compare:t}}et.fullFormats={date:Ze(Jh,Ul),time:Ze(ql(!0),Bl),"date-time":Ze(zh(!0),Yh),"iso-time":Ze(ql(),Qh),"iso-date-time":Ze(zh(),Xh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pF,"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:PF,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:fF,int32:{type:"number",validate:gF},int64:{type:"number",validate:yF},float:{type:"number",validate:Hh},double:{type:"number",validate:Hh},password:!0,binary:!0};et.fastFormats={...et.fullFormats,date:Ze(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ul),time:Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bl),"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,Yh),"iso-time":Ze(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Qh),"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,Xh),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 aF(e){return e%4===0&&(e%100!==0||e%400===0)}var lF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,cF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Jh(e){let t=lF.exec(e);if(!t)return!1;let r=+t[1],i=+t[2],n=+t[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&aF(r)?29:cF[i])}function Ul(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ql(e){return function(r){let i=Ll.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],c=i[5]==="-"?-1:1,u=+(i[6]||0),l=+(i[7]||0);if(u>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function Bl(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),i=new Date("2020-01-01T"+t).valueOf();if(!(r&&i))return;return r-i}function Qh(e,t){if(!(e&&t))return;let r=Ll.exec(e),i=Ll.exec(t);if(!(r&&i))return;if(e=r[1]+r[2]+r[3],t=i[1]+i[2]+i[3],e>t)return 1;if(e<t)return-1;return 0}var Ml=/t|\s/i;function zh(e){let t=ql(e);return function(i){let n=i.split(Ml);return n.length===2&&Jh(n[0])&&t(n[1])}}function Yh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),i=new Date(t).valueOf();if(!(r&&i))return;return r-i}function Xh(e,t){if(!(e&&t))return;let[r,i]=e.split(Ml),[n,s]=t.split(Ml),o=Ul(r,n);if(o===void 0)return;return o||Bl(i,s)}var dF=/\/|:/,uF=/^(?:[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 pF(e){return dF.test(e)&&uF.test(e)}var Wh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function fF(e){return Wh.lastIndex=0,Wh.test(e)}var mF=-2147483648,hF=2147483647;function gF(e){return Number.isInteger(e)&&e<=hF&&e>=mF}function yF(e){return Number.isInteger(e)}function Hh(){return!0}var _F=/[^\\]\\Z/;function PF(e){if(_F.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var tg=b(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var bF=Uo(),vF=ia(),wF=Ea(),$F=Ma(),eg=Ua(),EF=[bF.default,vF.default,(0,wF.default)(),$F.default,eg.metadataVocabulary,eg.contentVocabulary];Gl.default=EF});var rg=b(function(Gq,IF){IF.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 ng=b(function(W,Vl){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var SF=Lo(),xF=tg(),RF=Ka(),ig=rg(),CF=["/properties"],bs="http://json-schema.org/draft-07/schema";class Di extends SF.default{_addVocabularies(){if(super._addVocabularies(),xF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(RF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ig,CF):ig;this.addMetaSchema(e,bs,!1),this.refs["http://json-schema.org/schema"]=bs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bs)?bs:void 0)}}W.Ajv=Di;Vl.exports=W=Di;Vl.exports.Ajv=Di;Object.defineProperty(W,"__esModule",{value:!0});W.default=Di;var jF=cr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return jF.KeywordCxt}});var Cr=F();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var FF=Xr();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return FF.default}});var OF=dr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return OF.default}})});var sg=b(function(jr){Object.defineProperty(jr,"__esModule",{value:!0});jr.formatLimitDefinition=void 0;var TF=ng(),Be=F(),Rt=Be.operators,vs={formatMaximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},formatMinimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},formatExclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},formatExclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},AF={message:({keyword:e,schemaCode:t})=>Be.str`should be ${vs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Be._`{comparison: ${vs[e].okStr}, limit: ${t}}`};jr.formatLimitDefinition={keyword:Object.keys(vs),type:"string",schemaType:"string",$data:!0,error:AF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new TF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",Be._`${p}[${c.schemaCode}]`);e.fail$data((0,Be.or)(Be._`typeof ${f} != "object"`,Be._`${f} instanceof RegExp`,Be._`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${n}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:o.code.formats?Be._`${o.code.formats}${(0,Be.getProperty)(p)}`:void 0});e.fail$data(d(m))}function d(p){return Be._`${p}.compare(${r}, ${i}) ${vs[n].fail} 0`}},dependencies:["format"]};var kF=(e)=>(e.addKeyword(jr.formatLimitDefinition),e);jr.default=kF});var cg=b(function(Ni,lg){Object.defineProperty(Ni,"__esModule",{value:!0});var Fr=Zh(),DF=sg(),Kl=F(),og=new Kl.Name("fullFormats"),NF=new Kl.Name("fastFormats"),zl=(e,t={keywords:!0})=>{if(Array.isArray(t))return ag(e,t,Fr.fullFormats,og),e;let[r,i]=t.mode==="fast"?[Fr.fastFormats,NF]:[Fr.fullFormats,og],n=t.formats||Fr.formatNames;if(ag(e,n,r,i),t.keywords)(0,DF.default)(e);return e};zl.get=(e,t="full")=>{let i=(t==="fast"?Fr.fastFormats:Fr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function ag(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=Kl._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}lg.exports=Ni=zl;Object.defineProperty(Ni,"__esModule",{value:!0});Ni.default=zl});var Xg=b(function(WM,Yg){Yg.exports=CO;function RO(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function CO(e){let t=RO(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var yy=b(function(aU,gy){var VO=require("stream");class hy extends VO{#r=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}gy.exports=hy});class it extends Error{constructor(e,t,r){super(r);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class pt extends it{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Qi{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new pt(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Yi(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Dc=require("events"),Zi=xe(require("child_process")),Ge=xe(require("path")),Br=xe(require("fs")),U=xe(require("process")),Nc=require("util");var Oc=require("util");class Xi{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((i)=>!i._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((i,n)=>i.name().localeCompare(n.name()));return t}compareOptions(e,t){let r=(i)=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((i)=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),n=r.long&&e._findOption(r.long);if(!i&&!n)t.push(r);else if(r.long&&!n)t.push(e.createOption(r.long,r.description));else if(r.short&&!i)t.push(e.createOption(r.short,r.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter((n)=>!n.hidden);t.push(...i)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((r)=>Yi(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}formatItemList(e,t,r){if(t.length===0)return[];return[r.styleTitle(e),...t,""]}groupItems(e,t,r){let i=new Map;return e.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[])}),t.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[]);i.get(s).push(n)}),i}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth??80;function n(l,d){return t.formatItem(l,r,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),i),""]);let a=t.visibleArguments(e).map((l)=>n(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(l)=>l.helpGroupHeading??"Options:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((d)=>n(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),s.join(`
10
+ deps: ${r}}`};var TI={keyword:"dependencies",type:"object",schemaType:"object",error:We.error,code(e){let[t,r]=AI(e);$p(e,t),Ep(e,r)}};function AI({schema:e}){let t={},r={};for(let i in e){if(i==="__proto__")continue;let n=Array.isArray(e[i])?t:r;n[i]=e[i]}return[t,r]}function $p(e,t=e.schema){let{gen:r,data:i,it:n}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,pi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(c,()=>{for(let u of a)(0,pi.checkReportMissingProp)(e,u)});else r.if(da._`${c} && (${(0,pi.checkMissingProp)(e,a,s)})`),(0,pi.reportMissingProp)(e,s),r.else()}}We.validatePropertyDeps=$p;function Ep(e,t=e.schema){let{gen:r,data:i,keyword:n,it:s}=e,o=r.name("valid");for(let a in t){if((0,OI.alwaysValidSchema)(s,t[a]))continue;r.if((0,pi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}We.validateSchemaDeps=Ep;We.default=TI});var Sp=b(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var Ip=F(),kI=D(),DI={message:"property name must be valid",params:({params:e})=>Ip._`{propertyName: ${e.propertyName}}`},NI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:DI,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,kI.alwaysValidSchema)(n,r))return;let s=t.name("valid");t.forIn("key",i,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,Ip.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};ua.default=NI});var fa=b(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});var Fn=Ce(),Me=F(),LI=Re(),On=D(),qI={message:"must NOT have additional properties",params:({params:e})=>Me._`{additionalProperty: ${e.additionalProperty}}`},MI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:qI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,On.alwaysValidSchema)(o,r))return;let u=(0,Fn.allSchemaProperties)(i.properties),l=(0,Fn.allSchemaProperties)(i.patternProperties);d(),e.ok(Me._`${s} === ${LI.default.errors}`);function d(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let P=(0,On.schemaRefOrVal)(o,i.properties,"properties");y=(0,Fn.isOwnProperty)(t,P,g)}else if(u.length)y=(0,Me.or)(...u.map((P)=>Me._`${g} === ${P}`));else y=Me.nil;if(l.length)y=(0,Me.or)(y,...l.map((P)=>Me._`${(0,Fn.usePattern)(e,P)}.test(${g})`));return(0,Me.not)(y)}function f(g){t.code(Me._`delete ${n}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,On.alwaysValidSchema)(o,r)){let y=t.name("valid");if(c.removeAdditional==="failing")h(g,y,!1),t.if((0,Me.not)(y),()=>{e.reset(),f(g)});else if(h(g,y),!a)t.if((0,Me.not)(y),()=>t.break())}}function h(g,y,P){let v={keyword:"additionalProperties",dataProp:g,dataPropType:On.Type.Str};if(P===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,y)}}};pa.default=MI});var Cp=b(function(ha){Object.defineProperty(ha,"__esModule",{value:!0});var UI=cr(),xp=Ce(),ma=D(),Rp=fa(),BI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e;if(s.opts.removeAdditional==="all"&&i.additionalProperties===void 0)Rp.default.code(new UI.KeywordCxt(s,Rp.default,"additionalProperties"));let o=(0,xp.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=ma.mergeEvaluated.props(t,(0,ma.toHash)(o),s.props);let a=o.filter((d)=>!(0,ma.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a){if(u(d))l(d);else{if(t.if((0,xp.propertyInData)(t,n,d,s.opts.ownProperties)),l(d),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(d),e.ok(c)}function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ha.default=BI});var Tp=b(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var jp=Ce(),Tn=F(),Fp=D(),Op=D(),GI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:i,parentSchema:n,it:s}=e,{opts:o}=s,a=(0,jp.allSchemaProperties)(r),c=a.filter((h)=>(0,Fp.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&n.properties,l=t.name("valid");if(s.props!==!0&&!(s.props instanceof Tn.Name))s.props=(0,Op.evaluatedPropsToName)(t,s.props);let{props:d}=s;p();function p(){for(let h of a){if(u)f(h);if(s.allErrors)m(h);else t.var(l,!0),m(h),t.if(l)}}function f(h){for(let g in u)if(new RegExp(h).test(g))(0,Fp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Tn._`${(0,jp.usePattern)(e,h)}.test(${g})`,()=>{let y=c.includes(h);if(!y)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Op.Type.Str},l);if(s.opts.unevaluated&&d!==!0)t.assign(Tn._`${d}[${g}]`,!0);else if(!y&&!s.allErrors)t.if((0,Tn.not)(l),()=>t.break())})})}}};ga.default=GI});var Ap=b(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var VI=D(),KI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,VI.alwaysValidSchema)(i,r)){e.fail();return}let n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ya.default=KI});var kp=b(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var zI=Ce(),WI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:zI.validateUnion,error:{message:"must match a schema in anyOf"}};_a.default=WI});var Dp=b(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var An=F(),HI=D(),JI={message:"must match exactly one schema in oneOf",params:({params:e})=>An._`{passingSchemas: ${e.passing}}`},QI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:JI,code(e){let{gen:t,schema:r,parentSchema:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;if((0,HI.alwaysValidSchema)(n,l))t.var(c,!0);else p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c);if(d>0)t.if(An._`${c} && ${o}`).assign(o,!1).assign(a,An._`[${a}, ${d}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,d),p)e.mergeEvaluated(p,An.Name)})})}}};Pa.default=QI});var Np=b(function(ba){Object.defineProperty(ba,"__esModule",{value:!0});var YI=D(),XI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((s,o)=>{if((0,YI.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};ba.default=XI});var Mp=b(function(va){Object.defineProperty(va,"__esModule",{value:!0});var kn=F(),qp=D(),ZI={message:({params:e})=>kn.str`must match "${e.ifClause}" schema`,params:({params:e})=>kn._`{failingKeyword: ${e.ifClause}}`},eS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ZI,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,qp.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=Lp(i,"then"),s=Lp(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),n&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else if(n)t.if(a,u("then"));else t.if((0,kn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),d)t.assign(d,kn._`${l}`);else e.setParams({ifClause:l})}}}};function Lp(e,t){let r=e.schema[t];return r!==void 0&&!(0,qp.alwaysValidSchema)(e,r)}va.default=eS});var Up=b(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});var tS=D(),rS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,tS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wa.default=rS});var Ea=b(function($a){Object.defineProperty($a,"__esModule",{value:!0});var iS=sa(),nS=Pp(),sS=oa(),oS=vp(),aS=wp(),lS=jn(),cS=Sp(),dS=fa(),uS=Cp(),pS=Tp(),fS=Ap(),mS=kp(),hS=Dp(),gS=Np(),yS=Mp(),_S=Up();function PS(e=!1){let t=[fS.default,mS.default,hS.default,gS.default,yS.default,_S.default,cS.default,dS.default,lS.default,uS.default,pS.default];if(e)t.push(nS.default,oS.default);else t.push(iS.default,sS.default);return t.push(aS.default),t}$a.default=PS});var Sa=b(function(fi){Object.defineProperty(fi,"__esModule",{value:!0});fi.dynamicAnchor=void 0;var Ia=F(),bS=Re(),Bp=ei(),vS=$n(),wS={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>Gp(e,e.schema)};function Gp(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=Ia._`${bS.default.dynamicAnchors}${(0,Ia.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:$S(e);r.if(Ia._`!${n}`,()=>r.assign(n,s))}fi.dynamicAnchor=Gp;function $S(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:c}=i.opts,u=new Bp.SchemaEnv({schema:r,schemaId:c,root:n,baseId:s,localRefs:o,meta:a});return Bp.compileSchema.call(i,u),(0,vS.getValidate)(e,u)}fi.default=wS});var xa=b(function(mi){Object.defineProperty(mi,"__esModule",{value:!0});mi.dynamicRef=void 0;var Vp=F(),ES=Re(),Kp=$n(),IS={keyword:"$dynamicRef",schemaType:"string",code:(e)=>zp(e,e.schema)};function zp(e,t){let{gen:r,keyword:i,it:n}=e;if(t[0]!=="#")throw Error(`"${i}" only supports hash fragment reference`);let s=t.slice(1);if(n.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",Vp._`${ES.default.dynamicAnchors}${(0,Vp.getProperty)(s)}`);r.if(u,a(u,c),a(n.validateName,c))}else a(n.validateName,c)()}function a(c,u){return u?()=>r.block(()=>{(0,Kp.callRef)(e,c),r.let(u,!0)}):()=>(0,Kp.callRef)(e,c)}}mi.dynamicRef=zp;mi.default=IS});var Wp=b(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var SS=Sa(),xS=D(),RS={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,SS.dynamicAnchor)(e,"");else(0,xS.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ra.default=RS});var Hp=b(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var CS=xa(),jS={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,CS.dynamicRef)(e,e.schema)};Ca.default=jS});var Jp=b(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var FS=Sa(),OS=xa(),TS=Wp(),AS=Hp(),kS=[FS.default,OS.default,TS.default,AS.default];ja.default=kS});var Yp=b(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var Qp=jn(),DS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Qp.error,code:(e)=>(0,Qp.validatePropertyDeps)(e)};Fa.default=DS});var Xp=b(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var NS=jn(),LS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,NS.validateSchemaDeps)(e)};Oa.default=LS});var Zp=b(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});var qS=D(),MS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,qS.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ta.default=MS});var ef=b(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});var US=Yp(),BS=Xp(),GS=Zp(),VS=[US.default,BS.default,GS.default];Aa.default=VS});var rf=b(function(ka){Object.defineProperty(ka,"__esModule",{value:!0});var Et=F(),tf=D(),KS=Re(),zS={message:"must NOT have unevaluated properties",params:({params:e})=>Et._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},WS={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:zS,code(e){let{gen:t,schema:r,data:i,errsCount:n,it:s}=e;if(!n)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof Et.Name)t.if(Et._`${a} !== true`,()=>t.forIn("key",i,(d)=>t.if(u(a,d),()=>c(d))));else if(a!==!0)t.forIn("key",i,(d)=>a===void 0?c(d):t.if(l(a,d),()=>c(d)));s.props=!0,e.ok(Et._`${n} === ${KS.default.errors}`);function c(d){if(r===!1){if(e.setParams({unevaluatedProperty:d}),e.error(),!o)t.break();return}if(!(0,tf.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tf.Type.Str},p),!o)t.if((0,Et.not)(p),()=>t.break())}}function u(d,p){return Et._`!${d} || !${d}[${p}]`}function l(d,p){let f=[];for(let m in d)if(d[m]===!0)f.push(Et._`${p} !== ${m}`);return(0,Et.and)(...f)}}};ka.default=WS});var sf=b(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});var Dt=F(),nf=D(),HS={message:({params:{len:e}})=>Dt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dt._`{limit: ${e}}`},JS={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:HS,code(e){let{gen:t,schema:r,data:i,it:n}=e,s=n.items||0;if(s===!0)return;let o=t.const("len",Dt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Dt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,nf.alwaysValidSchema)(n,r)){let c=t.var("valid",Dt._`${o} <= ${s}`);t.if((0,Dt.not)(c),()=>a(c,s)),e.ok(c)}n.items=!0;function a(c,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:nf.Type.Num},c),!n.allErrors)t.if((0,Dt.not)(c),()=>t.break())})}}};Da.default=JS});var of=b(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var QS=rf(),YS=sf(),XS=[QS.default,YS.default];Na.default=XS});var af=b(function(La){Object.defineProperty(La,"__esModule",{value:!0});var Q=F(),ZS={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},ex={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ZS,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),y=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(y,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(y,h)),e.fail$data((0,Q.or)(P(),v()));function P(){if(c.strictSchema===!1)return Q.nil;return Q._`${o} && !${y}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${y}(${i}) : ${y}(${i}))`:Q._`${y}(${i})`,I=Q._`(typeof ${y} == "function" ? ${w} : ${y}.test(${i}))`;return Q._`${y} && ${y} !== true && ${g} === ${t} && !${I}`}}function f(){let m=d.formats[s];if(!m){P();return}if(m===!0)return;let[h,g,y]=v(m);if(h===t)e.pass(w());function P(){if(c.strictSchema===!1){d.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(I){let E=I instanceof RegExp?(0,Q.regexpCode)(I):c.code.formats?Q._`${c.code.formats}${(0,Q.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:I,code:E});if(typeof I=="object"&&!(I instanceof RegExp))return[I.type||"string",I.validate,Q._`${x}.validate`];return["string",I,x]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw Error("async format in sync schema");return Q._`await ${y}(${i})`}return typeof g=="function"?Q._`${y}(${i})`:Q._`${y}.test(${i})`}}}};La.default=ex});var Ma=b(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var tx=af(),rx=[tx.default];qa.default=rx});var Ua=b(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cf=b(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var ix=Uo(),nx=ia(),sx=Ea(),ox=Jp(),ax=ef(),lx=of(),cx=Ma(),lf=Ua(),dx=[ox.default,ix.default,nx.default,(0,sx.default)(!0),cx.default,lf.metadataVocabulary,lf.contentVocabulary,ax.default,lx.default];Ba.default=dx});var uf=b(function(Dn){Object.defineProperty(Dn,"__esModule",{value:!0});Dn.DiscrError=void 0;var df;(function(e){e.Tag="tag",e.Mapping="mapping"})(df||(Dn.DiscrError=df={}))});var Ka=b(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var mr=F(),Ga=uf(),pf=ei(),ux=dr(),px=D(),fx={message:({params:{discrError:e,tagName:t}})=>e===Ga.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>mr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},mx={keyword:"discriminator",type:"object",schemaType:"object",error:fx,code(e){let{gen:t,data:r,schema:i,parentSchema:n,it:s}=e,{oneOf:o}=n;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(i.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",mr._`${r}${(0,mr.getProperty)(a)}`);t.if(mr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ga.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(mr._`${u} === ${m}`),t.assign(c,d(f[m]));t.else(),e.error(!1,{discrError:Ga.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,mr.Name),m}function p(){var f;let m={},h=y(n),g=!0;for(let w=0;w<o.length;w++){let I=o[w];if((I===null||I===void 0?void 0:I.$ref)&&!(0,px.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=pf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof pf.SchemaEnv)I=I.schema;if(I===void 0)throw new ux.default(s.opts.uriResolver,s.baseId,x)}let E=(f=I===null||I===void 0?void 0:I.properties)===null||f===void 0?void 0:f[a];if(typeof E!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(I)),P(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function P(w,I){if(w.const)v(w.const,I);else if(w.enum)for(let E of w.enum)v(E,I);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(w,I){if(typeof w!="string"||w in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[w]=I}}}};Va.default=mx});var ff=b(function(xk,hx){hx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var mf=b(function(Rk,gx){gx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hf=b(function(Ck,yx){yx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var gf=b(function(jk,_x){_x.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var yf=b(function(Fk,Px){Px.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var _f=b(function(Ok,bx){bx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Pf=b(function(Tk,vx){vx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var bf=b(function(Ak,wx){wx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vf=b(function(za){Object.defineProperty(za,"__esModule",{value:!0});var $x=ff(),Ex=mf(),Ix=hf(),Sx=gf(),xx=yf(),Rx=_f(),Cx=Pf(),jx=bf(),Fx=["/properties"];function Ox(e){return[$x,Ex,Ix,Sx,xx,t(this,Rx),Cx,t(this,jx)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,Fx):i}}za.default=Ox});var Ja=b(function(z,Ha){Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv2020=void 0;var Tx=Lo(),Ax=cf(),kx=Ka(),Dx=vf(),Wa="https://json-schema.org/draft/2020-12/schema";class hi extends Tx.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),Ax.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(kx.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;Dx.default.call(this,e),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}}z.Ajv2020=hi;Ha.exports=z=hi;Ha.exports.Ajv2020=hi;Object.defineProperty(z,"__esModule",{value:!0});z.default=hi;var Nx=cr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return Nx.KeywordCxt}});var hr=F();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var Lx=Xr();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return Lx.default}});var qx=dr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return qx.default}})});var eg=b(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.formatNames=Ze.fastFormats=Ze.fullFormats=void 0;function Xe(e,t){return{validate:e,compare:t}}Ze.fullFormats={date:Xe(Qh,Ul),time:Xe(ql(!0),Bl),"date-time":Xe(Wh(!0),Xh),"iso-time":Xe(ql(),Yh),"iso-date-time":Xe(Wh(),Zh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fF,"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:bF,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:mF,int32:{type:"number",validate:yF},int64:{type:"number",validate:_F},float:{type:"number",validate:Jh},double:{type:"number",validate:Jh},password:!0,binary:!0};Ze.fastFormats={...Ze.fullFormats,date:Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ul),time:Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bl),"date-time":Xe(/^\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,Xh),"iso-time":Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yh),"iso-date-time":Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Zh),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ze.formatNames=Object.keys(Ze.fullFormats);function lF(e){return e%4===0&&(e%100!==0||e%400===0)}var cF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Qh(e){let t=cF.exec(e);if(!t)return!1;let r=+t[1],i=+t[2],n=+t[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&lF(r)?29:dF[i])}function Ul(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ql(e){return function(r){let i=Ll.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],c=i[5]==="-"?-1:1,u=+(i[6]||0),l=+(i[7]||0);if(u>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function Bl(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),i=new Date("2020-01-01T"+t).valueOf();if(!(r&&i))return;return r-i}function Yh(e,t){if(!(e&&t))return;let r=Ll.exec(e),i=Ll.exec(t);if(!(r&&i))return;if(e=r[1]+r[2]+r[3],t=i[1]+i[2]+i[3],e>t)return 1;if(e<t)return-1;return 0}var Ml=/t|\s/i;function Wh(e){let t=ql(e);return function(i){let n=i.split(Ml);return n.length===2&&Qh(n[0])&&t(n[1])}}function Xh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),i=new Date(t).valueOf();if(!(r&&i))return;return r-i}function Zh(e,t){if(!(e&&t))return;let[r,i]=e.split(Ml),[n,s]=t.split(Ml),o=Ul(r,n);if(o===void 0)return;return o||Bl(i,s)}var uF=/\/|:/,pF=/^(?:[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 fF(e){return uF.test(e)&&pF.test(e)}var Hh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mF(e){return Hh.lastIndex=0,Hh.test(e)}var hF=-2147483648,gF=2147483647;function yF(e){return Number.isInteger(e)&&e<=gF&&e>=hF}function _F(e){return Number.isInteger(e)}function Jh(){return!0}var PF=/[^\\]\\Z/;function bF(e){if(PF.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var rg=b(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var vF=Uo(),wF=ia(),$F=Ea(),EF=Ma(),tg=Ua(),IF=[vF.default,wF.default,(0,$F.default)(),EF.default,tg.metadataVocabulary,tg.contentVocabulary];Gl.default=IF});var ig=b(function(Vq,SF){SF.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 sg=b(function(W,Vl){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var xF=Lo(),RF=rg(),CF=Ka(),ng=ig(),jF=["/properties"],bs="http://json-schema.org/draft-07/schema";class Di extends xF.default{_addVocabularies(){if(super._addVocabularies(),RF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(CF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ng,jF):ng;this.addMetaSchema(e,bs,!1),this.refs["http://json-schema.org/schema"]=bs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bs)?bs:void 0)}}W.Ajv=Di;Vl.exports=W=Di;Vl.exports.Ajv=Di;Object.defineProperty(W,"__esModule",{value:!0});W.default=Di;var FF=cr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return FF.KeywordCxt}});var Cr=F();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var OF=Xr();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return OF.default}});var TF=dr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return TF.default}})});var og=b(function(jr){Object.defineProperty(jr,"__esModule",{value:!0});jr.formatLimitDefinition=void 0;var AF=sg(),Be=F(),Rt=Be.operators,vs={formatMaximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},formatMinimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},formatExclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},formatExclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},kF={message:({keyword:e,schemaCode:t})=>Be.str`should be ${vs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Be._`{comparison: ${vs[e].okStr}, limit: ${t}}`};jr.formatLimitDefinition={keyword:Object.keys(vs),type:"string",schemaType:"string",$data:!0,error:kF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new AF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",Be._`${p}[${c.schemaCode}]`);e.fail$data((0,Be.or)(Be._`typeof ${f} != "object"`,Be._`${f} instanceof RegExp`,Be._`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${n}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:o.code.formats?Be._`${o.code.formats}${(0,Be.getProperty)(p)}`:void 0});e.fail$data(d(m))}function d(p){return Be._`${p}.compare(${r}, ${i}) ${vs[n].fail} 0`}},dependencies:["format"]};var DF=(e)=>(e.addKeyword(jr.formatLimitDefinition),e);jr.default=DF});var dg=b(function(Ni,cg){Object.defineProperty(Ni,"__esModule",{value:!0});var Fr=eg(),NF=og(),Kl=F(),ag=new Kl.Name("fullFormats"),LF=new Kl.Name("fastFormats"),zl=(e,t={keywords:!0})=>{if(Array.isArray(t))return lg(e,t,Fr.fullFormats,ag),e;let[r,i]=t.mode==="fast"?[Fr.fastFormats,LF]:[Fr.fullFormats,ag],n=t.formats||Fr.formatNames;if(lg(e,n,r,i),t.keywords)(0,NF.default)(e);return e};zl.get=(e,t="full")=>{let i=(t==="fast"?Fr.fastFormats:Fr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function lg(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=Kl._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}cg.exports=Ni=zl;Object.defineProperty(Ni,"__esModule",{value:!0});Ni.default=zl});var Zg=b(function(HM,Xg){Xg.exports=jO;function CO(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function jO(e){let t=CO(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var _y=b(function(lU,yy){var KO=require("stream");class gy extends KO{#r=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}yy.exports=gy});class rt extends Error{constructor(e,t,r){super(r);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class ft extends rt{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Qi{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ft(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Yi(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Dc=require("events"),Zi=xe(require("child_process")),Ge=xe(require("path")),Br=xe(require("fs")),U=xe(require("process")),Nc=require("util");var Oc=require("util");class Xi{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((i)=>!i._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((i,n)=>i.name().localeCompare(n.name()));return t}compareOptions(e,t){let r=(i)=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((i)=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),n=r.long&&e._findOption(r.long);if(!i&&!n)t.push(r);else if(r.long&&!n)t.push(e.createOption(r.long,r.description));else if(r.short&&!i)t.push(e.createOption(r.short,r.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter((n)=>!n.hidden);t.push(...i)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((r)=>Yi(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}formatItemList(e,t,r){if(t.length===0)return[];return[r.styleTitle(e),...t,""]}groupItems(e,t,r){let i=new Map;return e.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[])}),t.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[]);i.get(s).push(n)}),i}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth??80;function n(l,d){return t.formatItem(l,r,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),i),""]);let a=t.visibleArguments(e).map((l)=>n(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(l)=>l.helpGroupHeading??"Options:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((d)=>n(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),s.join(`
11
11
  `)}displayWidth(e){return Oc.stripVTControlCharacters(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t==="[command]")return this.styleSubcommandText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleCommandText(t)}).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map((t)=>{if(t==="[options]")return this.styleOptionText(t);if(t[0]==="["||t[0]==="<")return this.styleArgumentText(t);return this.styleSubcommandText(t)}).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,r,i){let s=" ".repeat(2);if(!r)return s+e;let o=e.padEnd(t+e.length-i.displayWidth(e)),a=2,u=(this.helpWidth??80)-t-a-2,l;if(u<this.minWidthToWrap||i.preformatted(r))l=r;else l=i.boxWrap(r,u).replace(/\n/g,`
12
12
  `+" ".repeat(t+a));return s+o+" ".repeat(a)+l.replace(/\n/g,`
13
13
  ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,n=[];return r.forEach((s)=>{let o=s.match(i);if(o===null){n.push("");return}let a=[o.shift()],c=this.displayWidth(a[0]);o.forEach((u)=>{let l=this.displayWidth(u);if(c+l<=t){a.push(u),c+=l;return}n.push(a.join(""));let d=u.trimStart();a=[d],c=this.displayWidth(d)}),n.push(a.join(""))}),n.join(`
14
- `)}}class Ur{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=o_(e);if(this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new pt(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return Tc(this.name().replace(/^no-/,""));return Tc(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Ds{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{if(this.positiveOptions.has(r))this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let i=this.negativeOptions.get(r).presetArg,n=i!==void 0?i:!1;return t.negate===(n===e)}}function Tc(e){return e.split("-").reduce((t,r)=>t+r[0].toUpperCase()+r.slice(1))}function o_(e){let t,r,i=/^-[^-]$/,n=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(i.test(s[0]))t=s.shift();if(n.test(s[0]))r=s.shift();if(!t&&i.test(s[0]))t=s.shift();if(!t&&n.test(s[0]))t=r,r=s.shift();if(s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${a}
14
+ `)}}class Ur{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=a_(e);if(this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ft(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return Tc(this.name().replace(/^no-/,""));return Tc(this.name())}helpGroup(e){return this.helpGroupHeading=e,this}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Ds{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{if(this.positiveOptions.has(r))this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let i=this.negativeOptions.get(r).presetArg,n=i!==void 0?i:!1;return t.negate===(n===e)}}function Tc(e){return e.split("-").reduce((t,r)=>t+r[0].toUpperCase()+r.slice(1))}function a_(e){let t,r,i=/^-[^-]$/,n=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(i.test(s[0]))t=s.shift();if(n.test(s[0]))r=s.shift();if(!t&&i.test(s[0]))t=s.shift();if(!t&&n.test(s[0]))t=r,r=s.shift();if(s[0].startsWith("-")){let o=s[0],a=`option creation failed due to '${o}' in option flags '${e}'`;if(/^-[^-][^-]/.test(o))throw Error(`${a}
15
15
  - a short flag is a single dash and a single character
16
16
  - either use a single dash and a single character (for a short flag)
17
17
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(i.test(o))throw Error(`${a}
18
18
  - too many short flags`);if(n.test(o))throw Error(`${a}
19
19
  - too many long flags`);throw Error(`${a}
20
- - unrecognised flag format`)}if(t===void 0&&r===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:r}}function a_(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let r=[];for(let i=0;i<=e.length;i++)r[i]=[i];for(let i=0;i<=t.length;i++)r[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=e.length;n++){let s;if(e[n-1]===t[i-1])s=0;else s=1;if(r[n][i]=Math.min(r[n-1][i]+1,r[n][i-1]+1,r[n-1][i-1]+s),n>1&&i>1&&e[n-1]===t[i-2]&&e[n-2]===t[i-1])r[n][i]=Math.min(r[n][i],r[n-2][i-2]+1)}return r[e.length][t.length]}function Ns(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let r=e.startsWith("--");if(r)e=e.slice(2),t=t.map((o)=>o.slice(2));let i=[],n=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=a_(e,o),c=Math.max(e.length,o.length);if((c-a)/c>s){if(a<n)n=a,i=[o];else if(a===n)i.push(o)}}),i.sort((o,a)=>o.localeCompare(a)),r)i=i.map((o)=>`--${o}`);if(i.length>1)return`
20
+ - unrecognised flag format`)}if(t===void 0&&r===void 0)throw Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:r}}function l_(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let r=[];for(let i=0;i<=e.length;i++)r[i]=[i];for(let i=0;i<=t.length;i++)r[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=e.length;n++){let s;if(e[n-1]===t[i-1])s=0;else s=1;if(r[n][i]=Math.min(r[n-1][i]+1,r[n][i-1]+1,r[n-1][i-1]+s),n>1&&i>1&&e[n-1]===t[i-2]&&e[n-2]===t[i-1])r[n][i]=Math.min(r[n][i],r[n-2][i-2]+1)}return r[e.length][t.length]}function Ns(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let r=e.startsWith("--");if(r)e=e.slice(2),t=t.map((o)=>o.slice(2));let i=[],n=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=l_(e,o),c=Math.max(e.length,o.length);if((c-a)/c>s){if(a<n)n=a,i=[o];else if(a===n)i.push(o)}}),i.sort((o,a)=>o.localeCompare(a)),r)i=i.map((o)=>`--${o}`);if(i.length>1)return`
21
21
  (Did you mean one of ${i.join(", ")}?)`;if(i.length===1)return`
22
22
  (Did you mean ${i[0]}?)`;return""}class Zt extends Dc.EventEmitter{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(t)=>U.default.stdout.write(t),writeErr:(t)=>U.default.stderr.write(t),outputError:(t,r)=>r(t),getOutHelpWidth:()=>U.default.stdout.isTTY?U.default.stdout.columns:void 0,getErrHelpWidth:()=>U.default.stderr.isTTY?U.default.stderr.columns:void 0,getOutHasColors:()=>kc()??(U.default.stdout.isTTY&&U.default.stdout.hasColors?.()),getErrHasColors:()=>kc()??(U.default.stderr.isTTY&&U.default.stderr.hasColors?.()),stripColor:(t)=>Nc.stripVTControlCharacters(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let i=t,n=r;if(typeof i==="object"&&i!==null)n=i,i=null;n=n||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(i)a.description(i),a._executableHandler=!0;if(n.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,o)a.arguments(o);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),i)return this;return a}createCommand(e){return new Zt(e)}createHelp(){return Object.assign(new Xi,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...e},this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
23
23
  - specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Qi(e,t)}argument(e,t,r,i){let n=this.createArgument(e,t);if(typeof r==="function")n.default(i).argParser(r);else n.default(r);return this.addArgument(n),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean"){if(this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let r=e??"help [command]",[,i,n]=r.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);if(o.helpOption(!1),n)o.arguments(n);if(s)o.description(s);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,e||t)this._initCommandGroup(o);return this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
24
- Expecting one of '${r.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,r){if(this._exitCallback)this._exitCallback(new it(e,t,r));U.default.exit(e)}action(e){let t=(r)=>{let i=this.registeredArguments.length,n=r.slice(0,i);if(this._storeOptionsAsProperties)n[i]=this;else n[i]=this.opts();return n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new Ur(e,t)}_callParseArg(e,t,r,i){try{return e.parseArg(t,r)}catch(n){if(n.code==="commander.invalidArgument"){let s=`${i} ${n.message}`;this.error(s,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
24
+ Expecting one of '${r.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,r){if(this._exitCallback)this._exitCallback(new rt(e,t,r));U.default.exit(e)}action(e){let t=(r)=>{let i=this.registeredArguments.length,n=r.slice(0,i);if(this._storeOptionsAsProperties)n[i]=this;else n[i]=this.opts();return n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new Ur(e,t)}_callParseArg(e,t,r,i){try{return e.parseArg(t,r)}catch(n){if(n.code==="commander.invalidArgument"){let s=`${i} ${n.message}`;this.error(s,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
25
25
  - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(i)=>[i.name()].concat(i.aliases()),r=t(e).find((i)=>this._findCommand(i));if(r){let i=t(this._findCommand(r)).join("|"),n=t(e).join("|");throw Error(`cannot add command '${n}' as already have command '${i}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.defaultValue!==void 0)this.setOptionValueWithSource(r,e.defaultValue,"default");let i=(n,s,o)=>{if(n==null&&e.presetArg!==void 0)n=e.presetArg;let a=this.getOptionValue(r);if(n!==null&&e.parseArg)n=this._callParseArg(e,n,a,s);else if(n!==null&&e.variadic)n=e._collectValue(n,a);if(n==null)if(e.negate)n=!1;else if(e.isBoolean()||e.optional)n=!0;else n="";this.setOptionValueWithSource(r,n,o)};if(this.on("option:"+t,(n)=>{let s=`error: option '${e.flags}' argument '${n}' is invalid.`;i(n,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(n)=>{let s=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;i(n,s,"env")});return this}_optionEx(e,t,r,i,n){if(typeof t==="object"&&t instanceof Ur)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,r);if(s.makeOptionMandatory(!!e.mandatory),typeof i==="function")s.default(n).argParser(i);else if(i instanceof RegExp){let o=i;i=(a,c)=>{let u=o.exec(a);return u?u[0]:c},s.default(n).argParser(i)}else s.default(i);return this.addOption(s)}option(e,t,r,i){return this._optionEx({},e,t,r,i)}requiredOption(e,t,r,i){return this._optionEx({mandatory:!0},e,t,r,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((r)=>{if(r.getOptionValueSource(e)!==void 0)t=r.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(U.default.versions?.electron)t.from="electron";let i=U.default.execArgv??[];if(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))t.from="eval"}if(e===void 0)e=U.default.argv;this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":if(U.default.defaultApp)this._scriptPath=e[1],r=e.slice(2);else r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",r}parse(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){this._prepareForParse();let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_prepareForParse(){if(this._savedState===null)this.options.filter((e)=>e.negate&&e.defaultValue===void 0&&this.getOptionValue(e.attributeName())===void 0).forEach((e)=>{let t=e.long.replace(/^--no-/,"--");if(!this._findOption(t))this.setOptionValueWithSource(e.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
26
26
  - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,r){if(Br.default.existsSync(e))return;let i=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${e}' does not exist
27
27
  - if '${r}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
28
28
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
29
- - ${i}`;throw Error(n)}_executeSubCommand(e,t){t=t.slice();let r=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,l){let d=Ge.default.resolve(u,l);if(Br.default.existsSync(d))return d;if(r.includes(Ge.default.extname(l)))return;let p=r.find((f)=>Br.default.existsSync(`${d}${f}`));if(p)return`${d}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let u;try{u=Br.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}s=Ge.default.resolve(Ge.default.dirname(u),s)}if(s){let u=i(s,n);if(!u&&!e._executableFile&&this._scriptPath){let l=Ge.default.basename(this._scriptPath,Ge.default.extname(this._scriptPath));if(l!==this._name)u=i(s,`${l}-${e._name}`)}n=u||n}let o=r.includes(Ge.default.extname(n)),a;if(U.default.platform!=="win32")if(o)t.unshift(n),t=Ac(U.default.execArgv).concat(t),a=Zi.default.spawn(U.default.argv[0],t,{stdio:"inherit"});else a=Zi.default.spawn(n,t,{stdio:"inherit"});else this._checkForMissingExecutable(n,s,e._name),t.unshift(n),t=Ac(U.default.execArgv).concat(t),a=Zi.default.spawn(U.default.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((l)=>{U.default.on(l,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(l)})});let c=this._exitCallback;a.on("close",(u)=>{if(u=u??1,!c)U.default.exit(u);else c(new it(u,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(n,s,e._name);else if(u.code==="EACCES")throw Error(`'${n}' not executable`);if(!c)U.default.exit(1);else{let l=new it(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,c(l)}}),this.runningCommand=a}_dispatchSubcommand(e,t,r){let i=this._findCommand(e);if(!i)this.help({error:!0});i._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,i,"preSubcommand"),n=this._chainOrCall(n,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(r));else return i._parseCommand(t,r)}),n}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(r,i,n)=>{let s=i;if(i!==null&&r.parseArg){let o=`error: command-argument value '${i}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,i,n,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,i)=>{let n=r.defaultValue;if(r.variadic){if(i<this.args.length){if(n=this.args.slice(i),r.parseArg)n=n.reduce((s,o)=>e(r,o,s),r.defaultValue)}else if(n===void 0)n=[]}else if(i<this.args.length){if(n=this.args[i],r.parseArg)n=e(r,n,r.defaultValue)}t[i]=n}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let r=e,i=[];if(this._getCommandAndAncestors().reverse().filter((n)=>n._lifeCycleHooks[t]!==void 0).forEach((n)=>{n._lifeCycleHooks[t].forEach((s)=>{i.push({hookedCommand:n,callback:s})})}),t==="postAction")i.reverse();return i.forEach((n)=>{r=this._chainOrCall(r,()=>n.callback(n.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let i=e;if(this._lifeCycleHooks[r]!==void 0)this._lifeCycleHooks[r].forEach((n)=>{i=this._chainOrCall(i,()=>n(this,t))});return i}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{if(r.unknown.length>0)this.unknownOption(r.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(n,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(n))i(),this._processArguments(),this.parent.emit(n,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else i(),this._processArguments()}else if(this.commands.length)i(),this.help({error:!0});else i(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((r)=>{let i=r.attributeName();if(this.getOptionValue(i)===void 0)return!1;return this.getOptionValueSource(i)!=="default"});e.filter((r)=>r.conflictsWith.length>0).forEach((r)=>{let i=e.find((n)=>r.conflictsWith.includes(n.attributeName()));if(i)this._conflictingOption(r,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],i=t;function n(u){return u.length>1&&u[0]==="-"}let s=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((l)=>l.options.map((d)=>d.short).some((d)=>/^-\d$/.test(d)))},o=null,a=null,c=0;while(c<e.length||a){let u=a??e[c++];if(a=null,u==="--"){if(i===r)i.push(u);i.push(...e.slice(c));break}if(o&&(!n(u)||s(u))){this.emit(`option:${o.name()}`,u);continue}if(o=null,n(u)){let l=this._findOption(u);if(l){if(l.required){let d=e[c++];if(d===void 0)this.optionMissingArgument(l);this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;if(c<e.length&&(!n(e[c])||s(e[c])))d=e[c++];this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);o=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){if(l.required||l.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${l.name()}`,u.slice(2));else this.emit(`option:${l.name()}`),a=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),d=this._findOption(u.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(l+1));continue}}if(i===t&&n(u)&&!(this.commands.length===0&&s(u)))i=r;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),r.push(...e.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(c));break}else if(this._defaultCommandName){r.push(u,...e.slice(c));break}}if(this._passThroughOptions){i.push(u,...e.slice(c));break}i.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let i=this.options[r].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
29
+ - ${i}`;throw Error(n)}_executeSubCommand(e,t){t=t.slice();let r=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,l){let d=Ge.default.resolve(u,l);if(Br.default.existsSync(d))return d;if(r.includes(Ge.default.extname(l)))return;let p=r.find((f)=>Br.default.existsSync(`${d}${f}`));if(p)return`${d}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let u;try{u=Br.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}s=Ge.default.resolve(Ge.default.dirname(u),s)}if(s){let u=i(s,n);if(!u&&!e._executableFile&&this._scriptPath){let l=Ge.default.basename(this._scriptPath,Ge.default.extname(this._scriptPath));if(l!==this._name)u=i(s,`${l}-${e._name}`)}n=u||n}let o=r.includes(Ge.default.extname(n)),a;if(U.default.platform!=="win32")if(o)t.unshift(n),t=Ac(U.default.execArgv).concat(t),a=Zi.default.spawn(U.default.argv[0],t,{stdio:"inherit"});else a=Zi.default.spawn(n,t,{stdio:"inherit"});else this._checkForMissingExecutable(n,s,e._name),t.unshift(n),t=Ac(U.default.execArgv).concat(t),a=Zi.default.spawn(U.default.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((l)=>{U.default.on(l,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(l)})});let c=this._exitCallback;a.on("close",(u)=>{if(u=u??1,!c)U.default.exit(u);else c(new rt(u,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(u)=>{if(u.code==="ENOENT")this._checkForMissingExecutable(n,s,e._name);else if(u.code==="EACCES")throw Error(`'${n}' not executable`);if(!c)U.default.exit(1);else{let l=new rt(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,c(l)}}),this.runningCommand=a}_dispatchSubcommand(e,t,r){let i=this._findCommand(e);if(!i)this.help({error:!0});i._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,i,"preSubcommand"),n=this._chainOrCall(n,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(r));else return i._parseCommand(t,r)}),n}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(r,i,n)=>{let s=i;if(i!==null&&r.parseArg){let o=`error: command-argument value '${i}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,i,n,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,i)=>{let n=r.defaultValue;if(r.variadic){if(i<this.args.length){if(n=this.args.slice(i),r.parseArg)n=n.reduce((s,o)=>e(r,o,s),r.defaultValue)}else if(n===void 0)n=[]}else if(i<this.args.length){if(n=this.args[i],r.parseArg)n=e(r,n,r.defaultValue)}t[i]=n}),this.processedArgs=t}_chainOrCall(e,t){if(e?.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let r=e,i=[];if(this._getCommandAndAncestors().reverse().filter((n)=>n._lifeCycleHooks[t]!==void 0).forEach((n)=>{n._lifeCycleHooks[t].forEach((s)=>{i.push({hookedCommand:n,callback:s})})}),t==="postAction")i.reverse();return i.forEach((n)=>{r=this._chainOrCall(r,()=>n.callback(n.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let i=e;if(this._lifeCycleHooks[r]!==void 0)this._lifeCycleHooks[r].forEach((n)=>{i=this._chainOrCall(i,()=>n(this,t))});return i}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{if(r.unknown.length>0)this.unknownOption(r.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(n,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(n))i(),this._processArguments(),this.parent.emit(n,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else i(),this._processArguments()}else if(this.commands.length)i(),this.help({error:!0});else i(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((r)=>{let i=r.attributeName();if(this.getOptionValue(i)===void 0)return!1;return this.getOptionValueSource(i)!=="default"});e.filter((r)=>r.conflictsWith.length>0).forEach((r)=>{let i=e.find((n)=>r.conflictsWith.includes(n.attributeName()));if(i)this._conflictingOption(r,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],i=t;function n(u){return u.length>1&&u[0]==="-"}let s=(u)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u))return!1;return!this._getCommandAndAncestors().some((l)=>l.options.map((d)=>d.short).some((d)=>/^-\d$/.test(d)))},o=null,a=null,c=0;while(c<e.length||a){let u=a??e[c++];if(a=null,u==="--"){if(i===r)i.push(u);i.push(...e.slice(c));break}if(o&&(!n(u)||s(u))){this.emit(`option:${o.name()}`,u);continue}if(o=null,n(u)){let l=this._findOption(u);if(l){if(l.required){let d=e[c++];if(d===void 0)this.optionMissingArgument(l);this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;if(c<e.length&&(!n(e[c])||s(e[c])))d=e[c++];this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);o=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){if(l.required||l.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${l.name()}`,u.slice(2));else this.emit(`option:${l.name()}`),a=`-${u.slice(2)}`;continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),d=this._findOption(u.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(l+1));continue}}if(i===t&&n(u)&&!(this.commands.length===0&&s(u)))i=r;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),r.push(...e.slice(c));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(c));break}else if(this._defaultCommandName){r.push(u,...e.slice(c));break}}if(this._passThroughOptions){i.push(u,...e.slice(c));break}i.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let i=this.options[r].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
30
30
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
31
31
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
32
32
  `),this.outputHelp({error:!0});let r=t||{},i=r.exitCode||1,n=r.code||"commander.error";this._exit(i,n,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in U.default.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,U.default.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Ds(this.options),t=(r)=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter((r)=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach((r)=>{Object.keys(r.implied).filter((i)=>!t(i)).forEach((i)=>{this.setOptionValueWithSource(i,r.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=(s)=>{let o=s.attributeName(),a=this.getOptionValue(o),c=this.options.find((l)=>l.negate&&o===l.attributeName()),u=this.options.find((l)=>!l.negate&&o===l.attributeName());if(c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg))return c;return u||s},i=(s)=>{let o=r(s),a=o.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},n=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],n=this;do{let s=n.createHelp().visibleOptions(n).filter((o)=>o.long).map((o)=>o.long);i=i.concat(s),n=n.parent}while(n&&!n._enablePositionalOptions);t=Ns(e,i)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=e.length,n=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${n}. Expected ${t} argument${r} but got ${i}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach((n)=>{if(i.push(n.name()),n.alias())i.push(n.alias())}),t=Ns(e,i)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let i=this.createOption(t,r);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
33
33
  `),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let i=[r.name()].concat(r.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${i}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((r)=>Yi(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=Ge.default.basename(e,Ge.default.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let i=t.formatHelp(this,t);if(r.hasColors)return i;return this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,r,i,n;if(t)r=(o)=>this._outputConfiguration.writeErr(o),i=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth();else r=(o)=>this._outputConfiguration.writeOut(o),i=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!i)o=this._outputConfiguration.stripColor(o);return r(o)},hasColors:i,helpWidth:n}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let r=this._getOutputContext(e),i={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation({error:r.error});if(t){if(n=t(n),typeof n!=="string"&&!Buffer.isBuffer(n))throw Error("outputHelp callback must return a string or a Buffer")}if(r.write(n),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",i),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",i))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(U.default.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw Error(`Unexpected value for position to addHelpText.
34
34
  Expecting one of '${r.join("', '")}'`);let i=`${e}Help`;return this.on(i,(n)=>{let s;if(typeof t==="function")s=t({error:n.error,command:n.command});else s=t;if(s)n.write(`${s}
35
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((i)=>t.is(i)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Ac(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let r,i="127.0.0.1",n="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)r=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(r=s[1],/^\d+$/.test(s[3]))n=s[3];else i=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)r=s[1],i=s[3],n=s[4];if(r&&n!=="0")return`${r}=${i}:${parseInt(n)+1}`;return t})}function kc(){if(U.default.env.NO_COLOR||U.default.env.FORCE_COLOR==="0"||U.default.env.FORCE_COLOR==="false")return!1;if(U.default.env.FORCE_COLOR||U.default.env.CLICOLOR_FORCE!==void 0)return!0;return}var NT=new Zt;function _(e,t){if(e)return;if(typeof t==="string")throw Error(t);throw t}var Ji=require("path"),Wy=require("readline/promises");class re extends Error{code;status;body;constructor(e,t,r,i){super(e);this.name="PotatoApiError",this.code=t,this.status=r,this.body=i}static fromResponse(e,t){return new re(`Potato API request failed with status ${e}`,"http",e,t)}static waitTimeout(e){return new re(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class er extends Error{code="invalid_pipeline_graph";issues;constructor(e,t){super(e);this.name="PipelineGraphValidationError",this.issues=t}static fromIssues(e){let t=e.map(({path:r,reason:i})=>`- ${r}: ${i}`).join(`
35
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((i)=>t.is(i)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Ac(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let r,i="127.0.0.1",n="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)r=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(r=s[1],/^\d+$/.test(s[3]))n=s[3];else i=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)r=s[1],i=s[3],n=s[4];if(r&&n!=="0")return`${r}=${i}:${parseInt(n)+1}`;return t})}function kc(){if(U.default.env.NO_COLOR||U.default.env.FORCE_COLOR==="0"||U.default.env.FORCE_COLOR==="false")return!1;if(U.default.env.FORCE_COLOR||U.default.env.CLICOLOR_FORCE!==void 0)return!0;return}var LT=new Zt;function _(e,t){if(e)return;if(typeof t==="string")throw Error(t);throw t}var Ji=require("path"),Hy=require("readline/promises");class re extends Error{code;status;body;constructor(e,t,r,i){super(e);this.name="PotatoApiError",this.code=t,this.status=r,this.body=i}static fromResponse(e,t){return new re(`Potato API request failed with status ${e}`,"http",e,t)}static waitTimeout(e){return new re(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class er extends Error{code="invalid_pipeline_graph";issues;constructor(e,t){super(e);this.name="PipelineGraphValidationError",this.issues=t}static fromIssues(e){let t=e.map(({path:r,reason:i})=>`- ${r}: ${i}`).join(`
36
36
  `);return new er(`Pipeline graph validation failed
37
- ${t}`,e)}}var qs="x-potato-sdk-base-url",Lc=(e,t,r)=>(_(e.length>0,"The SDK base URL cannot be empty"),_(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[qs]:new URL(e).toString()},fetch:r});async function C(e,t){let{fetch:r=globalThis.fetch,...i}=t,n=new Headers(i.headers),s=n.get(qs);_(s,"The SDK base URL is missing"),n.delete(qs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let c=a;if(a.length===0)c=void 0;else if(o.headers.get("content-type")?.includes("application/json"))c=JSON.parse(a);throw re.fromResponse(o.status,c)}return a.length===0?void 0:JSON.parse(a)}var w0=()=>"/api/v2-beta/me",qc=async(e)=>C(w0(),{...e,method:"GET"}),$0=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([i,n])=>{if(n!==void 0)t.append(i,n===null?"null":n.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},Ms=async(e,t)=>C($0(e),{...t,method:"GET"}),E0=()=>"/api/v2-beta/projects",Mc=async(e,t)=>C(E0(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),I0=(e)=>`/api/v2-beta/projects/${e}`,Uc=async(e,t)=>C(I0(e),{...t,method:"GET"}),S0=(e)=>`/api/v2-beta/projects/${e}`,Bc=async(e,t,r)=>C(S0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),x0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Us=async(e,t,r)=>C(x0(e,t),{...r,method:"GET"}),R0=(e)=>`/api/v2-beta/pipelines/${e}`,Gc=async(e,t)=>C(R0(e),{...t,method:"GET"}),C0=(e)=>`/api/v2-beta/pipelines/${e}`,Vc=async(e,t,r)=>C(C0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),j0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/datasets?${i}`:`/api/v2-beta/projects/${e}/datasets`},Bs=async(e,t,r)=>C(j0(e,t),{...r,method:"GET"}),F0=(e)=>`/api/v2-beta/projects/${e}/datasets`,Kc=async(e,t,r)=>C(F0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),O0=(e)=>`/api/v2-beta/datasets/${e}`,zc=async(e,t)=>C(O0(e),{...t,method:"GET"}),T0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/fields?${i}`:`/api/v2-beta/datasets/${e}/fields`},Gs=async(e,t,r)=>C(T0(e,t),{...r,method:"GET"}),A0=(e)=>`/api/v2-beta/datasets/${e}/fields`,Vs=async(e,t,r)=>C(A0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),k0=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,Wc=async(e,t)=>C(k0(e),{...t,method:"GET"}),D0=(e)=>`/api/v2-beta/datasets/${e}/items`,Hc=async(e,t,r)=>C(D0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),N0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/items?${i}`:`/api/v2-beta/datasets/${e}/items`},Ks=async(e,t,r)=>C(N0(e,t),{...r,method:"GET"}),L0=(e)=>`/api/v2-beta/datasets/${e}/uploads`,Jc=async(e,t,r)=>C(L0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),q0=(e)=>`/api/v2-beta/uploads/${e}/finalize`,Qc=async(e,t)=>C(q0(e),{...t,method:"POST"}),M0=(e)=>`/api/v2-beta/uploads/${e}`,zs=async(e,t)=>C(M0(e),{...t,method:"GET"}),U0=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,Yc=async(e,t,r)=>C(U0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),B0=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,Xc=async(e,t,r)=>C(B0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),G0=(e)=>`/api/v2-beta/pipelines/${e}/export`,Zc=async(e,t)=>C(G0(e),{...t,method:"GET"}),V0=(e)=>`/api/v2-beta/pipelines/${e}/copy`,ed=async(e,t,r)=>C(V0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),K0=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,td=async(e,t,r)=>C(K0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),z0=(e)=>`/api/v2-beta/pipelines/${e}/runs`,rd=async(e,t)=>C(z0(e),{...t,method:"POST"}),W0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},Ws=async(e,t,r)=>C(W0(e,t),{...r,method:"GET"}),H0=(e)=>`/api/v2-beta/runs/${e}`,Hs=async(e,t)=>C(H0(e),{...t,method:"GET"}),J0=(e)=>`/api/v2-beta/runs/${e}/cancel`,id=async(e,t)=>C(J0(e),{...t,method:"POST"}),Q0=(e)=>`/api/v2-beta/datasets/${e}/exports`,nd=async(e,t,r)=>C(Q0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Y0=(e)=>`/api/v2-beta/exports/${e}`,Js=async(e,t)=>C(Y0(e),{...t,method:"GET"}),X0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,sd=async(e,t)=>C(X0(e),{...t,method:"GET"}),Z0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,od=async(e,t,r)=>C(Z0(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),ev=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,ad=async(e,t,r)=>C(ev(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),tv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,ld=async(e,t,r,i)=>C(tv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),rv=(e)=>`/api/v2-beta/projects/${e}/secrets`,cd=async(e,t)=>C(rv(e),{...t,method:"GET"}),iv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,dd=async(e,t,r,i)=>C(iv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),nv=(e)=>`/api/v2-beta/projects/${e}/files`,ud=async(e,t)=>C(nv(e),{...t,method:"GET"}),sv=(e)=>`/api/v2-beta/projects/${e}/files`,pd=async(e,t,r)=>C(sv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),ov=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,fd=async(e,t,r)=>C(ov(e,t),{...r,method:"POST"}),av=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,md=async(e,t,r)=>C(av(e,t),{...r,method:"DELETE"}),lv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/runs/${e}/items?${i}`:`/api/v2-beta/runs/${e}/items`},Qs=async(e,t,r)=>C(lv(e,t),{...r,method:"GET"}),cv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,hd=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,gd=async(e,t)=>C(dv(e),{...t,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,yd=async(e,t,r)=>C(uv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),pv=(e)=>`/api/v2-beta/checks/${e}`,Ys=async(e,t)=>C(pv(e),{...t,method:"GET"});async function*ft(e,t={}){let r=t.offset;while(!0){let i=await e({limit:t.limit,offset:r});if(yield*i.items,!i.pagination.hasMore)return;r=i.pagination.offset+i.pagination.limit}}var Gr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;_(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),_(Number.isFinite(n)&&n>0,"The polling interval must be a positive finite number");let s=Date.now()+i,o=new AbortController,a=setTimeout(()=>o.abort(),i);try{while(!0){if(o.signal.aborted)throw re.waitTimeout(i);let c=await e(o.signal);if(t(c))return c;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:d}=Promise.withResolvers();setTimeout(d,Math.min(n,u)),await l}}catch(c){if(o.signal.aborted)throw re.waitTimeout(i);throw c}finally{clearTimeout(a)}};var mv=(e)=>{let t=Lc(e.baseUrl,e.apiKey,e.fetch);async function r(l,d){switch(l.type){case"datasetUpload":return Gr((p)=>zs(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"datasetExport":return Gr((p)=>Js(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",d);case"pipelineCheck":return Gr((p)=>Ys(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"pipelineRun":return Gr((p)=>Hs(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d)}}return{me:()=>qc(t),projects:{create:(l)=>Mc(l,t),get:({projectId:l})=>Uc(l,t),update:({projectId:l,...d})=>Bc(l,d,t),listPage:(l={})=>Ms(l,t),listAll:(l={})=>ft(async(d)=>{let p=await Ms({...l,...d},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...d})=>Yc(l,d,t),get:({pipelineId:l})=>Gc(l,t),update:({pipelineId:l,...d})=>Vc(l,d,t),listPage:({projectId:l,...d})=>Us(l,d,t),listAll:({projectId:l,...d})=>ft(async(p)=>{let f=await Us(l,{...d,...p},t);return{items:f.pipelines,pagination:f.pagination}},d),getGraph:({pipelineId:l})=>sd(l,t),replaceGraph:({pipelineId:l,...d})=>od(l,"version"in d?{graph:d.graph,expectedVersion:d.version}:d,t),validateGraph:({pipelineId:l,...d})=>ad(l,d,t),estimateCost:({pipelineId:l,...d})=>td(l,d,t),patchNode:({pipelineId:l,nodeId:d,...p})=>ld(l,d,p,t),attachDataset:({pipelineId:l,...d})=>Xc(l,d,t),export:({pipelineId:l})=>Zc(l,t),copy:({pipelineId:l,...d})=>ed(l,d,t)},datasets:{create:({projectId:l,...d})=>Kc(l,d,t),get:({datasetId:l})=>zc(l,t),listPage:({projectId:l,...d})=>Bs(l,d,t),listAll:({projectId:l,...d})=>ft(async(p)=>{let f=await Bs(l,{...d,...p},t);return{items:f.datasets,pagination:f.pagination}},d),createField:async({datasetId:l,...d})=>{let p=await Vs(l,d,t);return _(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:d})=>{let p=await Vs(l,{fields:d},t);return _("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...d})=>Gs(l,d,t),getInferredFields:({datasetId:l})=>Wc(l,t),listAllFields:({datasetId:l,...d})=>ft(async(p)=>{let f=await Gs(l,{...d,...p},t);return{items:f.fields,pagination:f.pagination}},d),appendItems:({datasetId:l,...d})=>Hc(l,d,t),listItemsPage:({datasetId:l,...d})=>Ks(l,d,t),listAllItems:({datasetId:l,...d})=>ft(async(p)=>{let f=await Ks(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),startUpload:({datasetId:l,...d})=>Jc(l,d,t),finalizeUpload:({uploadId:l})=>Qc(l,t),getUpload:({uploadId:l})=>zs(l,t),startExport:({datasetId:l,...d})=>nd(l,d,t),getExport:({exportId:l})=>Js(l,t)},runs:{start:({pipelineId:l})=>{let d=new Headers(t.headers);return d.set("Content-Type","application/json"),rd(l,{...t,headers:d,body:"{}"})},get:({runId:l})=>Hs(l,t),cancel:({runId:l})=>id(l,t),listPage:({pipelineId:l,...d})=>Ws(l,d,t),listAll:({pipelineId:l,...d})=>ft(async(p)=>{let f=await Ws(l,{...d,...p},t);return{items:f.runs,pagination:f.pagination}},d),listItemsPage:({runId:l,...d})=>Qs(l,d,t),listAllItems:({runId:l,...d})=>ft(async(p)=>{let f=await Qs(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),getItem:({runId:l,itemId:d})=>hd(l,d,t)},secrets:{list:async({projectId:l})=>(await cd(l,t)).secrets,set:({projectId:l,name:d,...p})=>dd(l,d,p,t)},files:{list:async({projectId:l})=>(await ud(l,t)).files,startUpload:({projectId:l,...d})=>pd(l,d,t),finalizeUpload:({projectId:l,fileId:d})=>fd(l,d,t),delete:({projectId:l,fileId:d})=>md(l,d,t)},checks:{list:async({pipelineId:l})=>(await gd(l,t)).checks,start:({pipelineId:l,...d})=>yd(l,d,t),get:({checkRunId:l})=>Ys(l,t)},waitFor:r}};function nt(e){return mv(e)}var gr=require("fs/promises"),Qa=require("path"),$f=xe(Ja(),1);var Nn="toloka.json";class Ya extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var qx="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",Mx={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:qx},additionalProperties:{type:"object",properties:{pipelineId:{type:"string",minLength:1}},required:["pipelineId"],additionalProperties:!1}},datasets:{type:"object",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",properties:{datasetId:{type:"string",minLength:1}},required:["datasetId"],additionalProperties:!1}}},required:["projectId","pipelines","datasets"],additionalProperties:!1},Ux=new $f.default({allErrors:!0,strict:!1}),wf=Ux.compile(Mx);function Bx(e){let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return`${typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/"}: ${e.message??`failed ${e.keyword} validation`}`}function Ef(e){if(wf(e))return e;let t=wf.errors;throw _(t,"toloka.json validation failed without errors"),new Ya(`Invalid toloka.json: ${t.map(Bx).join("; ")}`)}async function $e(e){let t;try{t=await gr.readFile(Qa.join(e,Nn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Ef(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new Ya(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Nt(e,t){let r=Ef(t),i=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),n=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await gr.mkdir(e,{recursive:!0}),await gr.writeFile(Qa.join(e,Nn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
38
- `,"utf8")}var fe=require("fs/promises"),Sf=require("os"),yr=require("path");class gi extends Error{constructor(e,t){super(e,t);this.name="CredentialsError"}}var xf=(e)=>e.HOME??Sf.homedir(),Gx=(e)=>e.XDG_CONFIG_HOME??yr.join(xf(e),".config"),Ue=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??yr.join(Gx(e),"toloka","credentials.json"),Rf=(e=process.env)=>yr.join(xf(e),".toloka","credentials.json"),Et=(e)=>{let t=e.trim().replace(/\/+$/u,"");try{let r=new URL(t);return r.hash="",r.search="",r.toString().replace(/\/+$/u,"")}catch{return t}},Ln=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,Vx=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let r=Reflect.get(e,"name");if(r!==void 0&&typeof r!=="string")return;return r===void 0?{id:t}:{id:t,name:r}},Kx=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[r,i]of Object.entries(e)){if(r.length===0)return;let n=Vx(i);if(n===void 0)return;Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}return t},zx=(e,t)=>{let r=Kx(e);if(r===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(r,t))return;return{current:t,projects:r}}if(t!==void 0)return;return Object.keys(r).length===0?{}:{projects:r}},Wx=(e)=>{let t=Ln(e,"baseUrl"),r=Ln(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(typeof r!=="string"||r.length===0)return;let i=Ln(e,"current"),n=Ln(e,"projects");if(i===void 0&&n===void 0)return{baseUrl:t,apiKey:r};let s=zx(n,i);if(s===void 0)return;return{baseUrl:t,apiKey:r,...s}};async function qn(e){let t;try{t=await fe.readFile(e,"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"missing";return"invalid"}try{let r=Wx(JSON.parse(t));return r===void 0?"invalid":{credentials:r}}catch{return"invalid"}}async function Xa(e=process.env){let t=Ue(e),r=await qn(t);if(r!=="missing"){if(r==="invalid")throw new gi(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`);return{credentials:r.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let i=Rf(e),n=await qn(i);if(n==="missing")return;if(n==="invalid")throw new gi(`Invalid credentials file at ${i}. Run toloka logout, then toloka login.`);return{credentials:n.credentials,path:i,legacy:!0}}async function yi(e,t){try{return{found:await Xa(e)}}catch(r){if(!(r instanceof gi)||t===void 0)throw r;return{found:void 0,warning:r.message}}}async function Cf(e=process.env){return(await Xa(e))?.credentials}async function It(e=process.env){let t=await Xa(e);if(t!==void 0)return t;throw new gi(`No stored credentials found at ${Ue(e)}. Run toloka login.`)}var Hx=(e)=>{let t=e.projects,r=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,apiKey:e.apiKey,...e.current===void 0?{}:{current:e.current},...r?{projects:t}:{}}},If=async(e)=>{try{let t=await fe.lstat(e);_(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function Za(e){let t=yr.dirname(e);await If(t),await If(e),await fe.mkdir(t,{recursive:!0,mode:448}),await fe.chmod(t,448)}async function Mn(e,t=process.env){let r=Ue(t);return await Za(r),await fe.writeFile(r,`${JSON.stringify(Hx(e),null,2)}
39
- `,{mode:384}),await fe.chmod(r,384),r}var Jx=async(e)=>{try{return await fe.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}};async function jf(e=process.env){let t=[],r=[Ue(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Rf(e)]:[]];for(let i of r){if(!await Jx(i))continue;await fe.rm(i,{force:!0}),t.push(i)}return t}var Qx=16,Ff=(e)=>e.length>Qx?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var he="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, set projectId in toloka.json, or run toloka project add.",Yx="No project selected. Run toloka project add, or cd into a checkout.",Of="project add writes the machine registry; unset --api-key / --base-url / POTATO_API_KEY / POTATO_BASE_URL, or run login against that platform first.",Xx=/^[^/\s]+$/u,Un=(e)=>{let t=e.trim();return _(t.length>0&&Xx.test(t),"Project alias must be non-empty and contain no / or whitespace."),t},me=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},Zx=(e,t,r)=>me(e?.baseUrl)??me(t?.POTATO_BASE_URL)??Lt(t??{})??me(r?.baseUrl),_i=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,eR=(e,t,r)=>{if(!r||t?.projects===void 0)return{};if(t.current!==void 0){let i=_i(t.projects,t.current);if(i?.id===e)return i.name===void 0?{alias:t.current}:{alias:t.current,name:i.name}}for(let i of Object.keys(t.projects).toSorted()){let n=_i(t.projects,i);if(n?.id!==e)continue;return n.name===void 0?{alias:i}:{alias:i,name:n.name}}return{}};function Pi(e={}){let t=e.flags??{},r=e.environment??{},i=e.stored,n=e.effectiveBaseUrl??Zx(t,r,i),s=i!==void 0&&n!==void 0&&Et(n)===Et(i.baseUrl),a=[{id:me(t.projectId),source:"flag"},{id:me(r.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:me(r.POTATO_PROJECT_ID),source:"potato-project-id"},{id:me(e.state?.projectId),source:"toloka.json"},{id:s&&i.current!==void 0?me(i.projects?.[i.current]?.id):void 0,source:"registry"}].find((c)=>c.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...eR(a.id,i,s)}}var tl=(e,t)=>{if(e===void 0)return"Project: (none). Run toloka project add.";let r=e.alias===void 0?"":`alias ${e.alias}, `,i=e.source!=="registry"&&t?.current!==void 0?`; registry current is ${t.current}`:"";return`Project: ${e.id} (${r}from ${e.source}${i})`},Bn=(e,t,r)=>{let i=me(e.apiKey)??me(t.POTATO_API_KEY),n=me(e.baseUrl)??me(t.POTATO_BASE_URL)??Lt(t);_(i===void 0||i===r.apiKey,Of),_(n===void 0||Et(n)===Et(r.baseUrl),Of)},Gn=async(e,t)=>{await Mn(e,t)},Tf=(e,t,r)=>{let i=Object.assign(Object.create(null),e.projects??{},{[t]:r.name===void 0?{id:r.id}:r});return{...e,current:t,projects:i}},el=async(e,t,r)=>{_(e?.prompt,r);let i=(await e.prompt(t)).trim();return _(i.length>0,r),i};async function Af(e){let t=[];for await(let i of e.client.projects.listAll()){let n=e.context?.id===i.id?"*":" ",s=e.context?.id===i.id&&e.context.alias!==void 0?` ${e.context.alias}`:"";t.push(`${n} ${i.id} ${i.name}${s}`)}let r=t.length===0?"No projects visible.":t.join(`
40
- `);return e.io.stdout(r),{output:r}}async function kf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias??await el(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),i=me(e.projectId)??await el(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),n=_i(t.credentials.projects,r);_(n===void 0||n.id===i,`Alias ${r} already points at ${n?.id}. Run toloka project remove ${r} first.`),await e.afterPreflight?.();let s=await e.client.projects.get({projectId:i});await Gn(Tf(t.credentials,r,{id:s.id,name:s.name}),e.environment);let o=`Using project ${s.id} as ${r}.`;return e.io?.stdout(o),{output:o,alias:r,projectId:s.id}}async function Df(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias),i=_i(t.credentials.projects,r);_(i,`Unknown project alias ${r}.`),await Gn({...t.credentials,current:r},e.environment);let n=`Using project ${i.id} as ${r}.`;return e.io?.stdout(n),{output:n}}async function Nf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias),i=Object.assign(Object.create(null),t.credentials.projects??{});_(_i(i,r),`Unknown project alias ${r}.`),delete i[r];let n=t.credentials.current===r?void 0:t.credentials.current;await Gn({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...n===void 0?{}:{current:n},...Object.keys(i).length===0?{}:{projects:i}},e.environment);let s=`Removed local alias ${r}.`;return e.io?.stdout(s),{output:s}}function Lf(e){let t=Pi(e),r=t===void 0?Yx:tl(t,e.stored);return e.io?.stdout(r),t===void 0?{output:r}:{output:r,project:t}}var tR=(e)=>{let t=[...new Set(e.map((r)=>r.teamId))];return t.length===1?t[0]:void 0},rR=async(e,t)=>{let r=me(t);if(r!==void 0)return r;let i=[];for await(let s of e.projects.listAll())i.push(s);let n=tR(i);return _(n,"Missing team id. Pass --team-id. Visible projects do not share a single team, or none are visible."),n},iR=async(e,t,r,i)=>{if(t===void 0){try{await Nt(e,{projectId:r.id,pipelines:{},datasets:{}})}catch(n){let s=n instanceof Error?n.message:String(n);throw Error([`Created project ${r.id} as ${i}.`,`Failed to write toloka.json: ${s}`].join(`
41
- `),{cause:n})}return}if(t.projectId===r.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function qf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias??await el(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));_(t.credentials.projects?.[r]===void 0,`Alias ${r} already exists. Run toloka project remove ${r} first.`);let i=e.sourceRoot===void 0?void 0:await $e(e.sourceRoot);await e.afterPreflight?.();let n=await rR(e.client,e.teamId),s=await e.client.projects.create({teamId:n,name:me(e.name)??r});try{await Gn(Tf(t.credentials,r,{id:s.id,name:s.name}),e.environment)}catch(c){let u=c instanceof Error?c.message:String(c);throw Error([`Created ${s.id} but failed to update the local registry: ${u}`,`Run: toloka project add ${r} ${s.id}`].join(`
42
- `),{cause:c})}let o=[`Created project ${s.id} as ${r}.`];if(e.sourceRoot!==void 0){let c=await iR(e.sourceRoot,i,s,r);if(c!==void 0)o.push(c)}let a=o.join(`
43
- `);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var _r="https://platform.toloka.ai",nR=/^(?:prestable|pr-\d+)$/u,Lt=(e)=>{let t=e.ENV?.trim();if(t===void 0||!nR.test(t))return;return`https://${t}.platform.toloka-test.ai`},sR="https://console.toloka.ai",oR="https://prestable.console.toloka-test.ai",Mf=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return sR;if(t.endsWith(".platform.toloka-test.ai"))return oR;return},aR=["Missing API key. Run toloka login once to store credentials for this machine:",""," toloka login","","It explains how to generate an API key and where it is saved. To override per command,","pass --api-key or set POTATO_API_KEY. Run toloka auth-status to see what is in effect."].join(`
44
- `);function rl(e,t,r,i){let n=e.apiKey??r.POTATO_API_KEY??i?.apiKey,s=e.baseUrl??r.POTATO_BASE_URL??Lt(r)??i?.baseUrl??_r,o=Pi({flags:e,state:t,environment:r,stored:i,effectiveBaseUrl:s});return _(n,aR),{apiKey:n,baseUrl:s,...o===void 0?{}:{projectId:o.id}}}var lR=(e)=>{let t=Mf(e);return[...t===void 0?[`An API key identifies you to ${e}. Generate one in the console that`,"serves this platform, under Company -> API Keys -> Generate API Key."]:[`An API key identifies you to ${e}. To generate one:`,"",` 1. open ${t}`," 2. go to Company -> API Keys"," 3. press Generate API Key and copy it"],"","The key is shown once. Treat it like a password: it is stored with owner-only","permissions and never printed back to you."].join(`
45
- `)};async function Uf(e={}){let t=e.environment??process.env,r=e.write??(()=>{return}),i=(e.baseUrl??t.POTATO_BASE_URL??Lt(t)??_r).replace(/\/+$/u,""),n=e.apiKey;if(n===void 0)_(e.prompt,"Missing API key. Pass --api-key, or set POTATO_API_KEY, when stdin is not a terminal."),r(`
46
- ${lR(i)}
47
- `),n=(await e.prompt("API key: ",{mask:!0})).trim();_(n.length>0,"No API key entered.");let s={baseUrl:i,apiKey:n},o=e.probe?.(s)??nt(s),a;try{let p=await o.projects.listPage({limit:1});a=`Authenticated against ${i}: ${p.pagination.total} project(s) visible.`}catch(p){let f=p instanceof Error?p.message:String(p);throw Error([`Could not authenticate against ${i}: ${f}`,"","Nothing was saved. Check that the key was copied whole and has not been revoked."].join(`
48
- `),{cause:p})}let c=Ue(t),u=await qn(c),l=typeof u==="object"&&Et(u.credentials.baseUrl)===Et(i)?{baseUrl:i,apiKey:n,...u.credentials.current===void 0?{}:{current:u.credentials.current},...u.credentials.projects===void 0?{}:{projects:u.credentials.projects}}:s,d=await Mn(l,t);return{credentialsFile:d,baseUrl:i,output:[a,`Saved credentials to ${d}.`,"","toloka reads them automatically. --api-key and POTATO_API_KEY still win when set."].join(`
49
- `)}}async function Bf(e=process.env){let t=await jf(e);return{removed:t,output:t.length===0?`No stored credentials found at ${Ue(e)}.`:`Removed ${t.join(", ")}.
37
+ ${t}`,e)}}var qs="x-potato-sdk-base-url",Lc=(e,t,r)=>(_(e.length>0,"The SDK base URL cannot be empty"),_(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[qs]:new URL(e).toString()},fetch:r});async function C(e,t){let{fetch:r=globalThis.fetch,...i}=t,n=new Headers(i.headers),s=n.get(qs);_(s,"The SDK base URL is missing"),n.delete(qs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let c=a;if(a.length===0)c=void 0;else if(o.headers.get("content-type")?.includes("application/json"))c=JSON.parse(a);throw re.fromResponse(o.status,c)}return a.length===0?void 0:JSON.parse(a)}var $0=()=>"/api/v2-beta/me",qc=async(e)=>C($0(),{...e,method:"GET"}),E0=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([i,n])=>{if(n!==void 0)t.append(i,n===null?"null":n.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},Ms=async(e,t)=>C(E0(e),{...t,method:"GET"}),I0=()=>"/api/v2-beta/projects",Mc=async(e,t)=>C(I0(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),S0=(e)=>`/api/v2-beta/projects/${e}`,Uc=async(e,t)=>C(S0(e),{...t,method:"GET"}),x0=(e)=>`/api/v2-beta/projects/${e}`,Bc=async(e,t,r)=>C(x0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),R0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Us=async(e,t,r)=>C(R0(e,t),{...r,method:"GET"}),C0=(e)=>`/api/v2-beta/pipelines/${e}`,Gc=async(e,t)=>C(C0(e),{...t,method:"GET"}),j0=(e)=>`/api/v2-beta/pipelines/${e}`,Vc=async(e,t,r)=>C(j0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),F0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/datasets?${i}`:`/api/v2-beta/projects/${e}/datasets`},Bs=async(e,t,r)=>C(F0(e,t),{...r,method:"GET"}),O0=(e)=>`/api/v2-beta/projects/${e}/datasets`,Kc=async(e,t,r)=>C(O0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),T0=(e)=>`/api/v2-beta/datasets/${e}`,zc=async(e,t)=>C(T0(e),{...t,method:"GET"}),A0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/fields?${i}`:`/api/v2-beta/datasets/${e}/fields`},Gs=async(e,t,r)=>C(A0(e,t),{...r,method:"GET"}),k0=(e)=>`/api/v2-beta/datasets/${e}/fields`,Vs=async(e,t,r)=>C(k0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),D0=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,Wc=async(e,t)=>C(D0(e),{...t,method:"GET"}),N0=(e)=>`/api/v2-beta/datasets/${e}/items`,Hc=async(e,t,r)=>C(N0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),L0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/items?${i}`:`/api/v2-beta/datasets/${e}/items`},Ks=async(e,t,r)=>C(L0(e,t),{...r,method:"GET"}),q0=(e)=>`/api/v2-beta/datasets/${e}/uploads`,Jc=async(e,t,r)=>C(q0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),M0=(e)=>`/api/v2-beta/uploads/${e}/finalize`,Qc=async(e,t)=>C(M0(e),{...t,method:"POST"}),U0=(e)=>`/api/v2-beta/uploads/${e}`,zs=async(e,t)=>C(U0(e),{...t,method:"GET"}),B0=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,Yc=async(e,t,r)=>C(B0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),G0=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,Xc=async(e,t,r)=>C(G0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),V0=(e)=>`/api/v2-beta/pipelines/${e}/export`,Zc=async(e,t)=>C(V0(e),{...t,method:"GET"}),K0=(e)=>`/api/v2-beta/pipelines/${e}/copy`,ed=async(e,t,r)=>C(K0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),z0=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,td=async(e,t,r)=>C(z0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),W0=(e)=>`/api/v2-beta/pipelines/${e}/runs`,rd=async(e,t)=>C(W0(e),{...t,method:"POST"}),H0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},Ws=async(e,t,r)=>C(H0(e,t),{...r,method:"GET"}),J0=(e)=>`/api/v2-beta/runs/${e}`,Hs=async(e,t)=>C(J0(e),{...t,method:"GET"}),Q0=(e)=>`/api/v2-beta/runs/${e}/cancel`,id=async(e,t)=>C(Q0(e),{...t,method:"POST"}),Y0=(e)=>`/api/v2-beta/datasets/${e}/exports`,nd=async(e,t,r)=>C(Y0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),X0=(e)=>`/api/v2-beta/exports/${e}`,Js=async(e,t)=>C(X0(e),{...t,method:"GET"}),Z0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,sd=async(e,t)=>C(Z0(e),{...t,method:"GET"}),ev=(e)=>`/api/v2-beta/pipelines/${e}/graph`,od=async(e,t,r)=>C(ev(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),tv=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,ad=async(e,t,r)=>C(tv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),rv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,ld=async(e,t,r,i)=>C(rv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),iv=(e)=>`/api/v2-beta/projects/${e}/secrets`,cd=async(e,t)=>C(iv(e),{...t,method:"GET"}),nv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,dd=async(e,t,r,i)=>C(nv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),sv=(e)=>`/api/v2-beta/projects/${e}/files`,ud=async(e,t)=>C(sv(e),{...t,method:"GET"}),ov=(e)=>`/api/v2-beta/projects/${e}/files`,pd=async(e,t,r)=>C(ov(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),av=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,fd=async(e,t,r)=>C(av(e,t),{...r,method:"POST"}),lv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,md=async(e,t,r)=>C(lv(e,t),{...r,method:"DELETE"}),cv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/runs/${e}/items?${i}`:`/api/v2-beta/runs/${e}/items`},Qs=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,hd=async(e,t,r)=>C(dv(e,t),{...r,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,gd=async(e,t)=>C(uv(e),{...t,method:"GET"}),pv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,yd=async(e,t,r)=>C(pv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),fv=(e)=>`/api/v2-beta/checks/${e}`,Ys=async(e,t)=>C(fv(e),{...t,method:"GET"});async function*mt(e,t={}){let r=t.offset;while(!0){let i=await e({limit:t.limit,offset:r});if(yield*i.items,!i.pagination.hasMore)return;r=i.pagination.offset+i.pagination.limit}}var Gr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;_(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),_(Number.isFinite(n)&&n>0,"The polling interval must be a positive finite number");let s=Date.now()+i,o=new AbortController,a=setTimeout(()=>o.abort(),i);try{while(!0){if(o.signal.aborted)throw re.waitTimeout(i);let c=await e(o.signal);if(t(c))return c;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:d}=Promise.withResolvers();setTimeout(d,Math.min(n,u)),await l}}catch(c){if(o.signal.aborted)throw re.waitTimeout(i);throw c}finally{clearTimeout(a)}};var hv=(e)=>{let t=Lc(e.baseUrl,e.apiKey,e.fetch);async function r(l,d){switch(l.type){case"datasetUpload":return Gr((p)=>zs(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"datasetExport":return Gr((p)=>Js(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",d);case"pipelineCheck":return Gr((p)=>Ys(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"pipelineRun":return Gr((p)=>Hs(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d)}}return{me:()=>qc(t),projects:{create:(l)=>Mc(l,t),get:({projectId:l})=>Uc(l,t),update:({projectId:l,...d})=>Bc(l,d,t),listPage:(l={})=>Ms(l,t),listAll:(l={})=>mt(async(d)=>{let p=await Ms({...l,...d},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...d})=>Yc(l,d,t),get:({pipelineId:l})=>Gc(l,t),update:({pipelineId:l,...d})=>Vc(l,d,t),listPage:({projectId:l,...d})=>Us(l,d,t),listAll:({projectId:l,...d})=>mt(async(p)=>{let f=await Us(l,{...d,...p},t);return{items:f.pipelines,pagination:f.pagination}},d),getGraph:({pipelineId:l})=>sd(l,t),replaceGraph:({pipelineId:l,...d})=>od(l,"version"in d?{graph:d.graph,expectedVersion:d.version}:d,t),validateGraph:({pipelineId:l,...d})=>ad(l,d,t),estimateCost:({pipelineId:l,...d})=>td(l,d,t),patchNode:({pipelineId:l,nodeId:d,...p})=>ld(l,d,p,t),attachDataset:({pipelineId:l,...d})=>Xc(l,d,t),export:({pipelineId:l})=>Zc(l,t),copy:({pipelineId:l,...d})=>ed(l,d,t)},datasets:{create:({projectId:l,...d})=>Kc(l,d,t),get:({datasetId:l})=>zc(l,t),listPage:({projectId:l,...d})=>Bs(l,d,t),listAll:({projectId:l,...d})=>mt(async(p)=>{let f=await Bs(l,{...d,...p},t);return{items:f.datasets,pagination:f.pagination}},d),createField:async({datasetId:l,...d})=>{let p=await Vs(l,d,t);return _(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:d})=>{let p=await Vs(l,{fields:d},t);return _("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...d})=>Gs(l,d,t),getInferredFields:({datasetId:l})=>Wc(l,t),listAllFields:({datasetId:l,...d})=>mt(async(p)=>{let f=await Gs(l,{...d,...p},t);return{items:f.fields,pagination:f.pagination}},d),appendItems:({datasetId:l,...d})=>Hc(l,d,t),listItemsPage:({datasetId:l,...d})=>Ks(l,d,t),listAllItems:({datasetId:l,...d})=>mt(async(p)=>{let f=await Ks(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),startUpload:({datasetId:l,...d})=>Jc(l,d,t),finalizeUpload:({uploadId:l})=>Qc(l,t),getUpload:({uploadId:l})=>zs(l,t),startExport:({datasetId:l,...d})=>nd(l,d,t),getExport:({exportId:l})=>Js(l,t)},runs:{start:({pipelineId:l})=>{let d=new Headers(t.headers);return d.set("Content-Type","application/json"),rd(l,{...t,headers:d,body:"{}"})},get:({runId:l})=>Hs(l,t),cancel:({runId:l})=>id(l,t),listPage:({pipelineId:l,...d})=>Ws(l,d,t),listAll:({pipelineId:l,...d})=>mt(async(p)=>{let f=await Ws(l,{...d,...p},t);return{items:f.runs,pagination:f.pagination}},d),listItemsPage:({runId:l,...d})=>Qs(l,d,t),listAllItems:({runId:l,...d})=>mt(async(p)=>{let f=await Qs(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),getItem:({runId:l,itemId:d})=>hd(l,d,t)},secrets:{list:async({projectId:l})=>(await cd(l,t)).secrets,set:({projectId:l,name:d,...p})=>dd(l,d,p,t)},files:{list:async({projectId:l})=>(await ud(l,t)).files,startUpload:({projectId:l,...d})=>pd(l,d,t),finalizeUpload:({projectId:l,fileId:d})=>fd(l,d,t),delete:({projectId:l,fileId:d})=>md(l,d,t)},checks:{list:async({pipelineId:l})=>(await gd(l,t)).checks,start:({pipelineId:l,...d})=>yd(l,d,t),get:({checkRunId:l})=>Ys(l,t)},waitFor:r}};function it(e){return hv(e)}var gr=require("fs/promises"),Qa=require("path"),$f=xe(Ja(),1);var Nn="toloka.json";class Ya extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var Mx="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",Ux={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:Mx},additionalProperties:{type:"object",properties:{pipelineId:{type:"string",minLength:1}},required:["pipelineId"],additionalProperties:!1}},datasets:{type:"object",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",properties:{datasetId:{type:"string",minLength:1}},required:["datasetId"],additionalProperties:!1}}},required:["projectId","pipelines","datasets"],additionalProperties:!1},Bx=new $f.default({allErrors:!0,strict:!1}),wf=Bx.compile(Ux);function Gx(e){let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return`${typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/"}: ${e.message??`failed ${e.keyword} validation`}`}function Ef(e){if(wf(e))return e;let t=wf.errors;throw _(t,"toloka.json validation failed without errors"),new Ya(`Invalid toloka.json: ${t.map(Gx).join("; ")}`)}async function $e(e){let t;try{t=await gr.readFile(Qa.join(e,Nn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Ef(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new Ya(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Nt(e,t){let r=Ef(t),i=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),n=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await gr.mkdir(e,{recursive:!0}),await gr.writeFile(Qa.join(e,Nn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
38
+ `,"utf8")}var fe=require("fs/promises"),xf=require("os"),yr=require("path");class gi extends Error{constructor(e,t){super(e,t);this.name="CredentialsError"}}var Rf=(e)=>e.HOME??xf.homedir(),Vx=(e)=>e.XDG_CONFIG_HOME??yr.join(Rf(e),".config"),Ue=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??yr.join(Vx(e),"toloka","credentials.json"),Cf=(e=process.env)=>yr.join(Rf(e),".toloka","credentials.json"),If=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},at=(e)=>{let t=If(e.trim());try{let r=new URL(t);return r.hash="",r.search="",If(r.toString())}catch{return t}},Ln=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,Kx=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let r=Reflect.get(e,"name");if(r!==void 0&&typeof r!=="string")return;return r===void 0?{id:t}:{id:t,name:r}},zx=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[r,i]of Object.entries(e)){if(r.length===0)return;let n=Kx(i);if(n===void 0)return;Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}return t},Wx=(e,t)=>{let r=zx(e);if(r===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(r,t))return;return{current:t,projects:r}}if(t!==void 0)return;return Object.keys(r).length===0?{}:{projects:r}},Hx=(e)=>{let t=Ln(e,"baseUrl"),r=Ln(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(typeof r!=="string"||r.length===0)return;let i=Ln(e,"current"),n=Ln(e,"projects");if(i===void 0&&n===void 0)return{baseUrl:t,apiKey:r};let s=Wx(n,i);if(s===void 0)return;return{baseUrl:t,apiKey:r,...s}};async function qn(e){let t;try{t=await fe.readFile(e,"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"missing";return"invalid"}try{let r=Hx(JSON.parse(t));return r===void 0?"invalid":{credentials:r}}catch{return"invalid"}}async function Xa(e=process.env){let t=Ue(e),r=await qn(t);if(r!=="missing"){if(r==="invalid")throw new gi(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`);return{credentials:r.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let i=Cf(e),n=await qn(i);if(n==="missing")return;if(n==="invalid")throw new gi(`Invalid credentials file at ${i}. Run toloka logout, then toloka login.`);return{credentials:n.credentials,path:i,legacy:!0}}async function yi(e,t){try{return{found:await Xa(e)}}catch(r){if(!(r instanceof gi)||t===void 0)throw r;return{found:void 0,warning:r.message}}}async function jf(e=process.env){return(await Xa(e))?.credentials}async function It(e=process.env){let t=await Xa(e);if(t!==void 0)return t;throw new gi(`No stored credentials found at ${Ue(e)}. Run toloka login.`)}var Jx=(e)=>{let t=e.projects,r=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,apiKey:e.apiKey,...e.current===void 0?{}:{current:e.current},...r?{projects:t}:{}}},Sf=async(e)=>{try{let t=await fe.lstat(e);_(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function Za(e){let t=yr.dirname(e);await Sf(t),await Sf(e),await fe.mkdir(t,{recursive:!0,mode:448}),await fe.chmod(t,448)}async function Mn(e,t=process.env){let r=Ue(t);return await Za(r),await fe.writeFile(r,`${JSON.stringify(Jx(e),null,2)}
39
+ `,{mode:384}),await fe.chmod(r,384),r}var Qx=async(e)=>{try{return await fe.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}};async function Ff(e=process.env){let t=[],r=[Ue(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Cf(e)]:[]];for(let i of r){if(!await Qx(i))continue;await fe.rm(i,{force:!0}),t.push(i)}return t}var Yx=16,Of=(e)=>e.length>Yx?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var he="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, set projectId in toloka.json, or run toloka project add.",Xx="No project selected. Run toloka project add, or cd into a checkout.",Tf="project add writes the machine registry; unset --api-key / --base-url / POTATO_API_KEY / POTATO_BASE_URL, or run login against that platform first.",Zx=/^[^/\s]+$/u,Un=(e)=>{let t=e.trim();return _(t.length>0&&Zx.test(t),"Project alias must be non-empty and contain no / or whitespace."),t},me=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},eR=(e,t,r)=>me(e?.baseUrl)??me(t?.POTATO_BASE_URL)??Lt(t??{})??me(r?.baseUrl),_i=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,tR=(e,t,r)=>{if(!r||t?.projects===void 0)return{};if(t.current!==void 0){let i=_i(t.projects,t.current);if(i?.id===e)return i.name===void 0?{alias:t.current}:{alias:t.current,name:i.name}}for(let i of Object.keys(t.projects).toSorted()){let n=_i(t.projects,i);if(n?.id!==e)continue;return n.name===void 0?{alias:i}:{alias:i,name:n.name}}return{}};function Pi(e={}){let t=e.flags??{},r=e.environment??{},i=e.stored,n=e.effectiveBaseUrl??eR(t,r,i),s=i!==void 0&&n!==void 0&&at(n)===at(i.baseUrl),a=[{id:me(t.projectId),source:"flag"},{id:me(r.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:me(r.POTATO_PROJECT_ID),source:"potato-project-id"},{id:me(e.state?.projectId),source:"toloka.json"},{id:s&&i.current!==void 0?me(i.projects?.[i.current]?.id):void 0,source:"registry"}].find((c)=>c.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...tR(a.id,i,s)}}var tl=(e,t)=>{if(e===void 0)return"Project: (none). Run toloka project add.";let r=e.alias===void 0?"":`alias ${e.alias}, `,i=e.source!=="registry"&&t?.current!==void 0?`; registry current is ${t.current}`:"";return`Project: ${e.id} (${r}from ${e.source}${i})`},Bn=(e,t,r)=>{let i=me(e.apiKey)??me(t.POTATO_API_KEY),n=me(e.baseUrl)??me(t.POTATO_BASE_URL)??Lt(t);_(i===void 0||i===r.apiKey,Tf),_(n===void 0||at(n)===at(r.baseUrl),Tf)},Gn=async(e,t)=>{await Mn(e,t)},Af=(e,t,r)=>{let i=Object.assign(Object.create(null),e.projects??{},{[t]:r.name===void 0?{id:r.id}:r});return{...e,current:t,projects:i}},el=async(e,t,r)=>{_(e?.prompt,r);let i=(await e.prompt(t)).trim();return _(i.length>0,r),i};async function kf(e){let t=[];for await(let i of e.client.projects.listAll()){let n=e.context?.id===i.id?"*":" ",s=e.context?.id===i.id&&e.context.alias!==void 0?` ${e.context.alias}`:"";t.push(`${n} ${i.id} ${i.name}${s}`)}let r=t.length===0?"No projects visible.":t.join(`
40
+ `);return e.io.stdout(r),{output:r}}async function Df(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias??await el(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),i=me(e.projectId)??await el(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),n=_i(t.credentials.projects,r);_(n===void 0||n.id===i,`Alias ${r} already points at ${n?.id}. Run toloka project remove ${r} first.`),await e.afterPreflight?.();let s=await e.client.projects.get({projectId:i});await Gn(Af(t.credentials,r,{id:s.id,name:s.name}),e.environment);let o=`Using project ${s.id} as ${r}.`;return e.io?.stdout(o),{output:o,alias:r,projectId:s.id}}async function Nf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias),i=_i(t.credentials.projects,r);_(i,`Unknown project alias ${r}.`),await Gn({...t.credentials,current:r},e.environment);let n=`Using project ${i.id} as ${r}.`;return e.io?.stdout(n),{output:n}}async function Lf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias),i=Object.assign(Object.create(null),t.credentials.projects??{});_(_i(i,r),`Unknown project alias ${r}.`),delete i[r];let n=t.credentials.current===r?void 0:t.credentials.current;await Gn({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...n===void 0?{}:{current:n},...Object.keys(i).length===0?{}:{projects:i}},e.environment);let s=`Removed local alias ${r}.`;return e.io?.stdout(s),{output:s}}function qf(e){let t=Pi(e),r=t===void 0?Xx:tl(t,e.stored);return e.io?.stdout(r),t===void 0?{output:r}:{output:r,project:t}}var rR=(e)=>{let t=[...new Set(e.map((r)=>r.teamId))];return t.length===1?t[0]:void 0},iR=async(e,t)=>{let r=me(t);if(r!==void 0)return r;let i=[];for await(let s of e.projects.listAll())i.push(s);let n=rR(i);return _(n,"Missing team id. Pass --team-id. Visible projects do not share a single team, or none are visible."),n},nR=async(e,t,r,i)=>{if(t===void 0){try{await Nt(e,{projectId:r.id,pipelines:{},datasets:{}})}catch(n){let s=n instanceof Error?n.message:String(n);throw Error([`Created project ${r.id} as ${i}.`,`Failed to write toloka.json: ${s}`].join(`
41
+ `),{cause:n})}return}if(t.projectId===r.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function Mf(e){let t=await It(e.environment);Bn(e.flags??{},e.environment,t.credentials);let r=Un(e.alias??await el(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));_(t.credentials.projects?.[r]===void 0,`Alias ${r} already exists. Run toloka project remove ${r} first.`);let i=e.sourceRoot===void 0?void 0:await $e(e.sourceRoot);await e.afterPreflight?.();let n=await iR(e.client,e.teamId),s=await e.client.projects.create({teamId:n,name:me(e.name)??r});try{await Gn(Af(t.credentials,r,{id:s.id,name:s.name}),e.environment)}catch(c){let u=c instanceof Error?c.message:String(c);throw Error([`Created ${s.id} but failed to update the local registry: ${u}`,`Run: toloka project add ${r} ${s.id}`].join(`
42
+ `),{cause:c})}let o=[`Created project ${s.id} as ${r}.`];if(e.sourceRoot!==void 0){let c=await nR(e.sourceRoot,i,s,r);if(c!==void 0)o.push(c)}let a=o.join(`
43
+ `);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var _r="https://platform.toloka.ai",sR=/^(?:prestable|pr-\d+)$/u,Lt=(e)=>{let t=e.ENV?.trim();if(t===void 0||!sR.test(t))return;return`https://${t}.platform.toloka-test.ai`},oR="https://console.toloka.ai",aR="https://prestable.console.toloka-test.ai",Uf=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return oR;if(t.endsWith(".platform.toloka-test.ai"))return aR;return},lR=["Missing API key. Run toloka login once to store credentials for this machine:",""," toloka login","","It explains how to generate an API key and where it is saved. To override per command,","pass --api-key or set POTATO_API_KEY. Run toloka auth-status to see what is in effect."].join(`
44
+ `);function rl(e,t,r,i){let n=e.apiKey??r.POTATO_API_KEY??i?.apiKey,s=e.baseUrl??r.POTATO_BASE_URL??Lt(r)??i?.baseUrl??_r,o=Pi({flags:e,state:t,environment:r,stored:i,effectiveBaseUrl:s});return _(n,lR),{apiKey:n,baseUrl:s,...o===void 0?{}:{projectId:o.id}}}var cR=(e)=>{let t=Uf(e);return[...t===void 0?[`An API key identifies you to ${e}. Generate one in the console that`,"serves this platform, under Company -> API Keys -> Generate API Key."]:[`An API key identifies you to ${e}. To generate one:`,"",` 1. open ${t}`," 2. go to Company -> API Keys"," 3. press Generate API Key and copy it"],"","The key is shown once. Treat it like a password: it is stored with owner-only","permissions and never printed back to you."].join(`
45
+ `)};async function Bf(e={}){let t=e.environment??process.env,r=e.write??(()=>{return}),i=at(e.baseUrl??t.POTATO_BASE_URL??Lt(t)??_r),n=e.apiKey;if(n===void 0)_(e.prompt,"Missing API key. Pass --api-key, or set POTATO_API_KEY, when stdin is not a terminal."),r(`
46
+ ${cR(i)}
47
+ `),n=(await e.prompt("API key: ",{mask:!0})).trim();_(n.length>0,"No API key entered.");let s={baseUrl:i,apiKey:n},o=e.probe?.(s)??it(s),a;try{let p=await o.projects.listPage({limit:1});a=`Authenticated against ${i}: ${p.pagination.total} project(s) visible.`}catch(p){let f=p instanceof Error?p.message:String(p);throw Error([`Could not authenticate against ${i}: ${f}`,"","Nothing was saved. Check that the key was copied whole and has not been revoked."].join(`
48
+ `),{cause:p})}let c=Ue(t),u=await qn(c),l=typeof u==="object"&&at(u.credentials.baseUrl)===at(i)?{baseUrl:i,apiKey:n,...u.credentials.current===void 0?{}:{current:u.credentials.current},...u.credentials.projects===void 0?{}:{projects:u.credentials.projects}}:s,d=await Mn(l,t);return{credentialsFile:d,baseUrl:i,output:[a,`Saved credentials to ${d}.`,"","toloka reads them automatically. --api-key and POTATO_API_KEY still win when set."].join(`
49
+ `)}}async function Gf(e=process.env){let t=await Ff(e);return{removed:t,output:t.length===0?`No stored credentials found at ${Ue(e)}.`:`Removed ${t.join(", ")}.
50
50
 
51
- This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var Gf=(e)=>e.find((t)=>t!==void 0),cR=(e,t,r,i)=>Gf([e.flagApiKey===void 0?void 0:{value:e.flagApiKey,source:"from --api-key"},t.POTATO_API_KEY===void 0?void 0:{value:t.POTATO_API_KEY,source:"from POTATO_API_KEY"},r===void 0?void 0:{value:r.credentials.apiKey,source:`stored in ${i}`}]),dR=(e,t,r)=>{let i=Lt(t);return Gf([e.flagBaseUrl===void 0?void 0:{value:e.flagBaseUrl.replace(/\/+$/u,""),source:"from --base-url"},t.POTATO_BASE_URL===void 0?void 0:{value:t.POTATO_BASE_URL,source:"from POTATO_BASE_URL"},i===void 0?void 0:{value:i,source:`from ENV=${t.ENV}`},r===void 0?void 0:{value:r.credentials.baseUrl,source:"stored"}])??{value:_r,source:"default"}};async function Vf(e={}){let t=e.environment??process.env,r=e.credentialLookup??await yi(t,e.flagApiKey??t.POTATO_API_KEY),{found:i,warning:n}=r,s=i?.path??Ue(t),o=cR(e,t,i,s),a=dR(e,t,i),c=tl(e.project,i?.credentials),u=n===void 0?[]:[n,""];if(o===void 0)return u.push("Not logged in.","","Run toloka login to store an API key for this machine.","",c),{authenticated:!1,output:u.join(`
52
- `)};let{value:l,source:d}=a;if(u.push(`Platform: ${l} (${d})`,`API key: ${e.showToken===!0?o.value:Ff(o.value)} (${o.source})`,c),t.POTATO_API_KEY!==void 0&&i!==void 0)u.push("",`POTATO_API_KEY is set, so the key stored in ${i.path} is ignored.`);if(i?.legacy===!0)u.push("",`Credentials still live at the old path ${i.path}. Run toloka login to move them to ${Ue(t)}.`);let p=e.probe?.({baseUrl:l,apiKey:o.value})??nt({baseUrl:l,apiKey:o.value});try{let f=await p.projects.listPage({limit:1});return u.push("",`Reachable: ${f.pagination.total} project(s) visible.`),{authenticated:!0,output:u.join(`
51
+ This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var Vf=(e)=>e.find((t)=>t!==void 0),dR=(e,t,r,i)=>Vf([e.flagApiKey===void 0?void 0:{value:e.flagApiKey,source:"from --api-key"},t.POTATO_API_KEY===void 0?void 0:{value:t.POTATO_API_KEY,source:"from POTATO_API_KEY"},r===void 0?void 0:{value:r.credentials.apiKey,source:`stored in ${i}`}]),uR=(e,t,r)=>{let i=Lt(t);return Vf([e.flagBaseUrl===void 0?void 0:{value:e.flagBaseUrl.replace(/\/+$/u,""),source:"from --base-url"},t.POTATO_BASE_URL===void 0?void 0:{value:t.POTATO_BASE_URL,source:"from POTATO_BASE_URL"},i===void 0?void 0:{value:i,source:`from ENV=${t.ENV}`},r===void 0?void 0:{value:r.credentials.baseUrl,source:"stored"}])??{value:_r,source:"default"}};async function Kf(e={}){let t=e.environment??process.env,r=e.credentialLookup??await yi(t,e.flagApiKey??t.POTATO_API_KEY),{found:i,warning:n}=r,s=i?.path??Ue(t),o=dR(e,t,i,s),a=uR(e,t,i),c=tl(e.project,i?.credentials),u=n===void 0?[]:[n,""];if(o===void 0)return u.push("Not logged in.","","Run toloka login to store an API key for this machine.","",c),{authenticated:!1,output:u.join(`
52
+ `)};let{value:l,source:d}=a;if(u.push(`Platform: ${l} (${d})`,`API key: ${e.showToken===!0?o.value:Of(o.value)} (${o.source})`,c),t.POTATO_API_KEY!==void 0&&i!==void 0)u.push("",`POTATO_API_KEY is set, so the key stored in ${i.path} is ignored.`);if(i?.legacy===!0)u.push("",`Credentials still live at the old path ${i.path}. Run toloka login to move them to ${Ue(t)}.`);let p=e.probe?.({baseUrl:l,apiKey:o.value})??it({baseUrl:l,apiKey:o.value});try{let f=await p.projects.listPage({limit:1});return u.push("",`Reachable: ${f.pagination.total} project(s) visible.`),{authenticated:!0,output:u.join(`
53
53
  `)}}catch(f){let m=f instanceof Error?f.message:String(f);return u.push("",`Not reachable: ${m}`,"","Run toloka login to store a working key."),{authenticated:!1,output:u.join(`
54
- `)}}}var Th=require("crypto"),zt=require("fs/promises"),_s=require("path");var Pr=require("path");function zf(){let e=uR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function uR(e=process.argv[1]?Pr.dirname(process.argv[1]):process.cwd(),t=Pr.sep==="\\"){let r=t?Kf(e):e;return(i)=>{if(!i)return;let n=t?Kf(i):i,{dir:s,base:o,ext:a}=Pr.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let c=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${c}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function Kf(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var il=(e)=>{if("flags"in e){let t=Wf(e.flags),r=Hf(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Vn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,pR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function pR(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Wf=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,bi(r)]).filter(([,t])=>t!==void 0)),Hf=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map((r)=>{let i=t[r].metadata?.payload;return[r,i?Vn(i):void 0]}))},bi=(e)=>e===void 0?void 0:e.variant??e.enabled,Vn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var fR=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],vi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return fR.forEach(i),t.forEach(i),r};var Ee=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function nl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var hR="NativeGzipValidationError",gR=31,yR=139,_R=8,PR=(e)=>e.length>=2&&e[0]===gR&&e[1]===yR;var wi,bR=()=>{if(wi)return wi;wi=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;wi[e]=t>>>0}return wi},vR=(e)=>{let t=bR(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Kn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=hR,t},wR=async(e,t)=>{if(e.size<18)Kn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!PR(r)||r[2]!==_R)Kn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==vR(t))Kn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Kn("invalid-size")};async function qt(e,t=!0,r){try{let i=new TextEncoder().encode(e),n=new globalThis.CompressionStream("gzip"),s=n.writable.getWriter(),o=s.write(i).then(()=>s.close()).catch(async(u)=>{try{await s.abort(u)}catch{}throw u}),a=new Response(n.readable).blob(),[c]=await Promise.all([a,o]);return await wR(c,i),c}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var $R=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Jf=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return $R.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function br(e){let t=[];return JSON.stringify(e,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i=="function"||typeof i=="symbol")return;if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i})??"null"}var IR=Array.isArray,Qf=Object.prototype,dD=Qf.hasOwnProperty,zn=Qf.toString,He=IR||function(e){return zn.call(e)==="[object Array]"};var $i=(e)=>e===Object(e)&&!He(e);var Mt=(e)=>e===void 0,lt=(e)=>zn.call(e)=="[object String]",Yf=(e)=>lt(e)&&e.trim().length===0,Xf=(e)=>e===null;var Ei=(e)=>zn.call(e)=="[object Number]"&&e===e;var Zf=(e)=>zn.call(e)==="[object Boolean]";var em=(e)=>e instanceof Error;function Wn(e){return e===null||typeof e!="object"}function Ut(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function tm(e){return Ut(e,"ErrorEvent")}function vr(e){return typeof Event<"u"&&SR(e,Event)}function rm(e){return Ut(e,"Object")}function SR(e,t){try{return e instanceof t}catch{return!1}}function Ii(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ei(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return i.warn(" cannot be less than min: "+t+". Using min value instead."),t}return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),Ii(n||r,t,r,i)}var xR=86400000,RR=1,CR=10;function im(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??RR,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??CR}}class sl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ii(e.bucketSize,0,100,e._logger),this._refillRate=Ii(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ii(e.refillInterval,0,xR,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,i=Math.floor(r/this._refillInterval);if(i>0){let n=i*this._refillRate;e.tokens=Math.min(e.tokens+n,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];if(i)this._applyRefill(i,t);else i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i;if(i.tokens===0)return!0;if(i.tokens--,i.tokens===0)this._onBucketRateLimited?.(e);return i.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Bt{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Bt(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>281474976710655||t>4095||r>1073741823||i>4294967295)throw RangeError("invalid field value");let n=new Uint8Array(16);return n[0]=e/1099511627776,n[1]=e/4294967296,n[2]=e/16777216,n[3]=e/65536,n[4]=e/256,n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new Bt(n)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let r=new Uint8Array(16);for(let i=0;i<16;i+=4){let n=parseInt(t.substring(2*i,2*i+8),16);r[i+0]=n>>>24,r[i+1]=n>>>16,r[i+2]=n>>>8,r[i+3]=n}return new Bt(r)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Bt(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class sm{constructor(e){this.timestamp=0,this.counter=0,this.random=e??jR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Bt.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Bt.ofInner(e)}}var jR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),nm,Ie=()=>FR().toString(),FR=()=>(nm||(nm=new sm)).generate();class ol{add(e){let t=Ie(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((i)=>i.id<=t&&!r.has(i.promise)).map((i)=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function OR(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var om=(e,t,r)=>{function i(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{i("debug",...s)},info:(...s)=>{i("log",...s)},warn:(...s)=>{i("warn",...s)},error:(...s)=>{i("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>om(`${e} ${s}`,t,r)}},TR=(e)=>e();function am(e,t=TR){return om(e,t,OR())}var $r="Mobile",Jn="iOS",wr="Android",pm="Tablet",wD=wr+" "+pm;var kR="Apple",$D=kR+" Watch",fm="Safari",Qn="BlackBerry",mm="Samsung",DR=mm+"Browser",NR=mm+" Internet",Yn="Chrome",LR=Yn+" OS",qR=Yn+" "+Jn,hm="Internet Explorer",MR=hm+" "+$r,ll="Opera",ED=ll+" Mini",gm="Edge",UR="Microsoft "+gm,cl="Firefox",BR=cl+" "+Jn,dl="Nintendo",ul="PlayStation",Hn="Xbox",GR=wr+" "+$r,VR=$r+" "+fm,Si="Windows",KR=Si+" Phone";var ym="Generic",ID=ym+" "+$r.toLowerCase(),SD=ym+" "+pm.toLowerCase(),zR="Konqueror",WR="Oculus Browser",lm="Vivaldi",HR="Yandex",cm="Whale",JR="DuckDuckGo",QR="Pale Moon",dm="Waterfox",um="Brave",YR="Google Search App",H="(\\d+(\\.\\d+)?)",al=new RegExp("Version/"+H);var xD=new RegExp(Hn,"i"),RD=new RegExp(ul+" \\w+","i"),CD=new RegExp(dl+" \\w+","i"),XR=new RegExp(Qn+"|PlayBook|BB10","i"),ZR={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var jD={[MR]:[new RegExp("rv:"+H)],[UR]:[new RegExp(gm+"?\\/"+H)],[Yn]:[new RegExp("("+Yn+"|CrMo)\\/"+H)],[qR]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[fm]:[al],[VR]:[al],[ll]:[new RegExp("("+ll+"|OPR)\\/"+H)],[cl]:[new RegExp(cl+"\\/"+H)],[BR]:[new RegExp("FxiOS\\/"+H)],[zR]:[new RegExp("Konqueror[:/]?"+H,"i")],[Qn]:[new RegExp(Qn+" "+H),al],[GR]:[new RegExp("android\\s"+H,"i")],[NR]:[new RegExp(DR+"\\/"+H)],[WR]:[new RegExp("OculusBrowser\\/"+H)],[lm]:[new RegExp(lm+"\\/"+H)],[HR]:[new RegExp("YaBrowser\\/"+H)],[cm]:[new RegExp(cm+"\\/"+H)],[um]:[new RegExp(um+"\\/"+H)],[JR]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[QR]:[new RegExp("PaleMoon\\/"+H)],[dm]:[new RegExp(dm+"\\/"+H)],[YR]:[new RegExp("GSA\\/"+H)],[hm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var FD=[[new RegExp(Hn+"; "+Hn+" (.*?)[);]","i"),(e)=>[Hn,e&&e[1]||""]],[new RegExp(dl,"i"),[dl,""]],[new RegExp(ul,"i"),[ul,""]],[XR,[Qn,""]],[new RegExp(Si,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[KR,""];if(new RegExp($r).test(t)&&!/IEMobile\b/.test(t))return[Si+" "+$r,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=ZR[i]||"";if(/arm/i.test(t))n="RT";return[Si,n]}return[Si,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Jn,t.join(".")]}return[Jn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=Mt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+wr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[wr,t.join(".")]}return[wr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[LR,""]],[/Linux|debian/i,["Linux",""]]];var _m="utf8",eC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function tC(e){return typeof e=="string"&&eC.test(e)}function Xn(e,t){return tC(e)?e:t()}function Pm(e){return e?.replace(/\/+$/,"")}async function bm(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){if(i>0)await new Promise((n)=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function pl(){return new Date().toISOString()}function de(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var vm=(e)=>e instanceof Error;function fl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var iC={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},GD=iC.info;function ml(e){if(Zf(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(He(e))return{arrayValue:{values:e.map((t)=>ml(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function xi(e){let t=[];for(let r in e){let i=e[r];if(!(Xf(i)||Mt(i)))t.push({key:r,value:ml(i)})}return t}var Ri=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function hl(e){return String(e)+"000000"}function gl(e,t,r,i){let n="";if(i)n=Object.keys(i).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(i[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${n}`}function wm(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function yl(e,t,r){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}function _l(e,t,r,i){return{resourceMetrics:[{resource:{attributes:xi(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function Zn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var $m=1;class es{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,i;try{r=t.attributes?{...t.attributes}:void 0,i=gl(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let n=this._series.get(i);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(i,n)}let s=this._typeByName.get(t.name);if(s===void 0)this._typeByName.set(t.name,t.type);else if(s!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(n,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(Ri.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[wm(t,Ri)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=He(t)?t:[t],i=e;for(let n of r)try{let s=n(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=de(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){return _l(this._buildMetrics(e),yl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=hl(Date.now()),r=new Map;for(let i of e.values()){let n=gl(i.type,i.name,i.unit,void 0),s=r.get(n);if(!s){if(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count")s.sum={aggregationTemporality:$m,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:$m,dataPoints:[]};r.set(n,s)}let o=xi(i.attributes??{}),a=hl(i.windowStartMs);if(i.type==="count"){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(c)}else if(i.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(c)}else if(i.hist){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ri};s.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let i=this._series.get(t);if(!i){if(this._admitNewSeries())this._series.set(t,r);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,r.windowStartMs),i.type){case"count":i.total=(i.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(i.hist){i.hist.count+=r.hist.count,i.hist.sum+=r.hist.sum,i.hist.min=Math.min(i.hist.min,r.hist.min),i.hist.max=Math.max(i.hist.max,r.hist.max);for(let n=0;n<i.hist.bucketCounts.length;n++)i.hist.bucketCounts[n]+=r.hist.bucketCounts[n]}else i.hist=r.hist;break}}}}class Pl{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}var ve={};s_(ve,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ds,DOMExceptionCoercer:()=>km,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ci,ErrorCoercer:()=>ss,ErrorEventCoercer:()=>Dm,ErrorPropertiesBuilder:()=>is,EventCoercer:()=>Lm,ExceptionStepsBuffer:()=>Um,ObjectCoercer:()=>ls,PrimitiveCoercer:()=>cs,PromiseRejectionEventCoercer:()=>qm,ReduceableCache:()=>Mm,StringCoercer:()=>os,chromeStackLineParser:()=>bl,createDefaultStackParser:()=>wl,createStackParser:()=>Am,geckoStackLineParser:()=>vl,getUtf8ByteLength:()=>Bm,nodeStackLineParser:()=>jm,opera10StackLineParser:()=>xm,opera11StackLineParser:()=>Rm,resolveExceptionStepsConfig:()=>$l,reverseAndStripFrames:()=>Tm,stripReservedExceptionStepFields:()=>IC,winjsStackLineParser:()=>Sm});var ts,Em,rs;function Im(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(rs&&r.length===Em)return rs;return Em=r.length,rs=r.reduce((i,n)=>{if(!ts)ts={};let s=ts[n];if(s)i[s[0]]=s[1];else{let o=e(n);for(let a=o.length-1;a>=0;a--){let u=o[a]?.filename,l=t[n];if(u&&l){i[u]=l,ts[n]=[u,l];break}}}return i},{}),rs}var aC=4;class is{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&He(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let i;if(e.stack!=""&&e.stack!=null)i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)r.stacktrace={type:"raw",frames:e.stack};let i=[r];if(e.cause!=null)i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return i}buildParsingContext(e){return{chunkIdMap:Im(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=aC))return;{let a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return{...t,syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:(s)=>i(s,r),next:(s)=>i(s,r+1)}}}var se="?";function Je(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!Mt(i))s.lineno=i;if(!Mt(n))s.colno=n;return s}var ns=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:se,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var lC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dC=/\((\S*)(?::(\d+))(?::(\d+))\)/,bl=(e,t)=>{let r=lC.exec(e);if(r){let[,n,s,o]=r;return Je(t,n,se,+s,+o)}let i=cC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=dC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ns(i[1]||se,i[2]);return Je(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var uC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vl=(e,t)=>{let r=uC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=pC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let n=r[3],s=r[1]||se;return[s,n]=ns(s,n),Je(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var fC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Sm=(e,t)=>{let r=fC.exec(e);return r?Je(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var mC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,xm=(e,t)=>{let r=mC.exec(e);return r?Je(t,r[2],r[3]||se,+r[1]):void 0},hC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Rm=(e,t)=>{let r=hC.exec(e);return r?Je(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var gC=/^\s*[-]{4,}$/,yC=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,_C=/^Promise\.(?:all|any)$/,PC=/^index \d+$/,bC="node:internal/promise",jm=(e,t)=>{let r=e.match(yC);if(r){let i,n,s,o,a;if(r[1]){s=r[1];let l=s.lastIndexOf(".");if(s[l-1]===".")l--;if(l>0){i=s.slice(0,l),n=s.slice(l+1);let d=i.indexOf(".Module");if(d>0)s=s.slice(d+1),i=i.slice(0,d)}o=void 0}if(n)o=i,a=n;if(n==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||se,s=o?`${o}.${a}`:a;let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(c?.match(/\/[A-Z]:/))c=c.slice(1);if(!c&&r[5]&&!u)c=r[5];if(_C.test(s)&&PC.test(c||""))c=bC;return{filename:c?decodeURI(c):void 0,module:void 0,function:s,lineno:Cm(r[3]),colno:Cm(r[4]),in_app:vC(c||"",u),platform:t}}if(e.match(gC))return{filename:e,platform:t}};function vC(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function Cm(e){return parseInt(e||"",10)||void 0}var Fm=/\(error: (.*)\)/,Om=50;function Tm(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Om).map((r)=>({...r,filename:r.filename||wC(t).filename,function:r.function||se}))}function wC(e){return e[e.length-1]||{}}function wl(){return Am("web:javascript",bl,vl)}function Am(e,...t){return(r,i=0)=>{let n=[],s=r.split(`
55
- `);for(let o=i;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let c=Fm.test(a)?a.replace(Fm,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){n.push(l);break}}if(n.length>=Om)break}}return Tm(n)}}class km{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=lt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ut(e,"DOMException")}isDOMError(e){return Ut(e,"DOMError")}}class ss{match(e){return em(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Dm{constructor(){}match(e){return tm(e)&&e.error!=null}coerce(e,t){let r=t.apply(e.error);if(!r)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return r}}var $C=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class os{match(e){return typeof e=="string"}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match($C);if(i)t=i[1],r=i[2];return[t,r]}}var Nm=["fatal","error","warning","log","info","debug"];function as(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t)){if(i===r.length)return n;return n.length<=t?n:`${n.slice(0,t)}...`}}return""}class ls{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);return{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return vr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")i+=` with message: '${e.message}'`;return i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=as(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return lt(e)&&!Yf(e)&&Nm.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(vm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class Lm{match(e){return vr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${as(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class cs{match(e){return Wn(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class qm{match(e){return Ut(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!vr(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);if(Wn(r))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class Mm{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Ci={MESSAGE:"$message",TIMESTAMP:"$timestamp"},EC=new Set([Ci.MESSAGE,Ci.TIMESTAMP]),ds={enabled:!0,max_bytes:32768};function $l(e){if(!e)return{...ds};return{enabled:e.enabled??ds.enabled,max_bytes:SC(e.max_bytes,ds.max_bytes)}}function IC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(EC.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class Um{constructor(e){this._entries=[],this._totalBytes=0,this._config=$l(e)}setConfig(e){this._config=$l(e),this._trimToMaxBytes()}add(e){let t=xC(e);if(!t)return;let r=Bm(t.json);if(r>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function SC(e,t){if(!Ei(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function xC(e){let t;try{t=br(e)}catch{return}try{let r=JSON.parse(t);if(!$i(r))return;let i=r,n=i[Ci.MESSAGE],s=i[Ci.TIMESTAMP];if(!lt(n)||n.trim().length===0)return;if(!lt(s)&&!Ei(s))return;return{step:i,json:t}}catch{return}}function Bm(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let i=0;i<t.length;i++)if(t[i]==="%")r+=1,i+=2;else r+=1;return r}class St extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class Gt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var Km=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Gm(e){if(e instanceof St){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function RC(e){return typeof e=="object"&&(e instanceof St||zm(e))}function zm(e){return e instanceof Gt}function CC(e){if(e instanceof St)return e.status===502||e.status===504;if(!(e instanceof Gt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Er(e){return typeof e=="object"&&e instanceof St&&e.status===413}function ji(e){if(e instanceof St)return e.status===408||e.status===429||e.status>=500;return zm(e)}function Vm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var El="default";class us{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new is([new ss,new ls,new os,new cs],wl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ol,this._events=new Pl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=am("[PostHog]",this.logMsgIfDebug.bind(this)),n)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=Pm(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:ji},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!nl()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Ee.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,i)=>this._logger.info(r,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};if(Km(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=vi(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",n,i)})}async captureStatelessImmediate(e,t,r,i){let n=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",n,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",n,i)})}async aliasStatelessImmediate(e,t,r,i){let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",n,i)}groupIdentifyStateless(e,t,r,i,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,n,s){let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((i)=>i.json()).catch((i)=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},r={},i={},n={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)c.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)c.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:CC},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:il(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof St)return{type:"api_error",statusCode:e.status};if(e instanceof Gt){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,i,n,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=bi(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,i,n,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,i,n,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},n,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},n,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,i,n,s);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o={geoip_disable:n??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,i,o);if(!a.success)return;let c=a.response;if(c.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(c.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited};return c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(e,t).then((n)=>{if(n.status!==200||!n.json){let s=`Surveys API could not be loaded: ${n.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return n.json()}).catch((n)=>{this._logger.error("Surveys API could not be loaded",n),this._events.emit("error",n)}))?.surveys;if(i)this._logger.info("Surveys fetched from API: ",JSON.stringify(i));return i??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ee.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ee.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ee.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return El}persistedQueueKeyForRoute(e){return Ee.Queue}getActiveQueueRoutes(){return[El]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(n)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:i}),this.setPersistedProperty(n,s),this._events.emit(e,i),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:i,...n}=e,s=Vm(n.properties)?n.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(i!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:i};if(s)n.properties=s;return n.uuid=Xn(n.uuid,Ie),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:pl(),uuid:Xn(t?.uuid,Ie)};if(t?.disableGeoip??this.disableGeoip){if(!Vm(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await Gm(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((n)=>!!n),i=0;while(!0){let n=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(n.length===0)return;if(i>0)this._logger.debug(`flush() re-checking ${n.length} pending promise(s) before flushing`);await Promise.all(n.map((s)=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>fl([t])).then(()=>{if(this.pendingFlushPromise===i)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),fl([i]).then(()=>{if(this.flushPromises.delete(i),this.pendingFlushPromise===i)this.pendingFlushPromise=null;if(this.flushPromise===i)this.flushPromise=null}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=El){let i={api_key:this.apiKey,batch:e,sent_at:pl()};if(this.historicalMigration)i.historical_migration=!0;let n=br(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await qt(n,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||n};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((i)=>this.getRouteQueue(i).length>0))return;let t=[],r;for(let i of e)try{await this._flushRoute(i,t)}catch(n){if(r===void 0)r=n}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let n=i.length,s=0;while(i.length>0&&s<n){let o=i.slice(0,this.maxBatchSize),a=o.map((l)=>l.message===void 0?l.message:this.normalizeMessage(l.message)),c=async()=>{let d=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,d),i=d,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Er(l))return!1;return ji(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Er(l)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(l instanceof Gt))await c();throw this._events.emit("error",l),l}await c(),t.push(...a),s+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(s instanceof Gt)return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(ji(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,i){let n=t.body?t.body:"",s=-1;try{s=n instanceof Blob?n.size:Buffer.byteLength(n,_m)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await bm(async()=>{let o=new AbortController,a=i??this.requestTimeout,c=de(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(d){throw new Gt(d)}finally{clearTimeout(c)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new St(u,s);return u},{...this._retryOptions,...r})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let r=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!RC(n))throw n;await Gm(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),r()])}finally{clearTimeout(i)}}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Jm=require("fs"),Qm=require("readline"),ps=new ve.ReduceableCache(25),Ym=new ve.ReduceableCache(20),Il=7,AC=1000,kC=1e4;async function Xm(e){let t={};for(let n=e.length-1;n>=0;n--){let s=e[n],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||qC(o)||MC(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Ym.get(n))continue;let s=t[n];if(!s)continue;s.sort((c,u)=>c-u);let o=BC(s);if(o.every((c)=>UC(n,c)))continue;let a=GC(ps,n,{});i.push(DC(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)NC(e,ps);return ps.reduce(),e}function DC(e,t,r){return new Promise((i)=>{let n=Jm.createReadStream(e),s=Qm.createInterface({input:n});function o(){n.destroy(),i()}let a=0,c=0,u=t[c];if(u===void 0)return void o();let l=u[0],d=u[1];function p(){Ym.set(e,1),s.close(),s.removeAllListeners(),o()}n.on("error",p),s.on("error",p),s.on("close",o),s.on("line",(f)=>{if(a++,a<l)return;if(r[a]=VC(f,0),a>=d){if(c===t.length-1){s.close(),s.removeAllListeners();return}c++;let m=t[c];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],d=m[1]}})})}function NC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;LC(r.lineno,r,i)}}function LC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=Zm(e);n<e;n++){let s=r[n];if(s===void 0)return void Wm(t);t.pre_context.push(s)}if(r[e]===void 0)return void Wm(t);t.context_line=r[e];let i=eh(e);t.post_context=[];for(let n=e+1;n<=i;n++){let s=r[n];if(s===void 0)break;t.post_context.push(s)}}function Wm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function qC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function MC(e){if(e.lineno!==void 0&&e.lineno>kC)return!0;if(e.colno!==void 0&&e.colno>AC)return!0;return!1}function UC(e,t){let r=ps.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function BC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Hm(r),n=[];while(!0){if(t===e.length-1){n.push(i);break}let s=e[t+1];if(typeof s!="number")break;if(s<=i[1])i[1]=s+Il;else n.push(i),i=Hm(s);t++}return n}function Hm(e){return[Zm(e),eh(e)]}function Zm(e){return Math.max(1,e-Il)}function eh(e){return e+Il}function GC(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function VC(e,t){let r=e,i=r.length;if(i<=150)return r;if(t>i)t=i;let n=Math.max(t-60,0);if(n<5)n=0;let s=Math.min(n+140,i);if(s>i-5)s=i;if(s===i)n=Math.max(s-140,0);if(r=r.slice(n,s),n>0)r=`...${r}`;if(s<i)r+="...";return r}var Ir=require("path");function th(e=process.cwd()){let t=Ir.sep==="\\",r=(n)=>t?n.replace(/\\/g,"/"):n,i=r(e);return async(n)=>{for(let s of n)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Ir.isAbsolute(s.filename))s.filename=r(Ir.relative(i,r(s.filename)))}return n}}var rh="5.46.1";var ct={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Vt{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let n=this._flags[i];if(n)t[i]=n;else r.push(i)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let n=i.enabled===!1?!1:i.variant??!0;if(e[`$feature/${r}`]=n,i.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Vt({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)i.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(ct.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(ct.QUOTA_LIMITED);if(t===void 0)n.push(ct.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function ih(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var KC=60000,zC=1152921504606847000,WC=["is_not","is_set"];class Sr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Sr.prototype)}}function ah(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);ah(this,q)}}class Qe extends Error{constructor(e){super(e);ah(this,Qe)}}class Sl{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:n,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=n,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},r={},i={},n={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:n}}async getFeatureFlag(e,t,r={},i={},n={}){await this.loadFeatureFlags();let s,o;if(!this.loadedSuccessfullyOnce)return s;if(o=this.featureFlagsByKey[e],o!==void 0){let a=this.createEvaluationContext(t,r,i,n);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},n=this.featureFlags.length==0,s=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=c,u)i[a.key]=u}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:i,skipLoadCheck:n=!1}=r;if(!n)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let o=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:n,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new q("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let c=this.groupTypeMapping[String(a)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new q("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(n?.$device_id===void 0||n?.$device_id===null||n?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=s[c];return await this.matchFeatureFlagProperties(e,i[c],u,t)}{let c=this.getBucketingValueForFlag(e,r,n);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,n,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=r?.$device_id;if(i==null||i==="")return;return i}return t}getFeatureFlagPayload(e,t){let r=null;if(t!==!1&&t!=null){if(typeof t=="boolean")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(r!=null){if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{}return r}}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,n=e.key;if(!this.featureFlagsByKey)throw new q("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new q(`Flag dependency property for '${n}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new q(`Flag dependency property for '${n}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new q(`Circular dependency detected for flag '${n}' (empty dependency chain)`);for(let a of s){if(!(a in i)){let u=this.featureFlagsByKey[a];if(u)if(u.active)try{let l=await this.computeFlagValueLocally(u,r);i[a]=l}catch(l){throw new q(`Error evaluating flag dependency '${a}' for flag '${n}': ${l}`)}else i[a]=!1;else throw new q(`Missing flag dependency '${a}' for flag '${n}'`)}if(i[a]==null)throw new q(`Dependency '${a}' could not be evaluated`)}let o=i[n];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,r,i){let n=e.filters||{},s=n.groups||[],o=n.aggregation_group_type_index,a=n.early_exit??!1,{groups:c,groupProperties:u}=i,l=!1,d;for(let p of s)try{let f=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:o,m=r,h=t;if(f!==o){if(f!=null){let y=this.groupTypeMapping[String(f)];if(!y||!(y in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(y in u)){l=!0;continue}m=u[y],h=c[y]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let y=p.variant,P=n.multivariate?.variants||[];d=y&&P.some((v)=>v.key===y)?y:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof Qe)throw f;if(f instanceof q)l=!0;else throw f}if(d!==void 0)return d;if(l)throw new q("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,n){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let c=a.type,u=!1;if(c==="cohort"){let l=await ch(a,i,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,i,n));u=a.operator==="not_in"?!l:l}else u=c==="flag"?await this.evaluateFlagDependency(a,i,n):lh(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await nh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await nh(e.key,t,"variant"),i=this.variantLookupTable(e).find((n)=>r>=n.valueMin&&r<n.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{i=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:o.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,r)=>(t[r.key]=r,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((r)=>r.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map((r)=>r.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(KC,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Sr(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Sr(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Sr(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(n){this.onError?.(Error(`Failed to store in cache: ${n}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){if(e instanceof Sr)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=de(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(r)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((r,i)=>setTimeout(()=>i(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function nh(e,t,r=""){let i=await ih(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/zC}function lh(e,t,r){let{key:i,value:n}=e,s=e.operator||"exact";if(i in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new q(`Property ${i} not found in propertyValues`)}let o=t[i];if(o==null&&!WC.includes(s)){if(r)r(`Property ${i} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(u,l){if(Array.isArray(u))return u.map((d)=>String(d).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,d){if(d==="gt")return u>l;if(d==="gte")return u>=l;if(d==="lt")return u<l;if(d==="lte")return u<=l;throw Error(`Invalid operator: ${d}`)}switch(s){case"exact":return a(n,o);case"is_not":return!a(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return sh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return sh(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof n=="number"?n:parseFloat(String(n)),l;if(l=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(u)&&Number.isFinite(l))return c(l,u,s);return c(String(o),String(n),s)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q("Date operations cannot be performed on boolean values");let u=XC(String(n));if(u==null)u=oh(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=oh(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return Oe(oe(String(o)),oe(String(n)))===0;case"semver_neq":return Oe(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return Oe(oe(String(o)),oe(String(n)))>0;case"semver_gte":return Oe(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return Oe(oe(String(o)),oe(String(n)))<0;case"semver_lte":return Oe(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:d}=JC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:d}=QC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:d}=YC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}default:throw new q(`Unknown operator: ${s}`)}}function HC(e,t){if(!(e in t))throw new Qe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function ch(e,t,r,i=!1,n){let s=String(e.value);HC(s,r);let o=r[s];return dh(o,t,r,i,n)}async function dh(e,t,r,i=!1,n){if(!e)return!0;let{type:s,values:o}=e;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let u=await dh(c,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("Can't match cohort without a given cohort property value");return s==="AND"}for(let c of o)try{let u;if(c.type==="cohort")u=await ch(c,t,r,i,n);else if(c.type==="flag"){if(!n)throw new q(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(c)}else u=lh(c,t);let l=c.negation||!1;if(s==="AND"){if(!u&&!l)return!1;if(u&&l)return!1}else{if(u&&!l)return!0;if(!u&&l)return!0}}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("can't match cohort without a given cohort property value");return s==="AND"}function sh(e){try{return new RegExp(e),!0}catch(t){return!1}}function uh(e,t){if(!/^\d+$/.test(e))throw new q(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new q(`Invalid semver: ${t}`);return parseInt(e,10)}function oe(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new q(`Invalid semver: ${e}`);let i=r.split("."),n=(c)=>{if(c===void 0||c==="")return 0;return uh(c,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function Oe(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function JC(e){let t=oe(e),r=[t[0],t[1],t[2]],i=[t[0],t[1]+1,0];return{lower:r,upper:i}}function QC(e){let t=oe(e),[r,i,n]=t,s=[r,i,n],o;return o=r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,n+1],{lower:s,upper:o}}function YC(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(c)=>{try{return uh(c,e)}catch{throw new q(`Invalid wildcard semver: ${e}`)}},s=n(i[0]),o,a;if(i.length===1)o=[s,0,0],a=[s+1,0,0];else{let c=n(i[1]);o=[s,c,0],a=[s,c+1,0]}return{lower:o,upper:a}}function oh(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new q(`${e} is in an invalid date format`)}throw new q(`The date provided ${e} must be a string, number, or date object`)}function XC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let s=r.groups.interval;if(s=="h")i.setUTCHours(i.getUTCHours()-n);else if(s=="d")i.setUTCDate(i.getUTCDate()-n);else if(s=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(s=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(s!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}function ZC(e,t){let r=!1;return Object.assign((i)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(i)},{_posthogErrorHandler:!0})}function ph(e,t){globalThis.process?.on("uncaughtException",ZC(e,t))}function fh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var ej=2000;class Ye{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new sl({...im(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return $i(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,i,n){let s={...n},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())ph(this.onException.bind(this),this.onFatalError.bind(this)),fh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ye.isPreviouslyCapturedError(e)){let r=await Ye.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),n=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(n))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(ej),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class xl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function tj(e){return e==="v0"||e==="v1"}function mh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return tj(e)?e:"v0"}var Fi="analytics",Oi="ai";function hh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class xr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(xr.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let n=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(i instanceof Error)n+=` (${i.message})`;return n}}function Rl(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function rj(e){return typeof e=="string"?e:void 0}var ij=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Rl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Rl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Rl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:rj}],nj=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function sj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function oj(e){if(typeof e=="string"){let r=new Date(e);return Number.isNaN(r.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function gh(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function aj(e){let r={...sj(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of ij)if(s in r){let c=a(r[s]);if(c!==void 0)i[o]=c;delete r[s]}let n={};for(let{property:s,field:o}of nj)if(s in r){let a=r[s];if(typeof a=="string")n[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,gh(r,"$set",e.$set),gh(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:oj(e.timestamp),...n,options:i,properties:r}}function yh(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(aj)};if(r)i.historical_migration=!0;return i}var lj="/i/v1/analytics/events",cj=30000,dj=new Set([408,500,502,503,504]);class Cl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??cj,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>de(i,r))),this.generateRequestId=t.generateRequestId??Ie,this.compress=t.compress??qt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=yh(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${lj}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let c=1;c<=a;c++){let u=c===a,l=br({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),d;try{d=await this.sendOnce(n,l,c,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(c));continue}let{status:p}=d;if(p<200||p>=300){if(!u&&dj.has(p)){let y=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(c,y));continue}let g=await this.buildHttpError(d,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${p} response body`))}let m=this.classify(o,f,s);if(m.length===0)return this.surfacePartialDrops(t,s);if(u)return void this.onError(new xr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(c,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);if(c!==null)s=c,n["Content-Encoding"]="gzip"}let o=new AbortController,a=de(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:n,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)i["User-Agent"]=this.config.userAgent;return i}classify(e,t,r){let i=t.results??{},n=[];for(let s of e){let o=i[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")n.push(s)}}return n}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let s=parseInt(r,10);return Number.isFinite(s)&&s>0?1000*s:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let n=i-this.now();return n>0?n:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let i=r.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let i=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,i){this.onError(new xr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new xr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var uj=100,_h=30000,pj=50000,fj=50,mj=500,hj="https://us.i.posthog.com",Ph=new Set;function fs(e,t){if(Ph.has(e))return;Ph.add(e),console.warn(`[PostHog] ${t}`)}function gj(e){return typeof e=="string"?e.trim():""}function yj(e){return(typeof e=="string"?e.trim():"")||void 0}function _j(e){return(typeof e=="string"?e.trim():"")||hj}function Pj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function bj(e){if(!e)return{};let t={};for(let[i,n]of Object.entries(e))t[`$feature/${i}`]=n;let r=Object.keys(e).filter((i)=>e[i]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class jl extends us{constructor(e,t={}){let r=gj(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:_j(t.host),personalApiKey:yj(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new xl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=mh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,uj):_h,typeof i.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0);if(typeof i.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0);if(!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(i.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Sl({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation})}this.errorTracking=new Ye(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||pj}enqueue(e,t,r){super.enqueue(e,t,r),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,o=new Promise((a)=>{s=a});try{e(o)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??mj,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??fj;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},n)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&hh(e)?Oi:Fi}persistedQueueKeyForRoute(e){return e===Oi?Ee.AiQueue:Ee.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Fi,Oi]:[Fi]}async sendBatch(e,t,r=Fi){if(this.captureMode!=="v1"||r===Oi)return super.sendBatch(e,t,r);let i=e.filter((n)=>n!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Cl({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return rh}get metrics(){if(!this._metrics)this._metrics=new es(this,Zn(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:n,event:s,properties:o,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c):this.enqueue(e,u,c)}).catch((n)=>{if(n)console.error(n)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let i={};if(Object.keys(t).length>0)i.$set=t;if(Object.keys(r).length>0)i.$set_once=r;this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=Pj(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=_h){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",(n)=>{clearTimeout(r),i(),t(n>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let n=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let E=this._flagOverrides[e];if(E===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,y,P,v,w;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let E=this.featureFlagsPoller?.featureFlagsByKey[e];if(E)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(E,d,{matchValue:i});if(x){f=!0;let T=x.value;y=E.id,v="Evaluated locally",w=E.has_experiment,p={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof Qe||x instanceof q)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!f&&!a){let E=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,o,[e]);if(E===void 0)g=ct.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(ct.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(ct.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(ct.FLAG_MISSING);else{y=T.metadata?.id,P=T.metadata?.version,v=T.reason?.description??T.reason?.code,w=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}p={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(n){let E=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,x={$feature_flag:e,$feature_flag_response:E,$feature_flag_id:y,$feature_flag_version:P,$feature_flag_reason:v,locally_evaluated:f,[`$feature/${e}`]:E,$feature_flag_request_id:m,$feature_flag_evaluated_at:f?Date.now():h};if(w!==void 0)x.$feature_flag_has_experiment=w;if(f&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(T!==void 0)x.$feature_flag_definitions_loaded_at=T}if(g)x.$feature_flag_error=g;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:E,groups:s,disableGeoip:o,properties:x})}if(p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)p={...p,payload:this._payloadOverrides[e]};return p}async getFeatureFlag(e,t,r){fs("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return i.variant??!0}async getFeatureFlagPayload(e,t,r,i){if(fs("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(n===void 0)return;return n.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:n}=this._resolveDistinctId(t,r);if(!i)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,i,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(i){}return r}async isFeatureEnabled(e,t,r){fs("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,c,u,s,o);f={...f,...g.flags||{}},m={...m,...g.payloads||{}}}if(this._flagOverrides!==void 0)f={...f,...this._flagOverrides};if(this._payloadOverrides!==void 0)m={...m,...this._payloadOverrides};return{featureFlags:f,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),P=new Set;if(y)for(let[w,I]of Object.entries(y.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:y.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},P.add(w)}if((y?y.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,s,o);if(w){this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt,h=Boolean(w.errorsWhileComputingFlags),g=Array.isArray(w.quotaLimited)&&w.quotaLimited.includes("feature_flags");for(let[I,E]of Object.entries(w.flags)){if(P.has(I))continue;let x;if(E.metadata?.payload!==void 0)try{x=JSON.parse(E.metadata.payload)}catch{x=E.metadata.payload}p[I]={key:I,enabled:E.enabled,variant:E.variant,payload:x,id:E.metadata?.id,version:E.metadata?.version,reason:E.reason?.description??E.reason?.code,locallyEvaluated:!1,hasExperiment:E.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[w,I]of Object.entries(this._flagOverrides)){if(I===void 0){delete p[w];continue}let E=p[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:E?.payload,id:E?.id,version:E?.version,reason:E?.reason,locallyEvaluated:E?.locallyEvaluated??!1,hasExperiment:E?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[w,I]of Object.entries(this._payloadOverrides)){let E=p[w];if(E)p[w]={...E,payload:I}}return new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:n,disableGeoip:s,flags:p,requestId:f,evaluatedAt:m,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:h,quotaLimited:g})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:n,disableGeoip:s,properties:o}=e,a=n&&Object.keys(n).length>0?`_${JSON.stringify(Object.entries(n).sort(([u],[l])=>u<l?-1:u>l?1:0))}`:"",c=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(c);else this.distinctIdHasSentFlagCalls[t]=new Set([c]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:n,disableGeoip:s})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((i)=>[i,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((i)=>de(i,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.options.requestTimeout),r.signal=n.signal}try{return await this.fetch(t,r)}catch(n){this._events.emit("error",n);return}finally{if(i)clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[n,s]of Object.entries(e))if(rm(s)&&t&&n in t){let o={};for(let[a,c]of Object.entries(s))o[String(a)]=String(c);i[String(n)]=o}else r[String(n)]=String(s);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let n=i?.personProperties||{},s=i?.groupProperties||{},o=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,n,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let n={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...i?.[o]||{}};return{allPersonProperties:n,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,n){if(!Ye.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:i,flags:n},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!Ye.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((s)=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:n,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=e,d=this.context?.get(),p=t.includeContextProperties??!0,f=r||d?.distinctId,m=p?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};if(!f)f=Ie(),m.$process_person_profile=!1;if(p&&d?.sessionId&&!m.$session_id)m.$session_id=d.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?vi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(o){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(a){fs("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let P=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,P);return bj(v)}return{}}).catch(()=>({})).then((P)=>{let v=g.groups||s;return{...P,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"){if(Jf(y.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",y.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:y,options:{timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let n of r){if(i=n(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}}var bh=require("async_hooks");class Fl{constructor(){this.storage=new bh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function vj(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(n==="*"||n.includes(o.level)))return o;if(!o.tags)o.tags={};let c=o.tags[vh.POSTHOG_ID_TAG];if(c===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();o.tags["PostHog Person URL"]=l;let d=o.exception?.values||[],p=d.map((m)=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map((h)=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags};if(t&&r)f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:c,properties:f});return o}}class vh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,n){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(vj(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ol extends jl{getLibraryId(){return"posthog-node"}initializeContext(){return new Fl}createErrorPropertiesBuilder(){return new ve.ErrorPropertiesBuilder([new ve.EventCoercer,new ve.ErrorCoercer,new ve.ObjectCoercer,new ve.StringCoercer,new ve.PrimitiveCoercer],ve.createStackParser("node:javascript",ve.nodeStackLineParser),[zf(),Xm,th()])}}var $h=require("crypto"),Z=require("fs/promises"),Y=require("path");var wh={name:"@toloka-platform/sdk",version:"0.1.0-preview.3",private:!1,description:"Preview. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"dist/cli/toloka.js"},files:["README.md","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"preview"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build",test:"vitest run",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","posthog-node":"5.46.1"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},engines:{bun:"1.4.0"}};var Kt=wh.version,Xe="@toloka-platform/sdk",hs="toloka-build",Eh=`.claude/skills/${hs}/SKILL.md`,Ih=`.cursor/rules/${hs}.mdc`,Rr="AGENTS.md",ms="<!-- toloka:begin -->",Ti="<!-- toloka:end -->",$j=/<!-- toloka:sdk-version ([^\s>]+) -->/u,Ej=/<!-- toloka:skill-digest sha256:([a-f0-9]{64}) -->/u,Ij=[Eh,Ih,Rr],Sh="toloka-pipeline-as-code",xh=Y.join(".claude","skills",Sh),Rh=Y.join(".cursor","rules",`${Sh}.mdc`),Sj=[xh,Rh],xj=[Y.join(xh,"SKILL.md"),Rh],Rj=[["SKILL.md",new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/node-semantics.md",new URL("../../skills/references/node-semantics.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/workflow-and-cli.md",new URL("../../skills/references/workflow-and-cli.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")]],Ai=(e)=>e instanceof Error&&("code"in e)&&e.code==="ENOENT",gs=async(e)=>{try{return await Z.readFile(e,"utf8")}catch(t){if(Ai(t))return;throw t}},Tl=async(e)=>{try{return(await Z.lstat(e)).isDirectory()}catch(t){if(Ai(t))return!1;throw t}},Cj=async(e)=>{try{return(await Z.lstat(e)).isFile()}catch(t){if(Ai(t))return!1;throw t}},Ch=async(e,t)=>{let r=e;for(let i of t.split("/")){r=Y.join(r,i);try{let n=await Z.lstat(r);_(!n.isSymbolicLink(),`Refusing to write through symbolic link ${r}.`)}catch(n){if(Ai(n))return;throw n}}};async function jh(){let e=$h.createHash("sha256");for(let[t,r]of Rj)e.update(t),e.update("\x00"),e.update(await Z.readFile(r)),e.update("\x00");return e.digest("hex")}var jj=new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts"),Fj=`node_modules/${Xe}/skills/references/`,Oj=async(e)=>{let n=(await Z.readFile(jj,"utf8")).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/u,"").replace(/^#\s.*\r?\n+/u,"").replaceAll("](references/",`](${Fj}`).replaceAll("](../examples/",`](node_modules/${Xe}/examples/`);return e==="##"?n:n.replaceAll(/^## /gmu,"### ")},Al=async(e,t)=>`Generated by \`${Xe}\` version \`${Kt}\`.
54
+ `)}}}var Ah=require("crypto"),zt=require("fs/promises"),_s=require("path");var Pr=require("path");function Wf(){let e=pR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function pR(e=process.argv[1]?Pr.dirname(process.argv[1]):process.cwd(),t=Pr.sep==="\\"){let r=t?zf(e):e;return(i)=>{if(!i)return;let n=t?zf(i):i,{dir:s,base:o,ext:a}=Pr.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let c=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${c}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function zf(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var il=(e)=>{if("flags"in e){let t=Hf(e.flags),r=Jf(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Vn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,fR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function fR(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Hf=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,bi(r)]).filter(([,t])=>t!==void 0)),Jf=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map((r)=>{let i=t[r].metadata?.payload;return[r,i?Vn(i):void 0]}))},bi=(e)=>e===void 0?void 0:e.variant??e.enabled,Vn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var mR=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],vi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return mR.forEach(i),t.forEach(i),r};var Ee=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function nl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var gR="NativeGzipValidationError",yR=31,_R=139,PR=8,bR=(e)=>e.length>=2&&e[0]===yR&&e[1]===_R;var wi,vR=()=>{if(wi)return wi;wi=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;wi[e]=t>>>0}return wi},wR=(e)=>{let t=vR(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Kn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=gR,t},$R=async(e,t)=>{if(e.size<18)Kn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!bR(r)||r[2]!==PR)Kn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==wR(t))Kn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Kn("invalid-size")};async function qt(e,t=!0,r){try{let i=new TextEncoder().encode(e),n=new globalThis.CompressionStream("gzip"),s=n.writable.getWriter(),o=s.write(i).then(()=>s.close()).catch(async(u)=>{try{await s.abort(u)}catch{}throw u}),a=new Response(n.readable).blob(),[c]=await Promise.all([a,o]);return await $R(c,i),c}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var ER=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Qf=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return ER.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function br(e){let t=[];return JSON.stringify(e,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i=="function"||typeof i=="symbol")return;if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i})??"null"}var SR=Array.isArray,Yf=Object.prototype,uD=Yf.hasOwnProperty,zn=Yf.toString,He=SR||function(e){return zn.call(e)==="[object Array]"};var $i=(e)=>e===Object(e)&&!He(e);var Mt=(e)=>e===void 0,lt=(e)=>zn.call(e)=="[object String]",Xf=(e)=>lt(e)&&e.trim().length===0,Zf=(e)=>e===null;var Ei=(e)=>zn.call(e)=="[object Number]"&&e===e;var em=(e)=>zn.call(e)==="[object Boolean]";var tm=(e)=>e instanceof Error;function Wn(e){return e===null||typeof e!="object"}function Ut(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function rm(e){return Ut(e,"ErrorEvent")}function vr(e){return typeof Event<"u"&&xR(e,Event)}function im(e){return Ut(e,"Object")}function xR(e,t){try{return e instanceof t}catch{return!1}}function Ii(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ei(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return i.warn(" cannot be less than min: "+t+". Using min value instead."),t}return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),Ii(n||r,t,r,i)}var RR=86400000,CR=1,jR=10;function nm(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??CR,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??jR}}class sl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ii(e.bucketSize,0,100,e._logger),this._refillRate=Ii(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ii(e.refillInterval,0,RR,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,i=Math.floor(r/this._refillInterval);if(i>0){let n=i*this._refillRate;e.tokens=Math.min(e.tokens+n,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];if(i)this._applyRefill(i,t);else i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i;if(i.tokens===0)return!0;if(i.tokens--,i.tokens===0)this._onBucketRateLimited?.(e);return i.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Bt{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Bt(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>281474976710655||t>4095||r>1073741823||i>4294967295)throw RangeError("invalid field value");let n=new Uint8Array(16);return n[0]=e/1099511627776,n[1]=e/4294967296,n[2]=e/16777216,n[3]=e/65536,n[4]=e/256,n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new Bt(n)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let r=new Uint8Array(16);for(let i=0;i<16;i+=4){let n=parseInt(t.substring(2*i,2*i+8),16);r[i+0]=n>>>24,r[i+1]=n>>>16,r[i+2]=n>>>8,r[i+3]=n}return new Bt(r)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Bt(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class om{constructor(e){this.timestamp=0,this.counter=0,this.random=e??FR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Bt.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Bt.ofInner(e)}}var FR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),sm,Ie=()=>OR().toString(),OR=()=>(sm||(sm=new om)).generate();class ol{add(e){let t=Ie(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((i)=>i.id<=t&&!r.has(i.promise)).map((i)=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function TR(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var am=(e,t,r)=>{function i(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{i("debug",...s)},info:(...s)=>{i("log",...s)},warn:(...s)=>{i("warn",...s)},error:(...s)=>{i("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>am(`${e} ${s}`,t,r)}},AR=(e)=>e();function lm(e,t=AR){return am(e,t,TR())}var $r="Mobile",Jn="iOS",wr="Android",fm="Tablet",$D=wr+" "+fm;var DR="Apple",ED=DR+" Watch",mm="Safari",Qn="BlackBerry",hm="Samsung",NR=hm+"Browser",LR=hm+" Internet",Yn="Chrome",qR=Yn+" OS",MR=Yn+" "+Jn,gm="Internet Explorer",UR=gm+" "+$r,ll="Opera",ID=ll+" Mini",ym="Edge",BR="Microsoft "+ym,cl="Firefox",GR=cl+" "+Jn,dl="Nintendo",ul="PlayStation",Hn="Xbox",VR=wr+" "+$r,KR=$r+" "+mm,Si="Windows",zR=Si+" Phone";var _m="Generic",SD=_m+" "+$r.toLowerCase(),xD=_m+" "+fm.toLowerCase(),WR="Konqueror",HR="Oculus Browser",cm="Vivaldi",JR="Yandex",dm="Whale",QR="DuckDuckGo",YR="Pale Moon",um="Waterfox",pm="Brave",XR="Google Search App",H="(\\d+(\\.\\d+)?)",al=new RegExp("Version/"+H);var RD=new RegExp(Hn,"i"),CD=new RegExp(ul+" \\w+","i"),jD=new RegExp(dl+" \\w+","i"),ZR=new RegExp(Qn+"|PlayBook|BB10","i"),eC={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var FD={[UR]:[new RegExp("rv:"+H)],[BR]:[new RegExp(ym+"?\\/"+H)],[Yn]:[new RegExp("("+Yn+"|CrMo)\\/"+H)],[MR]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[mm]:[al],[KR]:[al],[ll]:[new RegExp("("+ll+"|OPR)\\/"+H)],[cl]:[new RegExp(cl+"\\/"+H)],[GR]:[new RegExp("FxiOS\\/"+H)],[WR]:[new RegExp("Konqueror[:/]?"+H,"i")],[Qn]:[new RegExp(Qn+" "+H),al],[VR]:[new RegExp("android\\s"+H,"i")],[LR]:[new RegExp(NR+"\\/"+H)],[HR]:[new RegExp("OculusBrowser\\/"+H)],[cm]:[new RegExp(cm+"\\/"+H)],[JR]:[new RegExp("YaBrowser\\/"+H)],[dm]:[new RegExp(dm+"\\/"+H)],[pm]:[new RegExp(pm+"\\/"+H)],[QR]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[YR]:[new RegExp("PaleMoon\\/"+H)],[um]:[new RegExp(um+"\\/"+H)],[XR]:[new RegExp("GSA\\/"+H)],[gm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var OD=[[new RegExp(Hn+"; "+Hn+" (.*?)[);]","i"),(e)=>[Hn,e&&e[1]||""]],[new RegExp(dl,"i"),[dl,""]],[new RegExp(ul,"i"),[ul,""]],[ZR,[Qn,""]],[new RegExp(Si,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[zR,""];if(new RegExp($r).test(t)&&!/IEMobile\b/.test(t))return[Si+" "+$r,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=eC[i]||"";if(/arm/i.test(t))n="RT";return[Si,n]}return[Si,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Jn,t.join(".")]}return[Jn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=Mt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+wr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[wr,t.join(".")]}return[wr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[qR,""]],[/Linux|debian/i,["Linux",""]]];var Pm="utf8",tC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rC(e){return typeof e=="string"&&tC.test(e)}function Xn(e,t){return rC(e)?e:t()}function bm(e){return e?.replace(/\/+$/,"")}async function vm(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){if(i>0)await new Promise((n)=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function pl(){return new Date().toISOString()}function de(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var wm=(e)=>e instanceof Error;function fl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var nC={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},VD=nC.info;function ml(e){if(em(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(He(e))return{arrayValue:{values:e.map((t)=>ml(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function xi(e){let t=[];for(let r in e){let i=e[r];if(!(Zf(i)||Mt(i)))t.push({key:r,value:ml(i)})}return t}var Ri=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function hl(e){return String(e)+"000000"}function gl(e,t,r,i){let n="";if(i)n=Object.keys(i).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(i[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${n}`}function $m(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function yl(e,t,r){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}function _l(e,t,r,i){return{resourceMetrics:[{resource:{attributes:xi(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function Zn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var Em=1;class es{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,i;try{r=t.attributes?{...t.attributes}:void 0,i=gl(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let n=this._series.get(i);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(i,n)}let s=this._typeByName.get(t.name);if(s===void 0)this._typeByName.set(t.name,t.type);else if(s!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(n,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(Ri.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[$m(t,Ri)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=He(t)?t:[t],i=e;for(let n of r)try{let s=n(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=de(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){return _l(this._buildMetrics(e),yl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=hl(Date.now()),r=new Map;for(let i of e.values()){let n=gl(i.type,i.name,i.unit,void 0),s=r.get(n);if(!s){if(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count")s.sum={aggregationTemporality:Em,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:Em,dataPoints:[]};r.set(n,s)}let o=xi(i.attributes??{}),a=hl(i.windowStartMs);if(i.type==="count"){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(c)}else if(i.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(c)}else if(i.hist){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ri};s.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let i=this._series.get(t);if(!i){if(this._admitNewSeries())this._series.set(t,r);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,r.windowStartMs),i.type){case"count":i.total=(i.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(i.hist){i.hist.count+=r.hist.count,i.hist.sum+=r.hist.sum,i.hist.min=Math.min(i.hist.min,r.hist.min),i.hist.max=Math.max(i.hist.max,r.hist.max);for(let n=0;n<i.hist.bucketCounts.length;n++)i.hist.bucketCounts[n]+=r.hist.bucketCounts[n]}else i.hist=r.hist;break}}}}class Pl{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}var ve={};o_(ve,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ds,DOMExceptionCoercer:()=>Dm,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ci,ErrorCoercer:()=>ss,ErrorEventCoercer:()=>Nm,ErrorPropertiesBuilder:()=>is,EventCoercer:()=>qm,ExceptionStepsBuffer:()=>Bm,ObjectCoercer:()=>ls,PrimitiveCoercer:()=>cs,PromiseRejectionEventCoercer:()=>Mm,ReduceableCache:()=>Um,StringCoercer:()=>os,chromeStackLineParser:()=>bl,createDefaultStackParser:()=>wl,createStackParser:()=>km,geckoStackLineParser:()=>vl,getUtf8ByteLength:()=>Gm,nodeStackLineParser:()=>Fm,opera10StackLineParser:()=>Rm,opera11StackLineParser:()=>Cm,resolveExceptionStepsConfig:()=>$l,reverseAndStripFrames:()=>Am,stripReservedExceptionStepFields:()=>SC,winjsStackLineParser:()=>xm});var ts,Im,rs;function Sm(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(rs&&r.length===Im)return rs;return Im=r.length,rs=r.reduce((i,n)=>{if(!ts)ts={};let s=ts[n];if(s)i[s[0]]=s[1];else{let o=e(n);for(let a=o.length-1;a>=0;a--){let u=o[a]?.filename,l=t[n];if(u&&l){i[u]=l,ts[n]=[u,l];break}}}return i},{}),rs}var lC=4;class is{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&He(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let i;if(e.stack!=""&&e.stack!=null)i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)r.stacktrace={type:"raw",frames:e.stack};let i=[r];if(e.cause!=null)i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return i}buildParsingContext(e){return{chunkIdMap:Sm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=lC))return;{let a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return{...t,syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:(s)=>i(s,r),next:(s)=>i(s,r+1)}}}var se="?";function Je(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!Mt(i))s.lineno=i;if(!Mt(n))s.colno=n;return s}var ns=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:se,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var cC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,dC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,uC=/\((\S*)(?::(\d+))(?::(\d+))\)/,bl=(e,t)=>{let r=cC.exec(e);if(r){let[,n,s,o]=r;return Je(t,n,se,+s,+o)}let i=dC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=uC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ns(i[1]||se,i[2]);return Je(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var pC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vl=(e,t)=>{let r=pC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=fC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let n=r[3],s=r[1]||se;return[s,n]=ns(s,n),Je(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var mC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,xm=(e,t)=>{let r=mC.exec(e);return r?Je(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var hC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Rm=(e,t)=>{let r=hC.exec(e);return r?Je(t,r[2],r[3]||se,+r[1]):void 0},gC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Cm=(e,t)=>{let r=gC.exec(e);return r?Je(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var yC=/^\s*[-]{4,}$/,_C=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,PC=/^Promise\.(?:all|any)$/,bC=/^index \d+$/,vC="node:internal/promise",Fm=(e,t)=>{let r=e.match(_C);if(r){let i,n,s,o,a;if(r[1]){s=r[1];let l=s.lastIndexOf(".");if(s[l-1]===".")l--;if(l>0){i=s.slice(0,l),n=s.slice(l+1);let d=i.indexOf(".Module");if(d>0)s=s.slice(d+1),i=i.slice(0,d)}o=void 0}if(n)o=i,a=n;if(n==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||se,s=o?`${o}.${a}`:a;let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(c?.match(/\/[A-Z]:/))c=c.slice(1);if(!c&&r[5]&&!u)c=r[5];if(PC.test(s)&&bC.test(c||""))c=vC;return{filename:c?decodeURI(c):void 0,module:void 0,function:s,lineno:jm(r[3]),colno:jm(r[4]),in_app:wC(c||"",u),platform:t}}if(e.match(yC))return{filename:e,platform:t}};function wC(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function jm(e){return parseInt(e||"",10)||void 0}var Om=/\(error: (.*)\)/,Tm=50;function Am(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Tm).map((r)=>({...r,filename:r.filename||$C(t).filename,function:r.function||se}))}function $C(e){return e[e.length-1]||{}}function wl(){return km("web:javascript",bl,vl)}function km(e,...t){return(r,i=0)=>{let n=[],s=r.split(`
55
+ `);for(let o=i;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let c=Om.test(a)?a.replace(Om,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){n.push(l);break}}if(n.length>=Tm)break}}return Am(n)}}class Dm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=lt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ut(e,"DOMException")}isDOMError(e){return Ut(e,"DOMError")}}class ss{match(e){return tm(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Nm{constructor(){}match(e){return rm(e)&&e.error!=null}coerce(e,t){let r=t.apply(e.error);if(!r)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return r}}var EC=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class os{match(e){return typeof e=="string"}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(EC);if(i)t=i[1],r=i[2];return[t,r]}}var Lm=["fatal","error","warning","log","info","debug"];function as(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t)){if(i===r.length)return n;return n.length<=t?n:`${n.slice(0,t)}...`}}return""}class ls{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);return{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return vr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")i+=` with message: '${e.message}'`;return i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=as(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return lt(e)&&!Xf(e)&&Lm.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(wm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class qm{match(e){return vr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${as(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class cs{match(e){return Wn(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Mm{match(e){return Ut(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!vr(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);if(Wn(r))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class Um{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Ci={MESSAGE:"$message",TIMESTAMP:"$timestamp"},IC=new Set([Ci.MESSAGE,Ci.TIMESTAMP]),ds={enabled:!0,max_bytes:32768};function $l(e){if(!e)return{...ds};return{enabled:e.enabled??ds.enabled,max_bytes:xC(e.max_bytes,ds.max_bytes)}}function SC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(IC.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class Bm{constructor(e){this._entries=[],this._totalBytes=0,this._config=$l(e)}setConfig(e){this._config=$l(e),this._trimToMaxBytes()}add(e){let t=RC(e);if(!t)return;let r=Gm(t.json);if(r>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function xC(e,t){if(!Ei(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function RC(e){let t;try{t=br(e)}catch{return}try{let r=JSON.parse(t);if(!$i(r))return;let i=r,n=i[Ci.MESSAGE],s=i[Ci.TIMESTAMP];if(!lt(n)||n.trim().length===0)return;if(!lt(s)&&!Ei(s))return;return{step:i,json:t}}catch{return}}function Gm(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let i=0;i<t.length;i++)if(t[i]==="%")r+=1,i+=2;else r+=1;return r}class St extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class Gt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var zm=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Vm(e){if(e instanceof St){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function CC(e){return typeof e=="object"&&(e instanceof St||Wm(e))}function Wm(e){return e instanceof Gt}function jC(e){if(e instanceof St)return e.status===502||e.status===504;if(!(e instanceof Gt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Er(e){return typeof e=="object"&&e instanceof St&&e.status===413}function ji(e){if(e instanceof St)return e.status===408||e.status===429||e.status>=500;return Wm(e)}function Km(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var El="default";class us{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new is([new ss,new ls,new os,new cs],wl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ol,this._events=new Pl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=lm("[PostHog]",this.logMsgIfDebug.bind(this)),n)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=bm(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:ji},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!nl()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Ee.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,i)=>this._logger.info(r,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};if(zm(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=vi(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",n,i)})}async captureStatelessImmediate(e,t,r,i){let n=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",n,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",n,i)})}async aliasStatelessImmediate(e,t,r,i){let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",n,i)}groupIdentifyStateless(e,t,r,i,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,n,s){let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((i)=>i.json()).catch((i)=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},r={},i={},n={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)c.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)c.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:jC},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:il(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof St)return{type:"api_error",statusCode:e.status};if(e instanceof Gt){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,i,n,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=bi(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,i,n,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,i,n,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},n,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},n,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,i,n,s);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o={geoip_disable:n??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,i,o);if(!a.success)return;let c=a.response;if(c.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(c.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited};return c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(e,t).then((n)=>{if(n.status!==200||!n.json){let s=`Surveys API could not be loaded: ${n.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return n.json()}).catch((n)=>{this._logger.error("Surveys API could not be loaded",n),this._events.emit("error",n)}))?.surveys;if(i)this._logger.info("Surveys fetched from API: ",JSON.stringify(i));return i??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ee.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ee.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ee.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return El}persistedQueueKeyForRoute(e){return Ee.Queue}getActiveQueueRoutes(){return[El]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(n)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:i}),this.setPersistedProperty(n,s),this._events.emit(e,i),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:i,...n}=e,s=Km(n.properties)?n.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(i!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:i};if(s)n.properties=s;return n.uuid=Xn(n.uuid,Ie),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:pl(),uuid:Xn(t?.uuid,Ie)};if(t?.disableGeoip??this.disableGeoip){if(!Km(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await Vm(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((n)=>!!n),i=0;while(!0){let n=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(n.length===0)return;if(i>0)this._logger.debug(`flush() re-checking ${n.length} pending promise(s) before flushing`);await Promise.all(n.map((s)=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>fl([t])).then(()=>{if(this.pendingFlushPromise===i)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),fl([i]).then(()=>{if(this.flushPromises.delete(i),this.pendingFlushPromise===i)this.pendingFlushPromise=null;if(this.flushPromise===i)this.flushPromise=null}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=El){let i={api_key:this.apiKey,batch:e,sent_at:pl()};if(this.historicalMigration)i.historical_migration=!0;let n=br(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await qt(n,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||n};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((i)=>this.getRouteQueue(i).length>0))return;let t=[],r;for(let i of e)try{await this._flushRoute(i,t)}catch(n){if(r===void 0)r=n}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let n=i.length,s=0;while(i.length>0&&s<n){let o=i.slice(0,this.maxBatchSize),a=o.map((l)=>l.message===void 0?l.message:this.normalizeMessage(l.message)),c=async()=>{let d=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,d),i=d,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Er(l))return!1;return ji(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Er(l)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(l instanceof Gt))await c();throw this._events.emit("error",l),l}await c(),t.push(...a),s+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(s instanceof Gt)return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(ji(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,i){let n=t.body?t.body:"",s=-1;try{s=n instanceof Blob?n.size:Buffer.byteLength(n,Pm)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await vm(async()=>{let o=new AbortController,a=i??this.requestTimeout,c=de(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(d){throw new Gt(d)}finally{clearTimeout(c)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new St(u,s);return u},{...this._retryOptions,...r})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let r=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!CC(n))throw n;await Vm(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),r()])}finally{clearTimeout(i)}}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Qm=require("fs"),Ym=require("readline"),ps=new ve.ReduceableCache(25),Xm=new ve.ReduceableCache(20),Il=7,kC=1000,DC=1e4;async function Zm(e){let t={};for(let n=e.length-1;n>=0;n--){let s=e[n],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||MC(o)||UC(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Xm.get(n))continue;let s=t[n];if(!s)continue;s.sort((c,u)=>c-u);let o=GC(s);if(o.every((c)=>BC(n,c)))continue;let a=VC(ps,n,{});i.push(NC(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)LC(e,ps);return ps.reduce(),e}function NC(e,t,r){return new Promise((i)=>{let n=Qm.createReadStream(e),s=Ym.createInterface({input:n});function o(){n.destroy(),i()}let a=0,c=0,u=t[c];if(u===void 0)return void o();let l=u[0],d=u[1];function p(){Xm.set(e,1),s.close(),s.removeAllListeners(),o()}n.on("error",p),s.on("error",p),s.on("close",o),s.on("line",(f)=>{if(a++,a<l)return;if(r[a]=KC(f,0),a>=d){if(c===t.length-1){s.close(),s.removeAllListeners();return}c++;let m=t[c];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],d=m[1]}})})}function LC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;qC(r.lineno,r,i)}}function qC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=eh(e);n<e;n++){let s=r[n];if(s===void 0)return void Hm(t);t.pre_context.push(s)}if(r[e]===void 0)return void Hm(t);t.context_line=r[e];let i=th(e);t.post_context=[];for(let n=e+1;n<=i;n++){let s=r[n];if(s===void 0)break;t.post_context.push(s)}}function Hm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function MC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function UC(e){if(e.lineno!==void 0&&e.lineno>DC)return!0;if(e.colno!==void 0&&e.colno>kC)return!0;return!1}function BC(e,t){let r=ps.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function GC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Jm(r),n=[];while(!0){if(t===e.length-1){n.push(i);break}let s=e[t+1];if(typeof s!="number")break;if(s<=i[1])i[1]=s+Il;else n.push(i),i=Jm(s);t++}return n}function Jm(e){return[eh(e),th(e)]}function eh(e){return Math.max(1,e-Il)}function th(e){return e+Il}function VC(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function KC(e,t){let r=e,i=r.length;if(i<=150)return r;if(t>i)t=i;let n=Math.max(t-60,0);if(n<5)n=0;let s=Math.min(n+140,i);if(s>i-5)s=i;if(s===i)n=Math.max(s-140,0);if(r=r.slice(n,s),n>0)r=`...${r}`;if(s<i)r+="...";return r}var Ir=require("path");function rh(e=process.cwd()){let t=Ir.sep==="\\",r=(n)=>t?n.replace(/\\/g,"/"):n,i=r(e);return async(n)=>{for(let s of n)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Ir.isAbsolute(s.filename))s.filename=r(Ir.relative(i,r(s.filename)))}return n}}var ih="5.46.1";var ct={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Vt{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let n=this._flags[i];if(n)t[i]=n;else r.push(i)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let n=i.enabled===!1?!1:i.variant??!0;if(e[`$feature/${r}`]=n,i.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Vt({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)i.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(ct.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(ct.QUOTA_LIMITED);if(t===void 0)n.push(ct.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function nh(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var zC=60000,WC=1152921504606847000,HC=["is_not","is_set"];class Sr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Sr.prototype)}}function lh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);lh(this,q)}}class Qe extends Error{constructor(e){super(e);lh(this,Qe)}}class Sl{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:n,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=n,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},r={},i={},n={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:n}}async getFeatureFlag(e,t,r={},i={},n={}){await this.loadFeatureFlags();let s,o;if(!this.loadedSuccessfullyOnce)return s;if(o=this.featureFlagsByKey[e],o!==void 0){let a=this.createEvaluationContext(t,r,i,n);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},n=this.featureFlags.length==0,s=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=c,u)i[a.key]=u}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:i,skipLoadCheck:n=!1}=r;if(!n)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let o=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:n,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new q("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let c=this.groupTypeMapping[String(a)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new q("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(n?.$device_id===void 0||n?.$device_id===null||n?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=s[c];return await this.matchFeatureFlagProperties(e,i[c],u,t)}{let c=this.getBucketingValueForFlag(e,r,n);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,n,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=r?.$device_id;if(i==null||i==="")return;return i}return t}getFeatureFlagPayload(e,t){let r=null;if(t!==!1&&t!=null){if(typeof t=="boolean")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(r!=null){if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{}return r}}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,n=e.key;if(!this.featureFlagsByKey)throw new q("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new q(`Flag dependency property for '${n}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new q(`Flag dependency property for '${n}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new q(`Circular dependency detected for flag '${n}' (empty dependency chain)`);for(let a of s){if(!(a in i)){let u=this.featureFlagsByKey[a];if(u)if(u.active)try{let l=await this.computeFlagValueLocally(u,r);i[a]=l}catch(l){throw new q(`Error evaluating flag dependency '${a}' for flag '${n}': ${l}`)}else i[a]=!1;else throw new q(`Missing flag dependency '${a}' for flag '${n}'`)}if(i[a]==null)throw new q(`Dependency '${a}' could not be evaluated`)}let o=i[n];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,r,i){let n=e.filters||{},s=n.groups||[],o=n.aggregation_group_type_index,a=n.early_exit??!1,{groups:c,groupProperties:u}=i,l=!1,d;for(let p of s)try{let f=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:o,m=r,h=t;if(f!==o){if(f!=null){let y=this.groupTypeMapping[String(f)];if(!y||!(y in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(y in u)){l=!0;continue}m=u[y],h=c[y]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let y=p.variant,P=n.multivariate?.variants||[];d=y&&P.some((v)=>v.key===y)?y:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof Qe)throw f;if(f instanceof q)l=!0;else throw f}if(d!==void 0)return d;if(l)throw new q("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,n){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let c=a.type,u=!1;if(c==="cohort"){let l=await dh(a,i,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,i,n));u=a.operator==="not_in"?!l:l}else u=c==="flag"?await this.evaluateFlagDependency(a,i,n):ch(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await sh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await sh(e.key,t,"variant"),i=this.variantLookupTable(e).find((n)=>r>=n.valueMin&&r<n.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{i=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:o.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,r)=>(t[r.key]=r,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((r)=>r.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map((r)=>r.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(zC,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Sr(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Sr(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Sr(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(n){this.onError?.(Error(`Failed to store in cache: ${n}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){if(e instanceof Sr)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=de(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(r)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((r,i)=>setTimeout(()=>i(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function sh(e,t,r=""){let i=await nh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/WC}function ch(e,t,r){let{key:i,value:n}=e,s=e.operator||"exact";if(i in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new q(`Property ${i} not found in propertyValues`)}let o=t[i];if(o==null&&!HC.includes(s)){if(r)r(`Property ${i} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(u,l){if(Array.isArray(u))return u.map((d)=>String(d).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,d){if(d==="gt")return u>l;if(d==="gte")return u>=l;if(d==="lt")return u<l;if(d==="lte")return u<=l;throw Error(`Invalid operator: ${d}`)}switch(s){case"exact":return a(n,o);case"is_not":return!a(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return oh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return oh(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof n=="number"?n:parseFloat(String(n)),l;if(l=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(u)&&Number.isFinite(l))return c(l,u,s);return c(String(o),String(n),s)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q("Date operations cannot be performed on boolean values");let u=ZC(String(n));if(u==null)u=ah(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=ah(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return Oe(oe(String(o)),oe(String(n)))===0;case"semver_neq":return Oe(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return Oe(oe(String(o)),oe(String(n)))>0;case"semver_gte":return Oe(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return Oe(oe(String(o)),oe(String(n)))<0;case"semver_lte":return Oe(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:d}=QC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:d}=YC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:d}=XC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}default:throw new q(`Unknown operator: ${s}`)}}function JC(e,t){if(!(e in t))throw new Qe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function dh(e,t,r,i=!1,n){let s=String(e.value);JC(s,r);let o=r[s];return uh(o,t,r,i,n)}async function uh(e,t,r,i=!1,n){if(!e)return!0;let{type:s,values:o}=e;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let u=await uh(c,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("Can't match cohort without a given cohort property value");return s==="AND"}for(let c of o)try{let u;if(c.type==="cohort")u=await dh(c,t,r,i,n);else if(c.type==="flag"){if(!n)throw new q(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(c)}else u=ch(c,t);let l=c.negation||!1;if(s==="AND"){if(!u&&!l)return!1;if(u&&l)return!1}else{if(u&&!l)return!0;if(!u&&l)return!0}}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("can't match cohort without a given cohort property value");return s==="AND"}function oh(e){try{return new RegExp(e),!0}catch(t){return!1}}function ph(e,t){if(!/^\d+$/.test(e))throw new q(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new q(`Invalid semver: ${t}`);return parseInt(e,10)}function oe(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new q(`Invalid semver: ${e}`);let i=r.split("."),n=(c)=>{if(c===void 0||c==="")return 0;return ph(c,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function Oe(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function QC(e){let t=oe(e),r=[t[0],t[1],t[2]],i=[t[0],t[1]+1,0];return{lower:r,upper:i}}function YC(e){let t=oe(e),[r,i,n]=t,s=[r,i,n],o;return o=r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,n+1],{lower:s,upper:o}}function XC(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(c)=>{try{return ph(c,e)}catch{throw new q(`Invalid wildcard semver: ${e}`)}},s=n(i[0]),o,a;if(i.length===1)o=[s,0,0],a=[s+1,0,0];else{let c=n(i[1]);o=[s,c,0],a=[s,c+1,0]}return{lower:o,upper:a}}function ah(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new q(`${e} is in an invalid date format`)}throw new q(`The date provided ${e} must be a string, number, or date object`)}function ZC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let s=r.groups.interval;if(s=="h")i.setUTCHours(i.getUTCHours()-n);else if(s=="d")i.setUTCDate(i.getUTCDate()-n);else if(s=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(s=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(s!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}function ej(e,t){let r=!1;return Object.assign((i)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(i)},{_posthogErrorHandler:!0})}function fh(e,t){globalThis.process?.on("uncaughtException",ej(e,t))}function mh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var tj=2000;class Ye{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new sl({...nm(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return $i(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,i,n){let s={...n},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())fh(this.onException.bind(this),this.onFatalError.bind(this)),mh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ye.isPreviouslyCapturedError(e)){let r=await Ye.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),n=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(n))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(tj),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class xl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function rj(e){return e==="v0"||e==="v1"}function hh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return rj(e)?e:"v0"}var Fi="analytics",Oi="ai";function gh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class xr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(xr.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let n=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(i instanceof Error)n+=` (${i.message})`;return n}}function Rl(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function ij(e){return typeof e=="string"?e:void 0}var nj=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Rl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Rl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Rl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:ij}],sj=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function oj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aj(e){if(typeof e=="string"){let r=new Date(e);return Number.isNaN(r.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function yh(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function lj(e){let r={...oj(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of nj)if(s in r){let c=a(r[s]);if(c!==void 0)i[o]=c;delete r[s]}let n={};for(let{property:s,field:o}of sj)if(s in r){let a=r[s];if(typeof a=="string")n[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,yh(r,"$set",e.$set),yh(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:aj(e.timestamp),...n,options:i,properties:r}}function _h(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(lj)};if(r)i.historical_migration=!0;return i}var cj="/i/v1/analytics/events",dj=30000,uj=new Set([408,500,502,503,504]);class Cl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??dj,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>de(i,r))),this.generateRequestId=t.generateRequestId??Ie,this.compress=t.compress??qt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=_h(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${cj}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let c=1;c<=a;c++){let u=c===a,l=br({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),d;try{d=await this.sendOnce(n,l,c,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(c));continue}let{status:p}=d;if(p<200||p>=300){if(!u&&uj.has(p)){let y=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(c,y));continue}let g=await this.buildHttpError(d,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${p} response body`))}let m=this.classify(o,f,s);if(m.length===0)return this.surfacePartialDrops(t,s);if(u)return void this.onError(new xr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(c,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);if(c!==null)s=c,n["Content-Encoding"]="gzip"}let o=new AbortController,a=de(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:n,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)i["User-Agent"]=this.config.userAgent;return i}classify(e,t,r){let i=t.results??{},n=[];for(let s of e){let o=i[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")n.push(s)}}return n}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let s=parseInt(r,10);return Number.isFinite(s)&&s>0?1000*s:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let n=i-this.now();return n>0?n:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let i=r.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let i=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,i){this.onError(new xr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new xr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var pj=100,Ph=30000,fj=50000,mj=50,hj=500,gj="https://us.i.posthog.com",bh=new Set;function fs(e,t){if(bh.has(e))return;bh.add(e),console.warn(`[PostHog] ${t}`)}function yj(e){return typeof e=="string"?e.trim():""}function _j(e){return(typeof e=="string"?e.trim():"")||void 0}function Pj(e){return(typeof e=="string"?e.trim():"")||gj}function bj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function vj(e){if(!e)return{};let t={};for(let[i,n]of Object.entries(e))t[`$feature/${i}`]=n;let r=Object.keys(e).filter((i)=>e[i]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class jl extends us{constructor(e,t={}){let r=yj(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:Pj(t.host),personalApiKey:_j(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new xl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=hh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,pj):Ph,typeof i.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0);if(typeof i.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0);if(!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(i.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Sl({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation})}this.errorTracking=new Ye(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||fj}enqueue(e,t,r){super.enqueue(e,t,r),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,o=new Promise((a)=>{s=a});try{e(o)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??hj,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??mj;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},n)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&gh(e)?Oi:Fi}persistedQueueKeyForRoute(e){return e===Oi?Ee.AiQueue:Ee.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Fi,Oi]:[Fi]}async sendBatch(e,t,r=Fi){if(this.captureMode!=="v1"||r===Oi)return super.sendBatch(e,t,r);let i=e.filter((n)=>n!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Cl({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return ih}get metrics(){if(!this._metrics)this._metrics=new es(this,Zn(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:n,event:s,properties:o,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c):this.enqueue(e,u,c)}).catch((n)=>{if(n)console.error(n)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let i={};if(Object.keys(t).length>0)i.$set=t;if(Object.keys(r).length>0)i.$set_once=r;this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=bj(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=Ph){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",(n)=>{clearTimeout(r),i(),t(n>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let n=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let E=this._flagOverrides[e];if(E===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,y,P,v,w;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let E=this.featureFlagsPoller?.featureFlagsByKey[e];if(E)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(E,d,{matchValue:i});if(x){f=!0;let T=x.value;y=E.id,v="Evaluated locally",w=E.has_experiment,p={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof Qe||x instanceof q)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!f&&!a){let E=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,o,[e]);if(E===void 0)g=ct.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(ct.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(ct.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(ct.FLAG_MISSING);else{y=T.metadata?.id,P=T.metadata?.version,v=T.reason?.description??T.reason?.code,w=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}p={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(n){let E=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,x={$feature_flag:e,$feature_flag_response:E,$feature_flag_id:y,$feature_flag_version:P,$feature_flag_reason:v,locally_evaluated:f,[`$feature/${e}`]:E,$feature_flag_request_id:m,$feature_flag_evaluated_at:f?Date.now():h};if(w!==void 0)x.$feature_flag_has_experiment=w;if(f&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(T!==void 0)x.$feature_flag_definitions_loaded_at=T}if(g)x.$feature_flag_error=g;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:E,groups:s,disableGeoip:o,properties:x})}if(p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)p={...p,payload:this._payloadOverrides[e]};return p}async getFeatureFlag(e,t,r){fs("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return i.variant??!0}async getFeatureFlagPayload(e,t,r,i){if(fs("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(n===void 0)return;return n.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:n}=this._resolveDistinctId(t,r);if(!i)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,i,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(i){}return r}async isFeatureEnabled(e,t,r){fs("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,c,u,s,o);f={...f,...g.flags||{}},m={...m,...g.payloads||{}}}if(this._flagOverrides!==void 0)f={...f,...this._flagOverrides};if(this._payloadOverrides!==void 0)m={...m,...this._payloadOverrides};return{featureFlags:f,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),P=new Set;if(y)for(let[w,I]of Object.entries(y.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:y.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},P.add(w)}if((y?y.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,s,o);if(w){this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt,h=Boolean(w.errorsWhileComputingFlags),g=Array.isArray(w.quotaLimited)&&w.quotaLimited.includes("feature_flags");for(let[I,E]of Object.entries(w.flags)){if(P.has(I))continue;let x;if(E.metadata?.payload!==void 0)try{x=JSON.parse(E.metadata.payload)}catch{x=E.metadata.payload}p[I]={key:I,enabled:E.enabled,variant:E.variant,payload:x,id:E.metadata?.id,version:E.metadata?.version,reason:E.reason?.description??E.reason?.code,locallyEvaluated:!1,hasExperiment:E.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[w,I]of Object.entries(this._flagOverrides)){if(I===void 0){delete p[w];continue}let E=p[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:E?.payload,id:E?.id,version:E?.version,reason:E?.reason,locallyEvaluated:E?.locallyEvaluated??!1,hasExperiment:E?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[w,I]of Object.entries(this._payloadOverrides)){let E=p[w];if(E)p[w]={...E,payload:I}}return new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:n,disableGeoip:s,flags:p,requestId:f,evaluatedAt:m,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:h,quotaLimited:g})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:n,disableGeoip:s,properties:o}=e,a=n&&Object.keys(n).length>0?`_${JSON.stringify(Object.entries(n).sort(([u],[l])=>u<l?-1:u>l?1:0))}`:"",c=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(c);else this.distinctIdHasSentFlagCalls[t]=new Set([c]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:n,disableGeoip:s})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((i)=>[i,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((i)=>de(i,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.options.requestTimeout),r.signal=n.signal}try{return await this.fetch(t,r)}catch(n){this._events.emit("error",n);return}finally{if(i)clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[n,s]of Object.entries(e))if(im(s)&&t&&n in t){let o={};for(let[a,c]of Object.entries(s))o[String(a)]=String(c);i[String(n)]=o}else r[String(n)]=String(s);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let n=i?.personProperties||{},s=i?.groupProperties||{},o=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,n,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let n={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...i?.[o]||{}};return{allPersonProperties:n,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,n){if(!Ye.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:i,flags:n},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!Ye.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((s)=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:n,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=e,d=this.context?.get(),p=t.includeContextProperties??!0,f=r||d?.distinctId,m=p?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};if(!f)f=Ie(),m.$process_person_profile=!1;if(p&&d?.sessionId&&!m.$session_id)m.$session_id=d.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?vi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(o){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(a){fs("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let P=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,P);return vj(v)}return{}}).catch(()=>({})).then((P)=>{let v=g.groups||s;return{...P,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"){if(Qf(y.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",y.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:y,options:{timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let n of r){if(i=n(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}}var vh=require("async_hooks");class Fl{constructor(){this.storage=new vh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function wj(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(n==="*"||n.includes(o.level)))return o;if(!o.tags)o.tags={};let c=o.tags[wh.POSTHOG_ID_TAG];if(c===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();o.tags["PostHog Person URL"]=l;let d=o.exception?.values||[],p=d.map((m)=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map((h)=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags};if(t&&r)f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:c,properties:f});return o}}class wh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,n){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(wj(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ol extends jl{getLibraryId(){return"posthog-node"}initializeContext(){return new Fl}createErrorPropertiesBuilder(){return new ve.ErrorPropertiesBuilder([new ve.EventCoercer,new ve.ErrorCoercer,new ve.ObjectCoercer,new ve.StringCoercer,new ve.PrimitiveCoercer],ve.createStackParser("node:javascript",ve.nodeStackLineParser),[Wf(),Zm,rh()])}}var Eh=require("crypto"),Z=require("fs/promises"),Y=require("path");var $h={name:"@toloka-platform/sdk",version:"0.1.0-preview.4",private:!1,description:"Preview. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"preview"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build",test:"vitest run",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","posthog-node":"5.46.1"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},engines:{bun:"1.4.0"}};var Kt=$h.version,dt="@toloka-platform/sdk",hs="toloka-build",Ih=`.claude/skills/${hs}/SKILL.md`,Sh=`.cursor/rules/${hs}.mdc`,Rr="AGENTS.md",ms="<!-- toloka:begin -->",Ti="<!-- toloka:end -->",Ej=/<!-- toloka:sdk-version ([^\s>]+) -->/u,Ij=/<!-- toloka:skill-digest sha256:([a-f0-9]{64}) -->/u,Sj=[Ih,Sh,Rr],xh="toloka-pipeline-as-code",Rh=Y.join(".claude","skills",xh),Ch=Y.join(".cursor","rules",`${xh}.mdc`),xj=[Rh,Ch],Rj=[Y.join(Rh,"SKILL.md"),Ch],Cj=[["SKILL.md",new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/node-semantics.md",new URL("../../skills/references/node-semantics.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/workflow-and-cli.md",new URL("../../skills/references/workflow-and-cli.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")]],Ai=(e)=>e instanceof Error&&("code"in e)&&e.code==="ENOENT",gs=async(e)=>{try{return await Z.readFile(e,"utf8")}catch(t){if(Ai(t))return;throw t}},Tl=async(e)=>{try{return(await Z.lstat(e)).isDirectory()}catch(t){if(Ai(t))return!1;throw t}},jj=async(e)=>{try{return(await Z.lstat(e)).isFile()}catch(t){if(Ai(t))return!1;throw t}},jh=async(e,t)=>{let r=e;for(let i of t.split("/")){r=Y.join(r,i);try{let n=await Z.lstat(r);_(!n.isSymbolicLink(),`Refusing to write through symbolic link ${r}.`)}catch(n){if(Ai(n))return;throw n}}};async function Fh(){let e=Eh.createHash("sha256");for(let[t,r]of Cj)e.update(t),e.update("\x00"),e.update(await Z.readFile(r)),e.update("\x00");return e.digest("hex")}var Fj=new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts"),Oj=`node_modules/${dt}/skills/references/`,Tj=async(e)=>{let n=(await Z.readFile(Fj,"utf8")).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/u,"").replace(/^#\s.*\r?\n+/u,"").replaceAll("](references/",`](${Oj}`).replaceAll("](../examples/",`](node_modules/${dt}/examples/`);return e==="##"?n:n.replaceAll(/^## /gmu,"### ")},Al=async(e,t)=>`Generated by \`${dt}\` version \`${Kt}\`.
56
56
  <!-- toloka:sdk-version ${Kt} -->
57
57
  <!-- toloka:skill-digest sha256:${t} -->
58
58
 
59
- ${await Oj(e)}
60
- Use the globally installed \`toloka\` binary. Install it with \`bun add --global ${Xe}@preview\` if it is not on \`PATH\`.
59
+ ${await Tj(e)}
60
+ Use the globally installed \`toloka\` binary. Install it with \`curl -fsSL https://platform.toloka.ai/cli/install.sh | sh\` if it is not on \`PATH\`.
61
61
 
62
62
  If the reference paths above are missing, keep following the workflow and constraints in this file, do not invent SDK helpers or CLI commands, and install the project's declared dependencies before validating, planning, or applying. When no project is selected, use \`toloka project add\` to adopt one or \`toloka project create\` to create one. Adopt live source with \`toloka import\`.
63
63
 
64
- `,Tj=async(e)=>`---
64
+ `,Aj=async(e)=>`---
65
65
  name: ${hs}
66
66
  description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka. Use when the user wants to create, adopt, inspect, plan, or apply a pipeline project as code.
67
67
  ---
68
68
 
69
69
  # Build Toloka pipelines as code
70
70
 
71
- ${await Al("##",e)}`,Aj=async(e)=>`---
71
+ ${await Al("##",e)}`,kj=async(e)=>`---
72
72
  description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka
73
73
  alwaysApply: false
74
74
  ---
75
75
 
76
76
  # Build Toloka pipelines as code
77
77
 
78
- ${await Al("##",e)}`,kj=async(e)=>`${ms}
78
+ ${await Al("##",e)}`,Dj=async(e)=>`${ms}
79
79
  ## Build Toloka pipelines as code
80
80
 
81
81
  ${(await Al("###",e)).trimEnd()}
82
- ${Ti}`,Dj=(e,t)=>{let r=e.indexOf(ms),i=e.indexOf(Ti),n=r!==-1,s=i!==-1,o=e.includes(`\r
82
+ ${Ti}`,Nj=(e,t)=>{let r=e.indexOf(ms),i=e.indexOf(Ti),n=r!==-1,s=i!==-1,o=e.includes(`\r
83
83
  `)?`\r
84
84
  `:`
85
85
  `,a=t.replaceAll(`
86
- `,o);if(!n&&!s){if(e.length===0)return`${a}${o}`;let c=e.endsWith(`${o}${o}`)?"":e.endsWith(o)?o:`${o}${o}`;return`${e}${c}${a}${o}`}return _(n&&s&&r<i,`Malformed toloka block in ${Rr}.`),_(!e.includes(ms,r+ms.length)&&!e.includes(Ti,i+Ti.length),`Multiple toloka blocks found in ${Rr}.`),`${e.slice(0,r)}${a}${e.slice(i+Ti.length)}`},Nj=async(e)=>{if(await Tl(Y.join(e,"node_modules",Xe)))return!0;let t=await gs(Y.join(e,"package.json"));if(t===void 0)return!1;let r=JSON.parse(t);return _(typeof r==="object"&&r!==null,"package.json must contain a JSON object."),["dependencies","devDependencies"].some((i)=>{let n=Reflect.get(r,i);return typeof n==="object"&&n!==null&&typeof Reflect.get(n,Xe)==="string"})},Lj=async(e,t)=>{if(await gs(e)===t)return!1;return await Z.mkdir(Y.dirname(e),{recursive:!0}),await Z.writeFile(e,t,"utf8"),!0},qj=async(e)=>{try{return await Z.lstat(e)}catch(t){if(Ai(t))return;throw t}},Mj=async(e)=>(await Promise.all(Sj.map(async(r)=>{let i=Y.join(e,r),n=await qj(i);if(n===void 0)return;return _(!n.isSymbolicLink(),`Refusing to remove legacy agent entry point through symbolic link ${i}.`),await Ch(e,r.split(Y.sep).join("/")),await Z.rm(i,{recursive:!0,force:!0}),r}))).filter((r)=>r!==void 0),Uj=(e,t,r,i)=>[`${r.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${Xe} ${Kt} in ${e}:`,...t.map((n)=>` ${n}`),...i.map((n)=>` removed ${n} (renamed to ${hs})`)].join(`
87
- `),Bj=async(e,t)=>{if(t===void 0)return;let r=await $e(e);if(_(r===void 0||r.projectId===t,`This directory is already bound to ${r?.projectId}.`),r!==void 0)return;return await Nt(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function Fh(e,t={}){await Z.mkdir(e,{recursive:!0});let r=await Z.realpath(e),i=await Bj(r,t.projectId),[n,s,o,a]=await Promise.all([Tl(Y.join(r,".claude")),Tl(Y.join(r,".cursor","rules")),Cj(Y.join(r,Rr)),jh()]),c=!n&&!s&&!o,l=[{relativePath:Eh,wanted:n||c,source:()=>Tj(a)},{relativePath:Ih,wanted:s,source:()=>Aj(a)},{relativePath:Rr,wanted:o||c,source:async()=>{let y=await gs(Y.join(r,Rr));return Dj(y??"",await kj(a))}}].filter((y)=>y.wanted);await Promise.all(l.map((y)=>Ch(r,y.relativePath)));let d=await Promise.all(l.map(async(y)=>({relativePath:y.relativePath,source:await y.source()}))),p=i===void 0?[]:[i];for(let y of d)if(await Lj(Y.join(r,y.relativePath),y.source))p.push(y.relativePath);let f=await Mj(r),m=await Nj(r),h=[...d.map((y)=>y.relativePath),...i===void 0?[]:[i]],g=m?void 0:`Warning: ${Xe} is not listed in dependencies or devDependencies in ${Y.join(r,"package.json")}. Run \`bun add --dev ${Xe}\` before using \`toloka\`, then re-run \`toloka init\`.`;return{targetDirectory:r,files:h,writtenFiles:p,sdkVersion:Kt,skillDigest:a,dependencyReady:m,output:Uj(r,h,p,f),...g===void 0?{}:{warning:g}}}async function Oh(e){let t=await jh(),r=new Set,i=new Set;for(let s of[...Ij,...xj]){let o=await gs(Y.join(e,s));if(o===void 0)continue;let a=Ej.exec(o)?.[1];if(a!==void 0&&a!==t){r.add(a.slice(0,12));let c=$j.exec(o)?.[1];if(c!==void 0)i.add(c)}}if(r.size===0)return;let n=i.size===0?"an earlier build":[...i].toSorted().join(", ");return`Warning: Agent instructions generated by ${Xe} ${n} do not match the installed ${Kt} skill content (${[...r].toSorted().join(", ")} -> ${t.slice(0,12)}). Re-run \`toloka init\`.`}var Gj="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",Vj="https://eu.posthog.com",Kj={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0},ys=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},zj=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};function Wj(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(zj(t))return!1;if(ys(t))return!0;if(ys(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(ys(e.CI??process.env.CI))return!1;if(ys(process.env.VITEST))return!1;return!0}var Hj={project:{list:!0,add:!0,switch:!0,current:!0,remove:!0,create:!0},pipeline:{list:!0,run:!0,status:!0,runs:!0,cost:!0,cancel:!0,results:!0},dataset:{list:!0,fields:!0,load:!0,upload:!0},secret:{set:!0}},Jj={apply:!0,"auth-status":!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,whoami:!0},kl=(e)=>{let t=e[0];if(t===void 0)return"help";let r=Hj[t];if(r===void 0)return Jj[t]===!0?t:"unknown";let i=e[1];return i!==void 0&&r[i]===!0?`${t} ${i}`:t};function Ah(e){let t=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i===void 0)continue;if(i==="--help"||i==="-h")break;if(i.startsWith("-")){if(Kj[i]===!0)r+=1;continue}t.push(i)}return kl(t)}function Qj(e){if(e===void 0)return{error_code:"command_failed"};if(e instanceof re||e instanceof er)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var Yj=(e)=>_s.join(_s.dirname(Ue(e)),"anonymous-id"),Xj=async(e)=>{let t=Yj(e);await Za(t);try{let i=(await zt.readFile(t,"utf8")).trim();if(i.length>0)return await zt.chmod(t,384),i}catch(i){if(!(i instanceof Error&&("code"in i)&&i.code==="ENOENT"))throw i}let r=Th.randomUUID();return await zt.writeFile(t,`${r}
88
- `,{mode:384}),await zt.chmod(t,384),r},Zj=()=>({shouldIdentify:!1,identifyCurrentUser(){},captureCommand(){},async shutdown(){}});function kh(e){let{environment:t}=e;if(e.client===void 0&&!Wj(t))return Zj();let{client:r,distinctId:i}=e,n,s=async()=>{if(r!==void 0&&i!==void 0)return;if(r===void 0){let c=new Ol(Gj,{host:Vj,flushAt:1,flushInterval:0});c.on("error",()=>{}),r=c}i??=await Xj(t)},o=()=>({sdk_version:Kt,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),a=s().catch(()=>{});return{shouldIdentify:!0,identifyCurrentUser(c){a=a.then(()=>{if(r===void 0||i===void 0)return;if(n===c.id)return;if(n=c.id,i!==c.id)r.alias({distinctId:c.id,alias:i});i=c.id}).catch(()=>{})},captureCommand(c){a=a.then(()=>{if(r===void 0||i===void 0)return;let u=o();if(c.outcome==="failed"){let l=Qj(c.error);r.capture({distinctId:i,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...u,command:kl(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,...l}});return}r.capture({distinctId:i,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...u,command:kl(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,outcome:c.outcome}})}).catch(()=>{})},async shutdown(){try{await a,await r?.shutdown(2000)}catch{}}}}var Tr=require("fs/promises"),Or=require("path");var qh=Symbol("sourceReference"),Mh={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},eF={arguments:!0,await:!0,break:!0,case:!0,catch:!0,class:!0,const:!0,continue:!0,debugger:!0,default:!0,delete:!0,do:!0,else:!0,enum:!0,eval:!0,export:!0,extends:!0,false:!0,finally:!0,for:!0,function:!0,if:!0,implements:!0,import:!0,in:!0,instanceof:!0,interface:!0,let:!0,new:!0,null:!0,package:!0,private:!0,protected:!0,public:!0,return:!0,static:!0,super:!0,switch:!0,this:!0,throw:!0,true:!0,try:!0,typeof:!0,var:!0,void:!0,while:!0,with:!0,yield:!0};function xt(e,t){return e<t?-1:e>t?1:0}function Dh(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Uh(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function Bh(e,t){let[r,...i]=Uh(e),s=`${(r??t).toLowerCase()}${i.map((a)=>`${a.slice(0,1).toUpperCase()}${a.slice(1).toLowerCase()}`).join("")}`,o=/^\d/.test(s)?`_${s}`:s;return Object.hasOwn(eF,o)?`${o}Value`:o}function tF(e,t){return Uh(e).map((r)=>r.toLowerCase()).join("-")||t}function Dl(e,t,r){let i=new Map,n=new Set;for(let c of e){_(!n.has(c.key),`Naming key "${c.key}" is duplicated`),n.add(c.key);let u=t(c),l=i.get(u)??[];l.push(c),i.set(u,l)}let s=new Set(i.keys()),o=new Set,a=new Map;for(let[c,u]of[...i.entries()].toSorted(([l],[d])=>xt(l,d))){let l=u.toSorted((d,p)=>xt(d.key,p.key));for(let d of l){let p=c;if(l.length>1||r!==void 0&&Object.hasOwn(r,p))p=`${c}_${Dh(d.key)}`;let f=2;while(o.has(p)||r!==void 0&&Object.hasOwn(r,p)||p!==c&&s.has(p))p=`${c}_${Dh(d.key)}_${f}`,f+=1;o.add(p),a.set(d.key,p)}}return a}function rF(e){return typeof e==="object"&&e!==null&&qh in e}function ee(e){return" ".repeat(e)}function Te(e,t=0){if(rF(e))return e.name;if(_(e!==void 0,"Cannot emit an undefined source value"),typeof e==="number")_(Number.isFinite(e),"Cannot emit a non-finite number");if(e===null||typeof e!=="object"){let n=JSON.stringify(e);return _(n!==void 0,`Cannot emit a ${typeof e} source value`),n}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
86
+ `,o);if(!n&&!s){if(e.length===0)return`${a}${o}`;let c=e.endsWith(`${o}${o}`)?"":e.endsWith(o)?o:`${o}${o}`;return`${e}${c}${a}${o}`}return _(n&&s&&r<i,`Malformed toloka block in ${Rr}.`),_(!e.includes(ms,r+ms.length)&&!e.includes(Ti,i+Ti.length),`Multiple toloka blocks found in ${Rr}.`),`${e.slice(0,r)}${a}${e.slice(i+Ti.length)}`},Lj=async(e)=>{if(await Tl(Y.join(e,"node_modules",dt)))return!0;let t=await gs(Y.join(e,"package.json"));if(t===void 0)return!1;let r=JSON.parse(t);return _(typeof r==="object"&&r!==null,"package.json must contain a JSON object."),["dependencies","devDependencies"].some((i)=>{let n=Reflect.get(r,i);return typeof n==="object"&&n!==null&&typeof Reflect.get(n,dt)==="string"})},qj=async(e,t)=>{if(await gs(e)===t)return!1;return await Z.mkdir(Y.dirname(e),{recursive:!0}),await Z.writeFile(e,t,"utf8"),!0},Mj=async(e)=>{try{return await Z.lstat(e)}catch(t){if(Ai(t))return;throw t}},Uj=async(e)=>(await Promise.all(xj.map(async(r)=>{let i=Y.join(e,r),n=await Mj(i);if(n===void 0)return;return _(!n.isSymbolicLink(),`Refusing to remove legacy agent entry point through symbolic link ${i}.`),await jh(e,r.split(Y.sep).join("/")),await Z.rm(i,{recursive:!0,force:!0}),r}))).filter((r)=>r!==void 0),Bj=(e,t,r,i)=>[`${r.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${dt} ${Kt} in ${e}:`,...t.map((n)=>` ${n}`),...i.map((n)=>` removed ${n} (renamed to ${hs})`)].join(`
87
+ `),Gj=async(e,t)=>{if(t===void 0)return;let r=await $e(e);if(_(r===void 0||r.projectId===t,`This directory is already bound to ${r?.projectId}.`),r!==void 0)return;return await Nt(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function Oh(e,t={}){await Z.mkdir(e,{recursive:!0});let r=await Z.realpath(e),i=await Gj(r,t.projectId),[n,s,o,a]=await Promise.all([Tl(Y.join(r,".claude")),Tl(Y.join(r,".cursor","rules")),jj(Y.join(r,Rr)),Fh()]),c=!n&&!s&&!o,l=[{relativePath:Ih,wanted:n||c,source:()=>Aj(a)},{relativePath:Sh,wanted:s,source:()=>kj(a)},{relativePath:Rr,wanted:o||c,source:async()=>{let y=await gs(Y.join(r,Rr));return Nj(y??"",await Dj(a))}}].filter((y)=>y.wanted);await Promise.all(l.map((y)=>jh(r,y.relativePath)));let d=await Promise.all(l.map(async(y)=>({relativePath:y.relativePath,source:await y.source()}))),p=i===void 0?[]:[i];for(let y of d)if(await qj(Y.join(r,y.relativePath),y.source))p.push(y.relativePath);let f=await Uj(r),m=await Lj(r),h=[...d.map((y)=>y.relativePath),...i===void 0?[]:[i]],g=m?void 0:`Warning: ${dt} is not listed in dependencies or devDependencies in ${Y.join(r,"package.json")}. Run \`bun add --dev ${dt}\` before using \`toloka\`, then re-run \`toloka init\`.`;return{targetDirectory:r,files:h,writtenFiles:p,sdkVersion:Kt,skillDigest:a,dependencyReady:m,output:Bj(r,h,p,f),...g===void 0?{}:{warning:g}}}async function Th(e){let t=await Fh(),r=new Set,i=new Set;for(let s of[...Sj,...Rj]){let o=await gs(Y.join(e,s));if(o===void 0)continue;let a=Ij.exec(o)?.[1];if(a!==void 0&&a!==t){r.add(a.slice(0,12));let c=Ej.exec(o)?.[1];if(c!==void 0)i.add(c)}}if(r.size===0)return;let n=i.size===0?"an earlier build":[...i].toSorted().join(", ");return`Warning: Agent instructions generated by ${dt} ${n} do not match the installed ${Kt} skill content (${[...r].toSorted().join(", ")} -> ${t.slice(0,12)}). Re-run \`toloka init\`.`}var Vj="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",Kj="https://eu.posthog.com",zj={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0},ys=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},Wj=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};function Hj(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(Wj(t))return!1;if(ys(t))return!0;if(ys(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(ys(e.CI??process.env.CI))return!1;if(ys(process.env.VITEST))return!1;return!0}var Jj={project:{list:!0,add:!0,switch:!0,current:!0,remove:!0,create:!0},pipeline:{list:!0,run:!0,status:!0,runs:!0,cost:!0,cancel:!0,results:!0},dataset:{list:!0,fields:!0,load:!0,upload:!0},secret:{set:!0}},Qj={apply:!0,"auth-status":!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,whoami:!0},kl=(e)=>{let t=e[0];if(t===void 0)return"help";let r=Jj[t];if(r===void 0)return Qj[t]===!0?t:"unknown";let i=e[1];return i!==void 0&&r[i]===!0?`${t} ${i}`:t};function kh(e){let t=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i===void 0)continue;if(i==="--help"||i==="-h")break;if(i.startsWith("-")){if(zj[i]===!0)r+=1;continue}t.push(i)}return kl(t)}function Yj(e){if(e===void 0)return{error_code:"command_failed"};if(e instanceof re||e instanceof er)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var Xj=(e)=>_s.join(_s.dirname(Ue(e)),"anonymous-id"),Zj=async(e)=>{let t=Xj(e);await Za(t);try{let i=(await zt.readFile(t,"utf8")).trim();if(i.length>0)return await zt.chmod(t,384),i}catch(i){if(!(i instanceof Error&&("code"in i)&&i.code==="ENOENT"))throw i}let r=Ah.randomUUID();return await zt.writeFile(t,`${r}
88
+ `,{mode:384}),await zt.chmod(t,384),r},eF=()=>({shouldIdentify:!1,identifyCurrentUser(){},captureCommand(){},async shutdown(){}});function Dh(e){let{environment:t}=e;if(e.client===void 0&&!Hj(t))return eF();let{client:r,distinctId:i}=e,n,s=async()=>{if(r!==void 0&&i!==void 0)return;if(r===void 0){let c=new Ol(Vj,{host:Kj,flushAt:1,flushInterval:0});c.on("error",()=>{}),r=c}i??=await Zj(t)},o=()=>({sdk_version:Kt,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),a=s().catch(()=>{});return{shouldIdentify:!0,identifyCurrentUser(c){a=a.then(()=>{if(r===void 0||i===void 0)return;if(n===c.id)return;if(n=c.id,i!==c.id)r.alias({distinctId:c.id,alias:i});i=c.id}).catch(()=>{})},captureCommand(c){a=a.then(()=>{if(r===void 0||i===void 0)return;let u=o();if(c.outcome==="failed"){let l=Yj(c.error);r.capture({distinctId:i,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...u,command:kl(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,...l}});return}r.capture({distinctId:i,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...u,command:kl(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,outcome:c.outcome}})}).catch(()=>{})},async shutdown(){try{await a,await r?.shutdown(2000)}catch{}}}}var Tr=require("fs/promises"),Or=require("path");var Mh=Symbol("sourceReference"),Uh={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},tF={arguments:!0,await:!0,break:!0,case:!0,catch:!0,class:!0,const:!0,continue:!0,debugger:!0,default:!0,delete:!0,do:!0,else:!0,enum:!0,eval:!0,export:!0,extends:!0,false:!0,finally:!0,for:!0,function:!0,if:!0,implements:!0,import:!0,in:!0,instanceof:!0,interface:!0,let:!0,new:!0,null:!0,package:!0,private:!0,protected:!0,public:!0,return:!0,static:!0,super:!0,switch:!0,this:!0,throw:!0,true:!0,try:!0,typeof:!0,var:!0,void:!0,while:!0,with:!0,yield:!0};function xt(e,t){return e<t?-1:e>t?1:0}function Nh(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Bh(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function Gh(e,t){let[r,...i]=Bh(e),s=`${(r??t).toLowerCase()}${i.map((a)=>`${a.slice(0,1).toUpperCase()}${a.slice(1).toLowerCase()}`).join("")}`,o=/^\d/.test(s)?`_${s}`:s;return Object.hasOwn(tF,o)?`${o}Value`:o}function rF(e,t){return Bh(e).map((r)=>r.toLowerCase()).join("-")||t}function Dl(e,t,r){let i=new Map,n=new Set;for(let c of e){_(!n.has(c.key),`Naming key "${c.key}" is duplicated`),n.add(c.key);let u=t(c),l=i.get(u)??[];l.push(c),i.set(u,l)}let s=new Set(i.keys()),o=new Set,a=new Map;for(let[c,u]of[...i.entries()].toSorted(([l],[d])=>xt(l,d))){let l=u.toSorted((d,p)=>xt(d.key,p.key));for(let d of l){let p=c;if(l.length>1||r!==void 0&&Object.hasOwn(r,p))p=`${c}_${Nh(d.key)}`;let f=2;while(o.has(p)||r!==void 0&&Object.hasOwn(r,p)||p!==c&&s.has(p))p=`${c}_${Nh(d.key)}_${f}`,f+=1;o.add(p),a.set(d.key,p)}}return a}function iF(e){return typeof e==="object"&&e!==null&&Mh in e}function ee(e){return" ".repeat(e)}function Te(e,t=0){if(iF(e))return e.name;if(_(e!==void 0,"Cannot emit an undefined source value"),typeof e==="number")_(Number.isFinite(e),"Cannot emit a non-finite number");if(e===null||typeof e!=="object"){let n=JSON.stringify(e);return _(n!==void 0,`Cannot emit a ${typeof e} source value`),n}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
89
89
  ${e.map((s)=>`${ee(t+1)}${Te(s,t+1)}`).join(`,
90
90
  `)}
91
91
  ${ee(t)}]`}let r=Object.entries(e).filter(([,n])=>n!==void 0).toSorted(([n],[s])=>xt(n,s));if(r.length===0)return"{}";return`{
92
92
  ${r.map(([n,s])=>{let o=n==="__proto__"?`[${JSON.stringify(n)}]`:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)?n:JSON.stringify(n);return`${ee(t+1)}${o}: ${Te(s,t+1)}`}).join(`,
93
93
  `)}
94
- ${ee(t)}}`}function ki(e,t){return{field:t(e.id),optional:e.optional}}function Ps(e,t){let{fieldProxyId:r,relations:i,...n}=e;return{...n,field:t(r),...i===void 0?{}:{relations:i.map(({id:s,...o})=>({...o,field:t(s)}))}}}function Nl(e,t){let{targetEntity:r,...i}=e;return{...i,targetEntity:t(r)}}function Nh(e,t){return{...e,gradedEntities:e.gradedEntities.map((r)=>Nl(r,t))}}function iF(e,t){switch(e.type){case"root":{let{datasetId:r,itemFilter:i,startedFieldProxies:n,completedFieldProxies:s,...o}=e.settings;return{...o,started:n.output.map((a)=>ki(a,t)),completed:s.input.map((a)=>ki(a,t))}}case"code":{let{fieldProxies:r,...i}=e.settings;return{...i,fieldProxies:{input:r.input.map((n)=>ki(n,t)),output:r.output.map((n)=>ki(n,t))}}}case"generation":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Ps(o,t)),output:r.output.map((o)=>Ps(o,t))},qualityCriteria:i.map((o)=>Nl(o,t)),...n===void 0?{}:{exam:Nh(n,t)}}}case"match":{let{conditions:r,fieldProxies:i,...n}=e.settings;return{...n,conditions:r.map(({predicates:s,...o})=>({...o,predicates:s.map(({fieldProxyId:a,...c})=>({...c,field:t(a)}))})),fieldProxies:{input:i.input.map((s)=>ki(s,t))}}}case"quorum":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Ps(o,t)),output:r.output.map((o)=>Ps(o,t))},qualityCriteria:i.map((o)=>Nl(o,t)),...n===void 0?{}:{exam:Nh(n,t)}}}}}function nF(e,t,r,i){let n=new Set,o=iF(e,(l)=>{let d=i.get(l);return _(d,`Node "${e.id}" references unknown field "${l}"`),n.add(d),{name:d,[qh]:!0}}),a=[...n].toSorted(xt),c=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],u=e.type==="root"?[`${ee(1)}${Te(o,1)}`,`${ee(1)}${Te({id:e.id},1)}`]:[`${ee(1)}${Te(e.settings.about.name,1)}`,`${ee(1)}${Te(o,1)}`,`${ee(1)}${Te({id:e.id},1)}`];return{binding:t,path:r,source:`${c.join(`
94
+ ${ee(t)}}`}function ki(e,t){return{field:t(e.id),optional:e.optional}}function Ps(e,t){let{fieldProxyId:r,relations:i,...n}=e;return{...n,field:t(r),...i===void 0?{}:{relations:i.map(({id:s,...o})=>({...o,field:t(s)}))}}}function Nl(e,t){let{targetEntity:r,...i}=e;return{...i,targetEntity:t(r)}}function Lh(e,t){return{...e,gradedEntities:e.gradedEntities.map((r)=>Nl(r,t))}}function nF(e,t){switch(e.type){case"root":{let{datasetId:r,itemFilter:i,startedFieldProxies:n,completedFieldProxies:s,...o}=e.settings;return{...o,started:n.output.map((a)=>ki(a,t)),completed:s.input.map((a)=>ki(a,t))}}case"code":{let{fieldProxies:r,...i}=e.settings;return{...i,fieldProxies:{input:r.input.map((n)=>ki(n,t)),output:r.output.map((n)=>ki(n,t))}}}case"generation":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Ps(o,t)),output:r.output.map((o)=>Ps(o,t))},qualityCriteria:i.map((o)=>Nl(o,t)),...n===void 0?{}:{exam:Lh(n,t)}}}case"match":{let{conditions:r,fieldProxies:i,...n}=e.settings;return{...n,conditions:r.map(({predicates:s,...o})=>({...o,predicates:s.map(({fieldProxyId:a,...c})=>({...c,field:t(a)}))})),fieldProxies:{input:i.input.map((s)=>ki(s,t))}}}case"quorum":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Ps(o,t)),output:r.output.map((o)=>Ps(o,t))},qualityCriteria:i.map((o)=>Nl(o,t)),...n===void 0?{}:{exam:Lh(n,t)}}}}}function sF(e,t,r,i){let n=new Set,o=nF(e,(l)=>{let d=i.get(l);return _(d,`Node "${e.id}" references unknown field "${l}"`),n.add(d),{name:d,[Mh]:!0}}),a=[...n].toSorted(xt),c=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],u=e.type==="root"?[`${ee(1)}${Te(o,1)}`,`${ee(1)}${Te({id:e.id},1)}`]:[`${ee(1)}${Te(e.settings.about.name,1)}`,`${ee(1)}${Te(o,1)}`,`${ee(1)}${Te({id:e.id},1)}`];return{binding:t,path:r,source:`${c.join(`
95
95
  `)}
96
96
 
97
97
  export const ${t} = ${e.type}(
98
98
  ${u.join(`,
99
99
  `)}
100
100
  );
101
- `}}function Gh(e,t){if(e.length===0)return`export {};
101
+ `}}function Vh(e,t){if(e.length===0)return`export {};
102
102
  `;return`import { field } from '@toloka-platform/sdk';
103
103
 
104
104
  ${e.map((i)=>{let n=t(i),s=[`${ee(1)}${Te(i.name,1)}`,`${ee(1)}${Te(i.jsonSchema,1)}`,...i.options===void 0?[]:[`${ee(1)}${Te(i.options,1)}`]];return{binding:n,source:`export const ${n} = field(
@@ -107,7 +107,7 @@ ${s.join(`,
107
107
  );`}}).toSorted((i,n)=>xt(i.binding,n.binding)).map(({source:i})=>i).join(`
108
108
 
109
109
  `)}
110
- `}function Vh(e){let t=new Map(e.map((i)=>[i,`field:${i.options?.id??i.name}`])),r=Dl(e.map((i)=>({key:t.get(i)??"",name:i.name,fallback:"field"})),({name:i,fallback:n})=>Bh(i,n),Mh);return Gh(e,(i)=>{let n=t.get(i);_(n,`Field "${i.name}" has no source key`);let s=r.get(n);return _(s,`Field "${i.name}" has no source binding`),s})}function sF(e,t){return Gh(e.fields.map((r)=>({name:r.name,jsonSchema:r.jsonSchema,options:{id:r.id}})),(r)=>{let i=r.options?.id;_(i,`Field "${r.name}" has no source ID`);let n=t.get(i);return _(n,`Field "${i}" has no source binding`),n})}function Lh(e,t,r,i){let n=r.get(e.node);_(n,`Connection references unknown node "${e.node}"`);let s=i.get(n.id);switch(_(s,`Node "${n.id}" has no source binding`),n.type){case"root":return _(e.handle===(t==="output"?"started":"completed"),`Root ${t} handle "${e.handle}" cannot be authored`),`${s}.${t==="output"?"started":"completed"}`;case"code":case"generation":case"quorum":return _(e.handle===t,`${n.type} ${t} handle "${e.handle}" cannot be authored`),`${s}.${t}`;case"match":if(t==="input")return _(e.handle==="input",`Match input handle "${e.handle}" cannot be authored`),`${s}.input`;if(e.handle==="default")return`${s}.default`;let o=/^matched_(\d+)$/.exec(e.handle);_(o,`Match output handle "${e.handle}" cannot be authored`);let a=o[1];return _(a!==void 0,`Match output handle "${e.handle}" has no index`),_(String(Number(a))===a,`Match output handle "${e.handle}" is not canonical`),`${s}.matched(${a})`}}function oF(e,t,r,i,n){let s=new Map(e.nodes.map((d)=>[d.id,d])),o=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...i.values()].toSorted(xt).join(", ")} } from './fields';`],...r.toSorted((d,p)=>xt(d.path,p.path)).flatMap(({binding:d,path:p})=>[`import { ${d} } from './${p.slice(0,-3)}';`])],a=e.fields.map(({id:d})=>{let p=i.get(d);return _(p,`Field "${d}" has no source binding`),p}),c=e.nodes.map(({id:d})=>{let p=n.get(d);return _(p,`Node "${d}" has no source binding`),p}),u=e.connections.map((d)=>{let p=Lh(d.from,"output",s,n),f=Lh(d.to,"input",s,n);if(Object.keys(d.settings).length===0)return`connect(${p}, ${f})`;return`connect(
110
+ `}function Kh(e){let t=new Map(e.map((i)=>[i,`field:${i.options?.id??i.name}`])),r=Dl(e.map((i)=>({key:t.get(i)??"",name:i.name,fallback:"field"})),({name:i,fallback:n})=>Gh(i,n),Uh);return Vh(e,(i)=>{let n=t.get(i);_(n,`Field "${i.name}" has no source key`);let s=r.get(n);return _(s,`Field "${i.name}" has no source binding`),s})}function oF(e,t){return Vh(e.fields.map((r)=>({name:r.name,jsonSchema:r.jsonSchema,options:{id:r.id}})),(r)=>{let i=r.options?.id;_(i,`Field "${r.name}" has no source ID`);let n=t.get(i);return _(n,`Field "${i}" has no source binding`),n})}function qh(e,t,r,i){let n=r.get(e.node);_(n,`Connection references unknown node "${e.node}"`);let s=i.get(n.id);switch(_(s,`Node "${n.id}" has no source binding`),n.type){case"root":return _(e.handle===(t==="output"?"started":"completed"),`Root ${t} handle "${e.handle}" cannot be authored`),`${s}.${t==="output"?"started":"completed"}`;case"code":case"generation":case"quorum":return _(e.handle===t,`${n.type} ${t} handle "${e.handle}" cannot be authored`),`${s}.${t}`;case"match":if(t==="input")return _(e.handle==="input",`Match input handle "${e.handle}" cannot be authored`),`${s}.input`;if(e.handle==="default")return`${s}.default`;let o=/^matched_(\d+)$/.exec(e.handle);_(o,`Match output handle "${e.handle}" cannot be authored`);let a=o[1];return _(a!==void 0,`Match output handle "${e.handle}" has no index`),_(String(Number(a))===a,`Match output handle "${e.handle}" is not canonical`),`${s}.matched(${a})`}}function aF(e,t,r,i,n){let s=new Map(e.nodes.map((d)=>[d.id,d])),o=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...i.values()].toSorted(xt).join(", ")} } from './fields';`],...r.toSorted((d,p)=>xt(d.path,p.path)).flatMap(({binding:d,path:p})=>[`import { ${d} } from './${p.slice(0,-3)}';`])],a=e.fields.map(({id:d})=>{let p=i.get(d);return _(p,`Field "${d}" has no source binding`),p}),c=e.nodes.map(({id:d})=>{let p=n.get(d);return _(p,`Node "${d}" has no source binding`),p}),u=e.connections.map((d)=>{let p=qh(d.from,"output",s,n),f=qh(d.to,"input",s,n);if(Object.keys(d.settings).length===0)return`connect(${p}, ${f})`;return`connect(
111
111
  ${ee(3)}${p},
112
112
  ${ee(3)}${f},
113
113
  ${ee(3)}${Te(d.settings,3)}
@@ -123,45 +123,45 @@ export default definePipeline({
123
123
  nodes: ${l(c,1)},
124
124
  connections: ${l(u,1)}
125
125
  });
126
- `}function Kh(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((u)=>({key:`field:${u.id}`,name:u.name,fallback:"field"})),...e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type}))],i=Dl(r,({name:u,fallback:l})=>Bh(u,l),Mh),n=Dl(e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type})),({name:u,fallback:l})=>tF(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return _(l,`Field "${u.id}" has no allocated binding`),[u.id,l]})),o=new Map(e.nodes.map((u)=>{let l=i.get(`node:${u.id}`);return _(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),d=n.get(`node:${u.id}`);return _(l&&d,`Node "${u.id}" has no allocated source name`),nF(u,l,`nodes/${d}/node.ts`,s)}),c=[{path:"fields.ts",source:sF(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:oF(e,t.dataset,a,s,o)}].toSorted((u,l)=>xt(u.path,l.path));return Object.fromEntries(c.map(({path:u,source:l})=>[u,l]))}var dt=require("fs/promises"),Wt=require("path");var pg=xe(Ja(),1),fg=xe(cg(),1);var dg={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"}},required:["audienceType"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var mg=new pg.default({strict:!1});fg.default(mg);var ug=mg.compile(dg),qF=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function Wl(e){if(ug(e))return;let t=ug.errors;_(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=qF(n),o=`${s.path}
127
- ${s.reason}`;if(r.has(o))continue;r.add(o),i.push(s)}throw er.fromIssues(i)}var MF=Symbol("fieldDefinition"),UF=Symbol("pipelineDefinition"),gg=Symbol("portDefinition"),BF=Symbol("nodeFieldReferences");function yg(e,t){return{node:e,handle:t,direction:"input",[gg]:"input"}}function _g(e,t){return{node:e,handle:t,direction:"output",[gg]:"output"}}function Pg(e){return typeof e==="object"&&e!==null&&MF in e}function Hl(e,t){if(Pg(e)){t.push(e);return}if(Array.isArray(e)){for(let r of e)Hl(r,t);return}if(typeof e==="object"&&e!==null)for(let r of Object.values(e))Hl(r,t)}function GF(e){let t=[];return Hl(e,t),t}function hg(e){return Pg(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function VF(e,t={}){let r=t.id??"root",{started:i,completed:n,...s}=e;return{id:r,type:"root",settings:{...s,startedFieldProxies:{output:i.map(hg)},completedFieldProxies:{input:n.map(hg)}},started:_g(r,"started"),completed:yg(r,"completed"),[BF]:GF(e)}}var Xq=Object.assign(VF,{started:_g("root","started"),completed:yg("root","completed")});function KF(e){return typeof e==="object"&&e!==null&&UF in e}function ws(e){_(KF(e),"Invalid pipeline definition: expected a value returned by definePipeline"),_(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;_(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),_(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}Wl(e.graph)}function Li(e,t){let r={version:e.graph.version,fields:e.graph.fields.map((i)=>({...i})),nodes:e.graph.nodes.map((i)=>i.type==="root"?{...i,settings:{...i.settings,datasetId:t.datasetId}}:i),connections:e.graph.connections.map((i)=>({from:{...i.from},to:{...i.to},settings:{...i.settings}}))};return Wl(r),r}function bg(e){let t=new Set;for(let r of e.nodes){if(r.type!=="code")continue;for(let i of r.settings.envVars??[])if(i.type==="secret")t.add(i.secretName)}return[...t].toSorted((r,i)=>r.localeCompare(i))}var qi=require("fs/promises"),ge=require("path"),vg=require("url");var wg=async(e)=>{let t;try{t=await qi.readdir(e,{withFileTypes:!0})}catch(i){if(i instanceof Error&&Reflect.get(i,"code")==="ENOENT")return[];throw i}let r=[];for(let i of t.toSorted((n,s)=>n.name.localeCompare(s.name))){let n=ge.join(e,i.name);if(i.isDirectory())r.push(...await wg(n));else if(i.isFile()&&i.name==="pipeline.ts")r.push(n)}return r},zF="toloka.json",WF=async(e)=>{try{return(await qi.stat(ge.join(e,zF))).isFile()}catch{return!1}};async function $g(e){let t=ge.resolve(e);for(;;){if(await WF(t))return t;let r=ge.dirname(t);if(r===t)return;t=r}}async function $s(e){let t=await wg(ge.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(i)=>{let n=await qi.stat(i),s=vg.pathToFileURL(i);s.searchParams.set("version",`${n.mtimeMs}-${n.size}`);let o=await import(s.href);_(typeof o==="object"&&o!==null,`Invalid ${i}: expected a module`);let a=Reflect.get(o,"default");ws(a);let c=ge.relative(e,ge.dirname(i)).split(ge.sep).join("/");return{sourceDirectory:c,name:ge.basename(c),definition:a}}))).toSorted((i,n)=>i.sourceDirectory.localeCompare(n.sourceDirectory))}}var HF=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,Ql=(e)=>{if(Array.isArray(e))return e.map(Ql);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ql(r)]))},we=(e)=>JSON.stringify(Ql(e)),Eg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Sg=(e,t)=>{if(!Eg(e)||!Eg(t))return t;return Object.fromEntries(Object.keys(e).map((r)=>[r,Sg(e[r],t[r])]))},JF=(e,t)=>we(e)===we(Sg(e,t)),Mi=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},Yl=(e)=>{let t=Reflect.get(e.settings,"about");if(typeof t==="object"&&t!==null){let r=Reflect.get(t,"name");if(typeof r==="string"&&r.length>0)return`${r} (${e.id})`}return e.id},QF=(e)=>`${e.name} (${e.id})`,YF=(e,t)=>{let r=t.get(e.from.node),i=t.get(e.to.node),n=r===void 0?e.from.node:Yl(r),s=i===void 0?e.to.node:Yl(i);return`${n}.${e.from.handle} -> ${s}.${e.to.handle}`},Es=(e)=>new Map(e.map((t)=>[t.id,t])),Jl=(e,t,r,i)=>{let n=[];for(let[s,o]of[...e].toSorted(([a],[c])=>a.localeCompare(c))){let a=t.get(s);if(a===void 0)n.push(i(o,"added"));else if(!r(o,a))n.push(i(o,"changed"))}for(let[s,o]of[...t].toSorted(([a],[c])=>a.localeCompare(c)))if(!e.has(s))n.push(i(o,"removed"));return n};function XF(e,t){let r=Es(e.nodes),i=Es(t.nodes),n=new Map(e.connections.map((o)=>[we(o),o])),s=new Map(t.connections.map((o)=>[we(o),o]));return[...Jl(Es(e.fields),Es(t.fields),(o,a)=>we(o)===we(a),(o,a)=>({kind:"field",action:a,label:QF(o),id:o.id})),...Jl(r,i,JF,(o,a)=>({kind:"node",action:a,label:Yl(o),id:o.id})),...Jl(n,s,()=>!0,(o,a)=>({kind:"connection",action:a,label:YF(o,a==="removed"?i:r)})),...we(e.layout)===we(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var Xl=(e,t)=>{let r=t.nodes.find((n)=>n.type==="root"),i=r===void 0?{}:{...r.settings.itemFilter===void 0?{}:{itemFilter:r.settings.itemFilter},...r.settings.itemLimit===void 0?{}:{itemLimit:r.settings.itemLimit}};return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((n)=>n.type==="root"?{...n,settings:{...i,...n.settings}}:n)}},Is=(e)=>{let t=new Map;for(let r of e.pipelines){let i=t.get(r.definition.dataset);if(i===void 0)i=new Map,t.set(r.definition.dataset,i);for(let n of r.definition.graph.fields){let s=i.get(n.name);if(_(s===void 0||we(s.jsonSchema)===we(n.jsonSchema),`Dataset "${r.definition.dataset}" has conflicting schemas for field "${n.name}".`),s===void 0)i.set(n.name,n)}}return[...t].toSorted(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({name:r,fields:[...i.values()].toSorted((n,s)=>n.name.localeCompare(s.name))}))},ZF=(e)=>{let t=new Set;for(let r of e.pipelines)_(HF.test(r.sourceDirectory),`Invalid pipeline source directory ${r.sourceDirectory}`),_(!t.has(r.sourceDirectory),`Pipeline source directory ${r.sourceDirectory} is declared more than once`),t.add(r.sourceDirectory),ws(r.definition);Is(e)},eO=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.datasetId);if(i!==void 0)return _(i.name===e,`Dataset ${i.id} is bound as "${e}" but is named "${i.name}".`),i;let n=r.filter((s)=>s.name===e);return _(n.length<=1,`Project has multiple datasets named "${e}".`),n[0]},tO=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.pipelineId);if(i!==void 0)return i;let n=r.filter((s)=>s.name===e.name);return _(n.length<=1,`Project has multiple pipelines named "${e.name}".`),n[0]},rO=(e)=>{let t=e.action==="added"?"+":e.action==="removed"?"-":e.action==="missing"?"!":"~";switch(e.kind){case"pipeline":return`${t} Pipeline ${e.action}: ${e.label}`;case"dataset":return`${t} Dataset ${e.action}: ${e.label}`;case"datasetField":return`${t} Dataset field ${e.action}: ${e.dataset}.${e.label}`;case"secret":return`${t} Missing secret: ${e.label}`;case"node":return`${t} Node ${e.action} in ${e.pipeline}: ${e.label}`;case"connection":return`${t} Connection ${e.action} in ${e.pipeline}: ${e.label}`;case"field":return`${t} Graph field ${e.action} in ${e.pipeline}: ${e.label}`;case"layout":return`${t} Layout ${e.action} in ${e.pipeline}: ${e.label}`}},iO=(e,t)=>{if(e.length===0)return"No changes.";let r=e.length===1?"change":"changes",i=[`Plan: ${e.length} ${r}`,...e.map(rO)];if(t.length>0){i.push("","Required secrets are missing:");for(let n of t)i.push(` ${n}`);i.push("Run `toloka secret set <name>` before apply.")}return i.join(`
128
- `)},nO=async(e,t,r,i)=>{let n=t.map((o)=>({desired:o,dataset:eO(o.name,r?.datasets[o.name],i)})),s=await Promise.all(n.map(async({dataset:o})=>o===void 0?[]:Mi(e.datasets.listAllFields({datasetId:o.id}))));return n.map(({desired:o,dataset:a},c)=>{let u=s[c]??[],l=new Map(u.map((d)=>[d.name,d]));return{...o,...a===void 0?{}:{dataset:a},liveFields:u,missingFields:o.fields.filter((d)=>!l.has(d.name)),conflictingFields:o.fields.filter((d)=>{let p=l.get(d.name);return p!==void 0&&we(p.jsonSchema)!==we(d.jsonSchema)})}})},sO=async(e,t,r,i,n)=>{let s=t.pipelines.map((a)=>({source:a,pipeline:tO(a,r?.pipelines[a.sourceDirectory],n)})),o=await Promise.all(s.map(async({pipeline:a})=>a===void 0?void 0:e.pipelines.getGraph({pipelineId:a.id})));return s.map(({source:a,pipeline:c},u)=>{let l=o[u],d=i.find((f)=>f.name===a.definition.dataset)?.dataset,p=[];if(c!==void 0&&l!==void 0)p=d===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:XF(Xl(Li(a.definition,{datasetId:d.id}),l.graph),l.graph);return{source:a,...c===void 0?{}:{pipeline:c},...l===void 0?{}:{snapshot:l},graphChanges:p}})},oO=(e,t,r,i,n)=>{let s=[];for(let o of n)s.push({kind:"pipeline",action:"removed",label:o});for(let o of i)s.push({kind:"dataset",action:"removed",label:o});for(let o of e){if(o.dataset===void 0)s.push({kind:"dataset",action:"added",label:o.name});for(let a of o.missingFields)s.push({kind:"datasetField",action:"added",label:a.name,dataset:o.name});for(let a of o.conflictingFields)s.push({kind:"datasetField",action:"changed",label:a.name,dataset:o.name})}for(let o of t)if(o.pipeline===void 0)s.push({kind:"pipeline",action:"added",label:o.source.sourceDirectory});else for(let a of o.graphChanges)s.push({...a,pipeline:o.source.sourceDirectory});for(let o of r)s.push({kind:"secret",action:"missing",label:o});return s},Ss=async(e,t)=>{let r=t.source??await $s(t.sourceRoot);ZF(r);let i=await $e(t.sourceRoot),n=t.projectId??i?.projectId;_(n,he);let s=i?.projectId===n?i:void 0,o=new Set(r.pipelines.flatMap(({definition:P})=>bg(P.graph))),a=t.listAllSecrets===!0||o.size>0,[c,u,l]=await Promise.all([Mi(e.pipelines.listAll({projectId:n})),Mi(e.datasets.listAll({projectId:n})),a?e.secrets.list({projectId:n}):Promise.resolve([])]),d=Is(r),p=Object.keys(s?.datasets??{}).filter((P)=>!d.some((v)=>v.name===P)).toSorted(),f=Object.keys(s?.pipelines??{}).filter((P)=>!r.pipelines.some((v)=>v.sourceDirectory===P)).toSorted(),m=await nO(e,d,s,u),h=await sO(e,r,s,m,c),g=new Set(l.map((P)=>P.name)),y=[...o].filter((P)=>!g.has(P)).toSorted();return{projectId:n,source:r,state:i,datasets:m,pipelines:h,livePipelines:c,liveDatasets:u,liveSecrets:l,changes:oO(m,h,y,p,f),missingSecrets:y,removedDatasets:p,removedPipelines:f}},Ig=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",aO=(e)=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},lO=(e)=>{let t=Map.groupBy(e,(r)=>Ig(r.name));return new Map(e.map((r)=>{let i=Ig(r.name),n=(t.get(i)?.length??0)>1;return[r.id,`pipelines/${n?`${i}-${aO(r.id)}`:i}`]}))};async function xg(e,t){let r=(await Mi(e.pipelines.listAll({projectId:t.projectId}))).toSorted((P,v)=>P.name.localeCompare(v.name)||P.id.localeCompare(v.id)),i=await Promise.all(r.map((P)=>e.pipelines.getGraph({pipelineId:P.id}))),n=new Set;for(let P of i){let v=P.graph.nodes.find((w)=>w.type==="root");_(v?.settings.datasetId,"Every imported pipeline must have a bound dataset."),n.add(v.settings.datasetId)}let s=await Mi(e.datasets.listAll({projectId:t.projectId})),o=[];for(let P of[...n].toSorted()){let v=s.find((w)=>w.id===P);_(v,`Project ${t.projectId} has no dataset ${P}.`),o.push(v)}let a=new Map(o.map((P)=>[P.id,P])),c=lO(r),u={},l={},d={};for(let[P,v]of r.entries()){let w=i[P];_(w,`Pipeline ${v.id} has no graph snapshot.`);let I=w.graph.nodes.find((R)=>R.type==="root");_(I?.settings.datasetId,`Pipeline ${v.id} has no dataset binding.`);let E=a.get(I.settings.datasetId);_(E,`Pipeline ${v.id} references unknown dataset ${I.settings.datasetId}.`);let x=d[E.name];_(x===void 0||x.datasetId===E.id,`Project has multiple referenced datasets named "${E.name}".`),d[E.name]={datasetId:E.id};let T=c.get(v.id);_(T,`Pipeline ${v.id} has no source directory.`),l[T]={pipelineId:v.id};for(let[R,V]of Object.entries(Kh(w.graph,{dataset:E.name})))u[`${T}/${R}`]=V}await dt.mkdir(t.sourceRoot,{recursive:!0});let p=Wt.join(t.sourceRoot,"pipelines"),f=!1;try{f=(await dt.stat(p)).isDirectory()}catch(P){if(!(P instanceof Error)||!("code"in P)||P.code!=="ENOENT")throw P}if(_(!f||t.force===!0,`Folder already exists: ${p}. Pass --force to replace it.`),f)await dt.rm(p,{recursive:!0,force:!0});for(let[P,v]of Object.entries(u).toSorted(([w],[I])=>w.localeCompare(I))){let w=Wt.join(t.sourceRoot,P);await dt.mkdir(Wt.dirname(w),{recursive:!0}),await dt.writeFile(w,v,"utf8")}let m={projectId:t.projectId,pipelines:l,datasets:d};await Nt(t.sourceRoot,m);let h=[...Object.keys(u),Nn].toSorted(),g=r.length===1?"pipeline":"pipelines",y=o.length===1?"dataset":"datasets";return{state:m,files:h,output:`Imported project ${t.projectId} with ${r.length} ${g} and ${o.length} ${y} into ${Wt.resolve(t.sourceRoot)}.`}}async function Rg(e,t){let r=await Ss(e,t);return{projectId:r.projectId,changes:r.changes,missingSecrets:r.missingSecrets,output:iO(r.changes,r.missingSecrets)}}async function Cg(e,t){let r=t.projectId;_(r,he);let i=await e.projects.get({projectId:r}),n=await Ss(e,{...t,listAllSecrets:!0}),s=n.changes.length,o=s===0?"Source has no pending changes.":`Source has ${s} pending change${s===1?"":"s"}.`;return{projectId:r,output:[`Project: ${r} (${i.name})`,`Team: ${i.teamId}`,`Pipelines: ${n.livePipelines.length}`,`Datasets: ${n.liveDatasets.length}`,`Secrets: ${n.liveSecrets.length}`,o].join(`
129
- `)}}async function jg(e,t){let r=await Ss(e,t);_(r.removedPipelines.length===0,`Refusing to delete pipelines absent from source: ${r.removedPipelines.join(", ")}.`),_(r.removedDatasets.length===0,`Refusing to delete datasets absent from source: ${r.removedDatasets.join(", ")}. Dataset items are never deleted.`),_(r.missingSecrets.length===0,`Required secrets are missing: ${r.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`);let i=r.datasets.flatMap((l)=>l.conflictingFields.map((d)=>`${l.name}.${d.name}`));_(i.length===0,`Dataset field schemas conflict with source: ${i.join(", ")}. Existing fields are never rewritten.`);let n=0,s=new Map;for(let l of r.datasets){let d=l.dataset;if(d===void 0)d=await e.datasets.create({projectId:r.projectId,name:l.name}),n+=1;if(s.set(l.name,d.id),l.missingFields.length>0)await e.datasets.createFields({datasetId:d.id,fields:l.missingFields.map((p)=>({name:p.name,jsonSchema:p.jsonSchema}))}),n+=l.missingFields.length}let o=new Map;for(let l of r.pipelines){let d=s.get(l.source.definition.dataset);_(d,`Dataset ${l.source.definition.dataset} has no resolved ID.`);let p=Li(l.source.definition,{datasetId:d});if(l.pipeline===void 0){let m=await e.pipelines.import({projectId:r.projectId,name:l.source.name,graph:p});await e.pipelines.attachDataset({pipelineId:m.id,datasetId:d}),o.set(l.source.sourceDirectory,m.id),n+=2;continue}if(o.set(l.source.sourceDirectory,l.pipeline.id),l.graphChanges.length===0)continue;let f=l.snapshot;_(f,`Pipeline ${l.pipeline.id} has no graph snapshot.`),await e.pipelines.replaceGraph({pipelineId:l.pipeline.id,graph:Xl(p,f.graph),expectedVersion:f.version}),n+=1}let a={projectId:r.projectId,pipelines:Object.fromEntries(r.source.pipelines.map((l)=>{let d=o.get(l.sourceDirectory);return _(d,`Pipeline ${l.sourceDirectory} has no resolved ID.`),[l.sourceDirectory,{pipelineId:d}]})),datasets:Object.fromEntries(r.datasets.map((l)=>{let d=s.get(l.name);return _(d,`Dataset ${l.name} has no resolved ID.`),[l.name,{datasetId:d}]}))};if(we(r.state)!==we(a))await Nt(t.sourceRoot,a);let c=n===0?"unchanged":"changed",u=n===0?"No changes.":`Applied ${n} ${n===1?"write":"writes"} to project ${r.projectId}.`;return{action:c,state:a,changes:r.changes,writes:n,output:u}}var cO=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),dO=(e)=>e.issues.map((t)=>{let r=cO(t);return` ${t.severity} ${t.code}${r.length===0?"":` ${r}`}: ${t.message}`});async function Fg(e,t){let r=await Ss(e,t),i=[];for(let o of r.pipelines){let a=r.datasets.find((l)=>l.name===o.source.definition.dataset)?.dataset;if(o.pipeline===void 0){i.push({sourceDirectory:o.source.sourceDirectory,skipped:"pipeline is not on the platform yet; run toloka apply first"});continue}if(a===void 0){i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,skipped:`dataset "${o.source.definition.dataset}" is not on the platform yet; run toloka apply first`});continue}let c=o.snapshot===void 0?Li(o.source.definition,{datasetId:a.id}):Xl(Li(o.source.definition,{datasetId:a.id}),o.snapshot.graph),u=await e.pipelines.validateGraph({pipelineId:o.pipeline.id,graph:c});i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,report:u})}let n=i.every((o)=>o.report?.valid!==!1),s=i.flatMap((o)=>{if(o.skipped!==void 0)return[`- ${o.sourceDirectory}: skipped (${o.skipped})`];return _(o.report,`Pipeline ${o.sourceDirectory} is missing a validation report`),[o.report.valid?`- ${o.sourceDirectory}: valid`:`- ${o.sourceDirectory}: invalid`,...dO(o.report)]});return{projectId:r.projectId,results:i,valid:n,output:s.length===0?"No pipelines to validate.":s.join(`
130
- `)}}var Tg="uploaded",uO=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pO=(e)=>uO.test(e)?e.toLowerCase():void 0,ec=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Zl=(e)=>{if(!ec(e))return"unknown";if(Array.isArray(e.anyOf)){let i=[...new Set(e.anyOf.map(Zl))];return i.length===0?"unknown":i.join(" | ")}let t=e.type,r=typeof t==="string"?[t]:Array.isArray(t)?t.filter((i)=>typeof i==="string"):[];if(r.length===0)return"unknown";return r.map((i)=>{if(i!=="array")return i;let n=Zl(e.items);return n==="unknown"?"array":`array<${n}>`}).join(" | ")},fO=(e)=>{if(e.length===0)return"No inferred fields are available yet.";return["Inferred fields:",...e.toSorted((t,r)=>t.jsonPath.localeCompare(r.jsonPath)).map((t)=>`${" ".repeat(t.depth)}- ${t.jsonPath}: ${Zl(t.jsonSchema)}`)].join(`
131
- `)},Ag=async(e)=>{let t=e.source??await $s(e.sourceRoot),r=Is(t).find((i)=>i.name===e.datasetName);return r===void 0?[]:r.fields.map((i)=>({name:i.name,jsonSchema:i.jsonSchema}))},Og=(e)=>`${e.name} (${e.id})`,kg=async(e,t)=>{let r=[];for await(let i of e.datasets.listAll({projectId:t}))r.push(i);return r.toSorted((i,n)=>{let s=i.name.localeCompare(n.name);return s===0?i.id.localeCompare(n.id):s})},tc=async(e,t,r)=>{let i=await $e(t.sourceRoot),n=t.projectId??i?.projectId;_(n,he);let s=t.datasetName,o=await kg(e,n),a=(f)=>o.filter((m)=>m.name===f).length<=1,c=pO(s),u=o.find((f)=>f.id===s||f.id.toLowerCase()===c);if(u!==void 0)return{datasetId:u.id,name:u.name,nameIsUnique:a(u.name)};let l=o.filter((f)=>f.name===s);if(_(l.length<=1,`Project ${n} has multiple datasets named "${s}": ${l.map(Og).join(", ")}.`),l.length===1){let[f]=l;return _(f,`Dataset "${s}" has no resolved ID.`),{datasetId:f.id,name:f.name,nameIsUnique:!0}}let d=i?.projectId===n?i.datasets[s]:void 0;if(d!==void 0){let f=o.find((m)=>m.id===d.datasetId);if(f!==void 0)return{datasetId:f.id,name:f.name,nameIsUnique:a(f.name)}}_(r&&c===void 0,o.length===0?`Dataset "${s}" does not exist in project ${n}. Run toloka apply first.`:`Dataset "${s}" does not exist in project ${n}. This project has: ${o.map(Og).join(", ")}.`),_((await Ag(t)).length>0,`Dataset "${s}" does not exist in project ${n} and no pipeline in source declares it. Bind a pipeline to it in source so its columns are known, or upload to an existing dataset.`);let p=await e.datasets.create({projectId:n,name:s});return{datasetId:p.id,name:p.name,nameIsUnique:!0}},mO=async(e)=>(await Tr.readFile(e,"utf8")).split(/\r?\n/u).map((r,i)=>({line:r,lineNumber:i+1})).filter(({line:r})=>r.trim().length>0).map(({line:r,lineNumber:i})=>{let n;try{n=JSON.parse(r)}catch{_(!1,`${Or.basename(e)}:${i} is not valid JSON`)}return _(ec(n),`${Or.basename(e)}:${i} must contain a JSON object`),n});async function Dg(e,t){let r=await mO(t.filePath),i=await tc(e,t,!0),n=i.datasetId,s=new Map;for await(let P of e.datasets.listAllFields({datasetId:n})){if(P.internal||P.name===Tg)continue;s.set(P.name,{name:P.name,jsonSchema:P.jsonSchema})}for(let P of await Ag({...t,datasetName:i.name}))if(!s.has(P.name))s.set(P.name,P);let o=[...s.values()],a=JSON.stringify(r),c=new TextEncoder().encode(a),u=await e.datasets.startUpload({datasetId:n,filename:Or.basename(t.filePath),format:"json",declaredSizeBytes:c.byteLength,fields:o}),l=await(t.fetch??globalThis.fetch)(u.uploadUrl,{method:"PUT",headers:{"Content-Type":"application/json","x-ms-blob-type":"BlockBlob"},body:c});_(l.ok,`Dataset upload failed with HTTP ${l.status}.`),await e.datasets.finalizeUpload({uploadId:u.job.id});let d=await e.waitFor({type:"datasetUpload",uploadId:u.job.id},t.waitFor),p=i.nameIsUnique?i.name:i.datasetId,f=d.status==="failed"&&d.error?.startsWith("Schema incompatible with existing upload")===!0?`
132
- Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";_(d.status==="succeeded",`${d.error??`Dataset upload ${d.id} failed.`}${f}`);let m=`Uploaded ${d.result.itemsIngested} rows to dataset ${i.name}.`,h=[],g,y;try{h=(await e.datasets.getInferredFields({datasetId:n})).fields,g=fO(h)}catch(P){y=`Upload succeeded, but inferred fields could not be fetched: ${P instanceof Error?P.message:String(P)}`}return{datasetId:n,rowsUploaded:d.result.itemsIngested,inferredFields:h,output:g===void 0?m:`${m}
133
- ${g}`,...y===void 0?{}:{warning:y}}}async function Ng(e,t){let r=await tc(e,t,!1),i=await e.datasets.getInferredFields({datasetId:r.datasetId}),n=i.fields.filter((o)=>o.depth===1),s=Vh(n.map(({name:o,jsonSchema:a})=>({name:o,jsonSchema:a})));return{datasetId:r.datasetId,inferredFields:i.fields,declarations:s,output:n.length===0?`Dataset ${r.name} has no inferred fields yet.`:s}}async function Lg(e,t){let r=await kg(e,t.projectId);if(r.length===0)return{output:"This project has no datasets."};return{output:r.map((i)=>`${i.name} ${i.id}`).join(`
134
- `)}}var hO=async(e)=>{let t=await e.fetch(e.downloadUrl);_(t.ok,`Dataset export download failed with HTTP ${t.status}.`);let r=await t.text(),i;try{i=JSON.parse(r)}catch(s){throw Error(`Dataset export ${e.exportId} is not valid JSON.`,{cause:s})}_(Array.isArray(i),`Dataset export ${e.exportId} is not a JSON array.`);let n=[];for(let[s,o]of i.entries())_(ec(o),`Dataset export ${e.exportId} row ${s} is not a JSON object.`),n.push(o);return n};async function qg(e,t){let r=await tc(e,t,!1),i=[];for await(let c of e.datasets.listAllFields({datasetId:r.datasetId})){if(c.internal||c.name===Tg)continue;i.push(c.name)}_(i.length>0,`Dataset ${r.name} has no fields to export.`);let n=await e.datasets.startExport({datasetId:r.datasetId,fields:i}),s;try{s=await e.waitFor({type:"datasetExport",exportId:n.id},t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs})}catch(c){throw _(!(c instanceof re&&c.code==="wait_timeout"),`Stopped waiting for dataset export ${n.id}; raise --timeout to wait longer.`),c}_(s.result.downloadUrl,`Dataset export ${s.id} succeeded without a download URL.`);let o=await hO({downloadUrl:s.result.downloadUrl,exportId:s.id,fetch:t.fetch??globalThis.fetch}),a=t.limit===void 0?o:o.slice(0,t.limit);return await Tr.mkdir(Or.dirname(t.outPath),{recursive:!0}),await Tr.writeFile(t.outPath,a.length===0?"":`${a.map((c)=>JSON.stringify(c)).join(`
126
+ `}function zh(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((u)=>({key:`field:${u.id}`,name:u.name,fallback:"field"})),...e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type}))],i=Dl(r,({name:u,fallback:l})=>Gh(u,l),Uh),n=Dl(e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type})),({name:u,fallback:l})=>rF(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return _(l,`Field "${u.id}" has no allocated binding`),[u.id,l]})),o=new Map(e.nodes.map((u)=>{let l=i.get(`node:${u.id}`);return _(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),d=n.get(`node:${u.id}`);return _(l&&d,`Node "${u.id}" has no allocated source name`),sF(u,l,`nodes/${d}/node.ts`,s)}),c=[{path:"fields.ts",source:oF(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:aF(e,t.dataset,a,s,o)}].toSorted((u,l)=>xt(u.path,l.path));return Object.fromEntries(c.map(({path:u,source:l})=>[u,l]))}var ut=require("fs/promises"),Wt=require("path");var fg=xe(Ja(),1),mg=xe(dg(),1);var ug={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"}},required:["audienceType"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var hg=new fg.default({strict:!1});mg.default(hg);var pg=hg.compile(ug),MF=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function Wl(e){if(pg(e))return;let t=pg.errors;_(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=MF(n),o=`${s.path}
127
+ ${s.reason}`;if(r.has(o))continue;r.add(o),i.push(s)}throw er.fromIssues(i)}var UF=Symbol("fieldDefinition"),BF=Symbol.for("@toloka-platform/sdk/pipeline-definition"),yg=Symbol("portDefinition"),GF=Symbol("nodeFieldReferences");function _g(e,t){return{node:e,handle:t,direction:"input",[yg]:"input"}}function Pg(e,t){return{node:e,handle:t,direction:"output",[yg]:"output"}}function bg(e){return typeof e==="object"&&e!==null&&UF in e}function Hl(e,t){if(bg(e)){t.push(e);return}if(Array.isArray(e)){for(let r of e)Hl(r,t);return}if(typeof e==="object"&&e!==null)for(let r of Object.values(e))Hl(r,t)}function VF(e){let t=[];return Hl(e,t),t}function gg(e){return bg(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function KF(e,t={}){let r=t.id??"root",{started:i,completed:n,...s}=e;return{id:r,type:"root",settings:{...s,startedFieldProxies:{output:i.map(gg)},completedFieldProxies:{input:n.map(gg)}},started:Pg(r,"started"),completed:_g(r,"completed"),[GF]:VF(e)}}var Zq=Object.assign(KF,{started:Pg("root","started"),completed:_g("root","completed")});function zF(e){return typeof e==="object"&&e!==null&&BF in e}function ws(e){_(zF(e),"Invalid pipeline definition: expected a value returned by definePipeline"),_(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;_(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),_(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}Wl(e.graph)}function Li(e,t){let r={version:e.graph.version,fields:e.graph.fields.map((i)=>({...i})),nodes:e.graph.nodes.map((i)=>i.type==="root"?{...i,settings:{...i.settings,datasetId:t.datasetId}}:i),connections:e.graph.connections.map((i)=>({from:{...i.from},to:{...i.to},settings:{...i.settings}}))};return Wl(r),r}function vg(e){let t=new Set;for(let r of e.nodes){if(r.type!=="code")continue;for(let i of r.settings.envVars??[])if(i.type==="secret")t.add(i.secretName)}return[...t].toSorted((r,i)=>r.localeCompare(i))}var qi=require("fs/promises"),ge=require("path"),wg=require("url");var $g=async(e)=>{let t;try{t=await qi.readdir(e,{withFileTypes:!0})}catch(i){if(i instanceof Error&&Reflect.get(i,"code")==="ENOENT")return[];throw i}let r=[];for(let i of t.toSorted((n,s)=>n.name.localeCompare(s.name))){let n=ge.join(e,i.name);if(i.isDirectory())r.push(...await $g(n));else if(i.isFile()&&i.name==="pipeline.ts")r.push(n)}return r},WF="toloka.json",HF=async(e)=>{try{return(await qi.stat(ge.join(e,WF))).isFile()}catch{return!1}};async function Eg(e){let t=ge.resolve(e);for(;;){if(await HF(t))return t;let r=ge.dirname(t);if(r===t)return;t=r}}async function $s(e){let t=await $g(ge.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(i)=>{let n=await qi.stat(i),s=wg.pathToFileURL(i);s.searchParams.set("version",`${n.mtimeMs}-${n.size}`);let o=await import(s.href);_(typeof o==="object"&&o!==null,`Invalid ${i}: expected a module`);let a=Reflect.get(o,"default");ws(a);let c=ge.relative(e,ge.dirname(i)).split(ge.sep).join("/");return{sourceDirectory:c,name:ge.basename(c),definition:a}}))).toSorted((i,n)=>i.sourceDirectory.localeCompare(n.sourceDirectory))}}var JF=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,Ql=(e)=>{if(Array.isArray(e))return e.map(Ql);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ql(r)]))},we=(e)=>JSON.stringify(Ql(e)),Ig=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),xg=(e,t)=>{if(!Ig(e)||!Ig(t))return t;return Object.fromEntries(Object.keys(e).map((r)=>[r,xg(e[r],t[r])]))},QF=(e,t)=>we(e)===we(xg(e,t)),Mi=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},Yl=(e)=>{let t=Reflect.get(e.settings,"about");if(typeof t==="object"&&t!==null){let r=Reflect.get(t,"name");if(typeof r==="string"&&r.length>0)return`${r} (${e.id})`}return e.id},YF=(e)=>`${e.name} (${e.id})`,XF=(e,t)=>{let r=t.get(e.from.node),i=t.get(e.to.node),n=r===void 0?e.from.node:Yl(r),s=i===void 0?e.to.node:Yl(i);return`${n}.${e.from.handle} -> ${s}.${e.to.handle}`},Es=(e)=>new Map(e.map((t)=>[t.id,t])),Jl=(e,t,r,i)=>{let n=[];for(let[s,o]of[...e].toSorted(([a],[c])=>a.localeCompare(c))){let a=t.get(s);if(a===void 0)n.push(i(o,"added"));else if(!r(o,a))n.push(i(o,"changed"))}for(let[s,o]of[...t].toSorted(([a],[c])=>a.localeCompare(c)))if(!e.has(s))n.push(i(o,"removed"));return n};function ZF(e,t){let r=Es(e.nodes),i=Es(t.nodes),n=new Map(e.connections.map((o)=>[we(o),o])),s=new Map(t.connections.map((o)=>[we(o),o]));return[...Jl(Es(e.fields),Es(t.fields),(o,a)=>we(o)===we(a),(o,a)=>({kind:"field",action:a,label:YF(o),id:o.id})),...Jl(r,i,QF,(o,a)=>({kind:"node",action:a,label:Yl(o),id:o.id})),...Jl(n,s,()=>!0,(o,a)=>({kind:"connection",action:a,label:XF(o,a==="removed"?i:r)})),...we(e.layout)===we(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var Xl=(e,t)=>{let r=t.nodes.find((n)=>n.type==="root"),i=r===void 0?{}:{...r.settings.itemFilter===void 0?{}:{itemFilter:r.settings.itemFilter},...r.settings.itemLimit===void 0?{}:{itemLimit:r.settings.itemLimit}};return{...e,...t.layout===void 0?{}:{layout:t.layout},nodes:e.nodes.map((n)=>n.type==="root"?{...n,settings:{...i,...n.settings}}:n)}},Is=(e)=>{let t=new Map;for(let r of e.pipelines){let i=t.get(r.definition.dataset);if(i===void 0)i=new Map,t.set(r.definition.dataset,i);for(let n of r.definition.graph.fields){let s=i.get(n.name);if(_(s===void 0||we(s.jsonSchema)===we(n.jsonSchema),`Dataset "${r.definition.dataset}" has conflicting schemas for field "${n.name}".`),s===void 0)i.set(n.name,n)}}return[...t].toSorted(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({name:r,fields:[...i.values()].toSorted((n,s)=>n.name.localeCompare(s.name))}))},eO=(e)=>{let t=new Set;for(let r of e.pipelines)_(JF.test(r.sourceDirectory),`Invalid pipeline source directory ${r.sourceDirectory}`),_(!t.has(r.sourceDirectory),`Pipeline source directory ${r.sourceDirectory} is declared more than once`),t.add(r.sourceDirectory),ws(r.definition);Is(e)},tO=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.datasetId);if(i!==void 0)return _(i.name===e,`Dataset ${i.id} is bound as "${e}" but is named "${i.name}".`),i;let n=r.filter((s)=>s.name===e);return _(n.length<=1,`Project has multiple datasets named "${e}".`),n[0]},rO=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.pipelineId);if(i!==void 0)return i;let n=r.filter((s)=>s.name===e.name);return _(n.length<=1,`Project has multiple pipelines named "${e.name}".`),n[0]},iO=(e)=>{let t=e.action==="added"?"+":e.action==="removed"?"-":e.action==="missing"?"!":"~";switch(e.kind){case"pipeline":return`${t} Pipeline ${e.action}: ${e.label}`;case"dataset":return`${t} Dataset ${e.action}: ${e.label}`;case"datasetField":return`${t} Dataset field ${e.action}: ${e.dataset}.${e.label}`;case"secret":return`${t} Missing secret: ${e.label}`;case"node":return`${t} Node ${e.action} in ${e.pipeline}: ${e.label}`;case"connection":return`${t} Connection ${e.action} in ${e.pipeline}: ${e.label}`;case"field":return`${t} Graph field ${e.action} in ${e.pipeline}: ${e.label}`;case"layout":return`${t} Layout ${e.action} in ${e.pipeline}: ${e.label}`}},nO=(e,t)=>{if(e.length===0)return"No changes.";let r=e.length===1?"change":"changes",i=[`Plan: ${e.length} ${r}`,...e.map(iO)];if(t.length>0){i.push("","Required secrets are missing:");for(let n of t)i.push(` ${n}`);i.push("Run `toloka secret set <name>` before apply.")}return i.join(`
128
+ `)},sO=async(e,t,r,i)=>{let n=t.map((o)=>({desired:o,dataset:tO(o.name,r?.datasets[o.name],i)})),s=await Promise.all(n.map(async({dataset:o})=>o===void 0?[]:Mi(e.datasets.listAllFields({datasetId:o.id}))));return n.map(({desired:o,dataset:a},c)=>{let u=s[c]??[],l=new Map(u.map((d)=>[d.name,d]));return{...o,...a===void 0?{}:{dataset:a},liveFields:u,missingFields:o.fields.filter((d)=>!l.has(d.name)),conflictingFields:o.fields.filter((d)=>{let p=l.get(d.name);return p!==void 0&&we(p.jsonSchema)!==we(d.jsonSchema)})}})},oO=async(e,t,r,i,n)=>{let s=t.pipelines.map((a)=>({source:a,pipeline:rO(a,r?.pipelines[a.sourceDirectory],n)})),o=await Promise.all(s.map(async({pipeline:a})=>a===void 0?void 0:e.pipelines.getGraph({pipelineId:a.id})));return s.map(({source:a,pipeline:c},u)=>{let l=o[u],d=i.find((f)=>f.name===a.definition.dataset)?.dataset,p=[];if(c!==void 0&&l!==void 0)p=d===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:ZF(Xl(Li(a.definition,{datasetId:d.id}),l.graph),l.graph);return{source:a,...c===void 0?{}:{pipeline:c},...l===void 0?{}:{snapshot:l},graphChanges:p}})},aO=(e,t,r,i,n)=>{let s=[];for(let o of n)s.push({kind:"pipeline",action:"removed",label:o});for(let o of i)s.push({kind:"dataset",action:"removed",label:o});for(let o of e){if(o.dataset===void 0)s.push({kind:"dataset",action:"added",label:o.name});for(let a of o.missingFields)s.push({kind:"datasetField",action:"added",label:a.name,dataset:o.name});for(let a of o.conflictingFields)s.push({kind:"datasetField",action:"changed",label:a.name,dataset:o.name})}for(let o of t)if(o.pipeline===void 0)s.push({kind:"pipeline",action:"added",label:o.source.sourceDirectory});else for(let a of o.graphChanges)s.push({...a,pipeline:o.source.sourceDirectory});for(let o of r)s.push({kind:"secret",action:"missing",label:o});return s},Ss=async(e,t)=>{let r=t.source??await $s(t.sourceRoot);eO(r);let i=await $e(t.sourceRoot),n=t.projectId??i?.projectId;_(n,he);let s=i?.projectId===n?i:void 0,o=new Set(r.pipelines.flatMap(({definition:P})=>vg(P.graph))),a=t.listAllSecrets===!0||o.size>0,[c,u,l]=await Promise.all([Mi(e.pipelines.listAll({projectId:n})),Mi(e.datasets.listAll({projectId:n})),a?e.secrets.list({projectId:n}):Promise.resolve([])]),d=Is(r),p=Object.keys(s?.datasets??{}).filter((P)=>!d.some((v)=>v.name===P)).toSorted(),f=Object.keys(s?.pipelines??{}).filter((P)=>!r.pipelines.some((v)=>v.sourceDirectory===P)).toSorted(),m=await sO(e,d,s,u),h=await oO(e,r,s,m,c),g=new Set(l.map((P)=>P.name)),y=[...o].filter((P)=>!g.has(P)).toSorted();return{projectId:n,source:r,state:i,datasets:m,pipelines:h,livePipelines:c,liveDatasets:u,liveSecrets:l,changes:aO(m,h,y,p,f),missingSecrets:y,removedDatasets:p,removedPipelines:f}},Sg=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",lO=(e)=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},cO=(e)=>{let t=Map.groupBy(e,(r)=>Sg(r.name));return new Map(e.map((r)=>{let i=Sg(r.name),n=(t.get(i)?.length??0)>1;return[r.id,`pipelines/${n?`${i}-${lO(r.id)}`:i}`]}))};async function Rg(e,t){let r=(await Mi(e.pipelines.listAll({projectId:t.projectId}))).toSorted((P,v)=>P.name.localeCompare(v.name)||P.id.localeCompare(v.id)),i=await Promise.all(r.map((P)=>e.pipelines.getGraph({pipelineId:P.id}))),n=new Set;for(let P of i){let v=P.graph.nodes.find((w)=>w.type==="root");_(v?.settings.datasetId,"Every imported pipeline must have a bound dataset."),n.add(v.settings.datasetId)}let s=await Mi(e.datasets.listAll({projectId:t.projectId})),o=[];for(let P of[...n].toSorted()){let v=s.find((w)=>w.id===P);_(v,`Project ${t.projectId} has no dataset ${P}.`),o.push(v)}let a=new Map(o.map((P)=>[P.id,P])),c=cO(r),u={},l={},d={};for(let[P,v]of r.entries()){let w=i[P];_(w,`Pipeline ${v.id} has no graph snapshot.`);let I=w.graph.nodes.find((R)=>R.type==="root");_(I?.settings.datasetId,`Pipeline ${v.id} has no dataset binding.`);let E=a.get(I.settings.datasetId);_(E,`Pipeline ${v.id} references unknown dataset ${I.settings.datasetId}.`);let x=d[E.name];_(x===void 0||x.datasetId===E.id,`Project has multiple referenced datasets named "${E.name}".`),d[E.name]={datasetId:E.id};let T=c.get(v.id);_(T,`Pipeline ${v.id} has no source directory.`),l[T]={pipelineId:v.id};for(let[R,V]of Object.entries(zh(w.graph,{dataset:E.name})))u[`${T}/${R}`]=V}await ut.mkdir(t.sourceRoot,{recursive:!0});let p=Wt.join(t.sourceRoot,"pipelines"),f=!1;try{f=(await ut.stat(p)).isDirectory()}catch(P){if(!(P instanceof Error)||!("code"in P)||P.code!=="ENOENT")throw P}if(_(!f||t.force===!0,`Folder already exists: ${p}. Pass --force to replace it.`),f)await ut.rm(p,{recursive:!0,force:!0});for(let[P,v]of Object.entries(u).toSorted(([w],[I])=>w.localeCompare(I))){let w=Wt.join(t.sourceRoot,P);await ut.mkdir(Wt.dirname(w),{recursive:!0}),await ut.writeFile(w,v,"utf8")}let m={projectId:t.projectId,pipelines:l,datasets:d};await Nt(t.sourceRoot,m);let h=[...Object.keys(u),Nn].toSorted(),g=r.length===1?"pipeline":"pipelines",y=o.length===1?"dataset":"datasets";return{state:m,files:h,output:`Imported project ${t.projectId} with ${r.length} ${g} and ${o.length} ${y} into ${Wt.resolve(t.sourceRoot)}.`}}async function Cg(e,t){let r=await Ss(e,t);return{projectId:r.projectId,changes:r.changes,missingSecrets:r.missingSecrets,output:nO(r.changes,r.missingSecrets)}}async function jg(e,t){let r=t.projectId;_(r,he);let i=await e.projects.get({projectId:r}),n=await Ss(e,{...t,listAllSecrets:!0}),s=n.changes.length,o=s===0?"Source has no pending changes.":`Source has ${s} pending change${s===1?"":"s"}.`;return{projectId:r,output:[`Project: ${r} (${i.name})`,`Team: ${i.teamId}`,`Pipelines: ${n.livePipelines.length}`,`Datasets: ${n.liveDatasets.length}`,`Secrets: ${n.liveSecrets.length}`,o].join(`
129
+ `)}}async function Fg(e,t){let r=await Ss(e,t);_(r.removedPipelines.length===0,`Refusing to delete pipelines absent from source: ${r.removedPipelines.join(", ")}.`),_(r.removedDatasets.length===0,`Refusing to delete datasets absent from source: ${r.removedDatasets.join(", ")}. Dataset items are never deleted.`),_(r.missingSecrets.length===0,`Required secrets are missing: ${r.missingSecrets.join(", ")}. Run toloka secret set <name> before apply.`);let i=r.datasets.flatMap((l)=>l.conflictingFields.map((d)=>`${l.name}.${d.name}`));_(i.length===0,`Dataset field schemas conflict with source: ${i.join(", ")}. Existing fields are never rewritten.`);let n=0,s=new Map;for(let l of r.datasets){let d=l.dataset;if(d===void 0)d=await e.datasets.create({projectId:r.projectId,name:l.name}),n+=1;if(s.set(l.name,d.id),l.missingFields.length>0)await e.datasets.createFields({datasetId:d.id,fields:l.missingFields.map((p)=>({name:p.name,jsonSchema:p.jsonSchema}))}),n+=l.missingFields.length}let o=new Map;for(let l of r.pipelines){let d=s.get(l.source.definition.dataset);_(d,`Dataset ${l.source.definition.dataset} has no resolved ID.`);let p=Li(l.source.definition,{datasetId:d});if(l.pipeline===void 0){let m=await e.pipelines.import({projectId:r.projectId,name:l.source.name,graph:p});await e.pipelines.attachDataset({pipelineId:m.id,datasetId:d}),o.set(l.source.sourceDirectory,m.id),n+=2;continue}if(o.set(l.source.sourceDirectory,l.pipeline.id),l.graphChanges.length===0)continue;let f=l.snapshot;_(f,`Pipeline ${l.pipeline.id} has no graph snapshot.`),await e.pipelines.replaceGraph({pipelineId:l.pipeline.id,graph:Xl(p,f.graph),expectedVersion:f.version}),n+=1}let a={projectId:r.projectId,pipelines:Object.fromEntries(r.source.pipelines.map((l)=>{let d=o.get(l.sourceDirectory);return _(d,`Pipeline ${l.sourceDirectory} has no resolved ID.`),[l.sourceDirectory,{pipelineId:d}]})),datasets:Object.fromEntries(r.datasets.map((l)=>{let d=s.get(l.name);return _(d,`Dataset ${l.name} has no resolved ID.`),[l.name,{datasetId:d}]}))};if(we(r.state)!==we(a))await Nt(t.sourceRoot,a);let c=n===0?"unchanged":"changed",u=n===0?"No changes.":`Applied ${n} ${n===1?"write":"writes"} to project ${r.projectId}.`;return{action:c,state:a,changes:r.changes,writes:n,output:u}}var dO=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),uO=(e)=>e.issues.map((t)=>{let r=dO(t);return` ${t.severity} ${t.code}${r.length===0?"":` ${r}`}: ${t.message}`});async function Og(e,t){let r=await Ss(e,t),i=[];for(let o of r.pipelines){let a=r.datasets.find((l)=>l.name===o.source.definition.dataset)?.dataset;if(o.pipeline===void 0){i.push({sourceDirectory:o.source.sourceDirectory,skipped:"pipeline is not on the platform yet; run toloka apply first"});continue}if(a===void 0){i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,skipped:`dataset "${o.source.definition.dataset}" is not on the platform yet; run toloka apply first`});continue}let c=o.snapshot===void 0?Li(o.source.definition,{datasetId:a.id}):Xl(Li(o.source.definition,{datasetId:a.id}),o.snapshot.graph),u=await e.pipelines.validateGraph({pipelineId:o.pipeline.id,graph:c});i.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,report:u})}let n=i.every((o)=>o.report?.valid!==!1),s=i.flatMap((o)=>{if(o.skipped!==void 0)return[`- ${o.sourceDirectory}: skipped (${o.skipped})`];return _(o.report,`Pipeline ${o.sourceDirectory} is missing a validation report`),[o.report.valid?`- ${o.sourceDirectory}: valid`:`- ${o.sourceDirectory}: invalid`,...uO(o.report)]});return{projectId:r.projectId,results:i,valid:n,output:s.length===0?"No pipelines to validate.":s.join(`
130
+ `)}}var Ag="uploaded",pO=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,fO=(e)=>pO.test(e)?e.toLowerCase():void 0,ec=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Zl=(e)=>{if(!ec(e))return"unknown";if(Array.isArray(e.anyOf)){let i=[...new Set(e.anyOf.map(Zl))];return i.length===0?"unknown":i.join(" | ")}let t=e.type,r=typeof t==="string"?[t]:Array.isArray(t)?t.filter((i)=>typeof i==="string"):[];if(r.length===0)return"unknown";return r.map((i)=>{if(i!=="array")return i;let n=Zl(e.items);return n==="unknown"?"array":`array<${n}>`}).join(" | ")},mO=(e)=>{if(e.length===0)return"No inferred fields are available yet.";return["Inferred fields:",...e.toSorted((t,r)=>t.jsonPath.localeCompare(r.jsonPath)).map((t)=>`${" ".repeat(t.depth)}- ${t.jsonPath}: ${Zl(t.jsonSchema)}`)].join(`
131
+ `)},kg=async(e)=>{let t=e.source??await $s(e.sourceRoot),r=Is(t).find((i)=>i.name===e.datasetName);return r===void 0?[]:r.fields.map((i)=>({name:i.name,jsonSchema:i.jsonSchema}))},Tg=(e)=>`${e.name} (${e.id})`,Dg=async(e,t)=>{let r=[];for await(let i of e.datasets.listAll({projectId:t}))r.push(i);return r.toSorted((i,n)=>{let s=i.name.localeCompare(n.name);return s===0?i.id.localeCompare(n.id):s})},tc=async(e,t,r)=>{let i=await $e(t.sourceRoot),n=t.projectId??i?.projectId;_(n,he);let s=t.datasetName,o=await Dg(e,n),a=(f)=>o.filter((m)=>m.name===f).length<=1,c=fO(s),u=o.find((f)=>f.id===s||f.id.toLowerCase()===c);if(u!==void 0)return{datasetId:u.id,name:u.name,nameIsUnique:a(u.name)};let l=o.filter((f)=>f.name===s);if(_(l.length<=1,`Project ${n} has multiple datasets named "${s}": ${l.map(Tg).join(", ")}.`),l.length===1){let[f]=l;return _(f,`Dataset "${s}" has no resolved ID.`),{datasetId:f.id,name:f.name,nameIsUnique:!0}}let d=i?.projectId===n?i.datasets[s]:void 0;if(d!==void 0){let f=o.find((m)=>m.id===d.datasetId);if(f!==void 0)return{datasetId:f.id,name:f.name,nameIsUnique:a(f.name)}}_(r&&c===void 0,o.length===0?`Dataset "${s}" does not exist in project ${n}. Run toloka apply first.`:`Dataset "${s}" does not exist in project ${n}. This project has: ${o.map(Tg).join(", ")}.`),_((await kg(t)).length>0,`Dataset "${s}" does not exist in project ${n} and no pipeline in source declares it. Bind a pipeline to it in source so its columns are known, or upload to an existing dataset.`);let p=await e.datasets.create({projectId:n,name:s});return{datasetId:p.id,name:p.name,nameIsUnique:!0}},hO=async(e)=>(await Tr.readFile(e,"utf8")).split(/\r?\n/u).map((r,i)=>({line:r,lineNumber:i+1})).filter(({line:r})=>r.trim().length>0).map(({line:r,lineNumber:i})=>{let n;try{n=JSON.parse(r)}catch{_(!1,`${Or.basename(e)}:${i} is not valid JSON`)}return _(ec(n),`${Or.basename(e)}:${i} must contain a JSON object`),n});async function Ng(e,t){let r=await hO(t.filePath),i=await tc(e,t,!0),n=i.datasetId,s=new Map;for await(let P of e.datasets.listAllFields({datasetId:n})){if(P.internal||P.name===Ag)continue;s.set(P.name,{name:P.name,jsonSchema:P.jsonSchema})}for(let P of await kg({...t,datasetName:i.name}))if(!s.has(P.name))s.set(P.name,P);let o=[...s.values()],a=JSON.stringify(r),c=new TextEncoder().encode(a),u=await e.datasets.startUpload({datasetId:n,filename:Or.basename(t.filePath),format:"json",declaredSizeBytes:c.byteLength,fields:o}),l=await(t.fetch??globalThis.fetch)(u.uploadUrl,{method:"PUT",headers:{"Content-Type":"application/json","x-ms-blob-type":"BlockBlob"},body:c});_(l.ok,`Dataset upload failed with HTTP ${l.status}.`),await e.datasets.finalizeUpload({uploadId:u.job.id});let d=await e.waitFor({type:"datasetUpload",uploadId:u.job.id},t.waitFor),p=i.nameIsUnique?i.name:i.datasetId,f=d.status==="failed"&&d.error?.startsWith("Schema incompatible with existing upload")===!0?`
132
+ Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";_(d.status==="succeeded",`${d.error??`Dataset upload ${d.id} failed.`}${f}`);let m=`Uploaded ${d.result.itemsIngested} rows to dataset ${i.name}.`,h=[],g,y;try{h=(await e.datasets.getInferredFields({datasetId:n})).fields,g=mO(h)}catch(P){y=`Upload succeeded, but inferred fields could not be fetched: ${P instanceof Error?P.message:String(P)}`}return{datasetId:n,rowsUploaded:d.result.itemsIngested,inferredFields:h,output:g===void 0?m:`${m}
133
+ ${g}`,...y===void 0?{}:{warning:y}}}async function Lg(e,t){let r=await tc(e,t,!1),i=await e.datasets.getInferredFields({datasetId:r.datasetId}),n=i.fields.filter((o)=>o.depth===1),s=Kh(n.map(({name:o,jsonSchema:a})=>({name:o,jsonSchema:a})));return{datasetId:r.datasetId,inferredFields:i.fields,declarations:s,output:n.length===0?`Dataset ${r.name} has no inferred fields yet.`:s}}async function qg(e,t){let r=await Dg(e,t.projectId);if(r.length===0)return{output:"This project has no datasets."};return{output:r.map((i)=>`${i.name} ${i.id}`).join(`
134
+ `)}}var gO=async(e)=>{let t=await e.fetch(e.downloadUrl);_(t.ok,`Dataset export download failed with HTTP ${t.status}.`);let r=await t.text(),i;try{i=JSON.parse(r)}catch(s){throw Error(`Dataset export ${e.exportId} is not valid JSON.`,{cause:s})}_(Array.isArray(i),`Dataset export ${e.exportId} is not a JSON array.`);let n=[];for(let[s,o]of i.entries())_(ec(o),`Dataset export ${e.exportId} row ${s} is not a JSON object.`),n.push(o);return n};async function Mg(e,t){let r=await tc(e,t,!1),i=[];for await(let c of e.datasets.listAllFields({datasetId:r.datasetId})){if(c.internal||c.name===Ag)continue;i.push(c.name)}_(i.length>0,`Dataset ${r.name} has no fields to export.`);let n=await e.datasets.startExport({datasetId:r.datasetId,fields:i}),s;try{s=await e.waitFor({type:"datasetExport",exportId:n.id},t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs})}catch(c){throw _(!(c instanceof re&&c.code==="wait_timeout"),`Stopped waiting for dataset export ${n.id}; raise --timeout to wait longer.`),c}_(s.result.downloadUrl,`Dataset export ${s.id} succeeded without a download URL.`);let o=await gO({downloadUrl:s.result.downloadUrl,exportId:s.id,fetch:t.fetch??globalThis.fetch}),a=t.limit===void 0?o:o.slice(0,t.limit);return await Tr.mkdir(Or.dirname(t.outPath),{recursive:!0}),await Tr.writeFile(t.outPath,a.length===0?"":`${a.map((c)=>JSON.stringify(c)).join(`
135
135
  `)}
136
- `),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function Mg(e,t){return await e.secrets.set({projectId:t.projectId,name:t.name,value:t.value}),{name:t.name,output:`Set secret ${t.name}.`}}var gO=["emacs","vim"],yO=new Set(gO);function _O(e){return yO.has(e)}function Ug(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(_O)))}var Ui=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",xs=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var rc=(e)=>e.name==="backspace";var ic=(e)=>"1234567890".includes(e.name),nc=(e)=>e.name==="enter"||e.name==="return";class sc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class oc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Rs extends Error{name="ExitPromptError"}class ac extends Error{name="HookError"}class Bi extends Error{name="ValidationError"}var Kg=require("async_hooks");var Cs=require("async_hooks");var Bg=new Cs.AsyncLocalStorage;function PO(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Gg(e,t){let r=PO(e);return Bg.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Ht(){let e=Bg.getStore();if(!e)throw new ac("[Inquirer] Hook functions can only be called from within a prompt");return e}function lc(){return Ht().rl}function cc(e){let t=(...r)=>{let i=Ht(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Cs.AsyncResource.bind(t)}function Ar(e){let t=Ht(),{index:r}=t,i={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},n=e(i);return t.index++,n}function Vg(){Ht().handleChange()}var Jt={queue(e){let t=Ht(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(lc());if(i!=null&&typeof i!=="function")throw new Bi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Ht();cc(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Ht();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function bO(e){return typeof e==="function"}function tt(e){return Ar((t)=>{let r=Kg.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),Vg()});if(t.initialized)return[t.get(),r];let i=bO(e)?e():e;return t.set(i),[i,r]})}function Qt(e,t){Ar((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))Jt.queue(e);r.set(t)})}var ke=require("util");var Ae=xe(require("process"));function vO(){if(!Ae.default.platform.startsWith("win"))return Ae.default.env.TERM!=="linux";return Boolean(Ae.default.env.CI)||Boolean(Ae.default.env.WT_SESSION)||Boolean(Ae.default.env.TERMINUS_SUBLIME)||Ae.default.env.ConEmuTask==="{cmd::Cmder}"||Ae.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ae.default.env.TERM_PROGRAM==="vscode"||Ae.default.env.TERM==="xterm-256color"||Ae.default.env.TERM==="alacritty"||Ae.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var zg={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Wg={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},wO={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},$O={...zg,...Wg},EO={...zg,...wO},IO=vO(),SO=IO?$O:EO,kr=SO,RM=Object.entries(Wg);var xO={prefix:{idle:ke.styleText("blue","?"),done:ke.styleText("green",kr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>ke.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>ke.styleText("cyan",e),message:(e)=>ke.styleText("bold",e),error:(e)=>ke.styleText("red",`> ${e}`),defaultAnswer:(e)=>ke.styleText("dim",`(${e})`),help:(e)=>ke.styleText("dim",e),highlight:(e)=>ke.styleText("cyan",e),key:(e)=>ke.styleText("cyan",ke.styleText("bold",`<${e}>`))}};function Hg(){return{...xO,keybindings:Ug()}}function Jg(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Qg(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Jg(s)&&Jg(n)?Qg(s,n):n}return t}function Gi(...e){let t=[Hg(),...e.filter((r)=>r!=null)];return Qg(...t)}function dc({status:e="idle",theme:t}){let[r,i]=tt(!1),[n,s]=tt(0),{prefix:o,spinner:a}=Gi(t);if(Qt(()=>{if(e==="loading"){let u,l=-1,d=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Vi(e,t){return Ar((r)=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,s)=>n!==t[s])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function Yt(e){return tt({current:e})[0]}function uc(e){let t=Yt(e);t.current=e,Qt((r)=>{let i=!1,n=cc((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var my=xe(Xg(),1);var Zg=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),ey=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ty=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var jO=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,FO=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ry=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,OO=/\t{1,1000}/y,iy=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,TO=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,AO=/\p{M}+/gu,kO={limit:1/0,ellipsis:""},ny=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?ny(n,kO,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.emojiWidth??2,l=2,d=r.regularWidth??1,p=r.wideWidth??2,f=[[TO,d],[jO,0],[FO,a],[OO,c],[iy,u],[ry,p]],m=0,h=0,g=e.length,y=0,P=!1,v=g,w=Math.max(0,i-s),I=0,E=0,x=0,T=0;e:while(!0){if(E>I||h>=g&&h>m){let R=e.slice(I,E)||e.slice(m,h);y=0;for(let V of R.replaceAll(AO,"")){let J=V.codePointAt(0)||0;if(ey(J))T=2;else if(ty(J))T=p;else T=d;if(x+T>w)v=Math.min(v,Math.max(I,m)+y);if(x+T>i){P=!0;break e}y+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,X]=f[R];if(J.lastIndex=h,J.test(e)){if(y=J===ry?Zg(e.slice(h,J.lastIndex)):J===iy?1:J.lastIndex-h,T=y*X,x+T>w)v=Math.min(v,h+Math.floor((w-x)/X));if(x+T>i){P=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:P?w:x,index:P?v:g,truncated:P,ellipsed:P&&i>=s}},sy=ny;var DO={limit:1/0,ellipsis:"",ellipsisWidth:0},NO=(e,t={})=>sy(e,DO,t).width,ut=NO;var js="\x1B",dy="\x9B",LO=39,fc="\x07",uy="[",qO="]",py="m",mc=`${qO}8;;`,oy=new RegExp(`(?:\\${uy}(?<code>\\d+)m|\\${mc}(?<uri>.*)${fc})`,"y"),ay=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},ly=(e)=>`${js}${uy}${e}${py}`,cy=(e)=>`${js}${mc}${e}${fc}`,pc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:ut(o),c=i.next(),u=i.next(),l=0;while(!c.done){let d=c.value,p=ut(d);if(a+p<=r)e[e.length-1]+=d;else e.push(d),a=0;if(d===js||d===dy)n=!0,s=t.startsWith(mc,l+1);if(n){if(s){if(d===fc)n=!1,s=!1}else if(d===py)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;c=u,u=i.next(),l+=d.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},MO=(e)=>{let t=e.split(" "),r=t.length;while(r){if(ut(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},UO=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],c=0;for(let d=0;d<o.length;d++){let p=o[d];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=ut(h)}if(d!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=ut(p);if(r.hard&&f>t){let m=t-c,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");pc(a,p,t),c=ut(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){pc(a,p,t),c=ut(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){pc(a,p,t),c=ut(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}if(r.trim!==!1)a=a.map((d)=>MO(d));let u=a.join(`
137
- `),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(i+=p,!l){if(l=p>="\uD800"&&p<="\uDBFF",l)continue}else l=!1;if(p===js||p===dy){oy.lastIndex=d+1;let m=oy.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);n=h===LO?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(u[d+1]===`
138
- `){if(s)i+=cy("");let f=n?ay(n):void 0;if(n&&f)i+=ly(f)}else if(p===`
139
- `){if(n&&ay(n))i+=ly(n);if(s)i+=cy(s)}}return i},BO=/\r?\n/;function fy(e,t,r){return String(e).normalize().split(BO).map((i)=>UO(i,t,r)).join(`
136
+ `),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function Ug(e,t){return await e.secrets.set({projectId:t.projectId,name:t.name,value:t.value}),{name:t.name,output:`Set secret ${t.name}.`}}var yO=["emacs","vim"],_O=new Set(yO);function PO(e){return _O.has(e)}function Bg(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(PO)))}var Ui=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",xs=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var rc=(e)=>e.name==="backspace";var ic=(e)=>"1234567890".includes(e.name),nc=(e)=>e.name==="enter"||e.name==="return";class sc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class oc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Rs extends Error{name="ExitPromptError"}class ac extends Error{name="HookError"}class Bi extends Error{name="ValidationError"}var zg=require("async_hooks");var Cs=require("async_hooks");var Gg=new Cs.AsyncLocalStorage;function bO(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Vg(e,t){let r=bO(e);return Gg.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Ht(){let e=Gg.getStore();if(!e)throw new ac("[Inquirer] Hook functions can only be called from within a prompt");return e}function lc(){return Ht().rl}function cc(e){let t=(...r)=>{let i=Ht(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Cs.AsyncResource.bind(t)}function Ar(e){let t=Ht(),{index:r}=t,i={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},n=e(i);return t.index++,n}function Kg(){Ht().handleChange()}var Jt={queue(e){let t=Ht(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(lc());if(i!=null&&typeof i!=="function")throw new Bi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Ht();cc(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Ht();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function vO(e){return typeof e==="function"}function et(e){return Ar((t)=>{let r=zg.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),Kg()});if(t.initialized)return[t.get(),r];let i=vO(e)?e():e;return t.set(i),[i,r]})}function Qt(e,t){Ar((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))Jt.queue(e);r.set(t)})}var ke=require("util");var Ae=xe(require("process"));function wO(){if(!Ae.default.platform.startsWith("win"))return Ae.default.env.TERM!=="linux";return Boolean(Ae.default.env.CI)||Boolean(Ae.default.env.WT_SESSION)||Boolean(Ae.default.env.TERMINUS_SUBLIME)||Ae.default.env.ConEmuTask==="{cmd::Cmder}"||Ae.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ae.default.env.TERM_PROGRAM==="vscode"||Ae.default.env.TERM==="xterm-256color"||Ae.default.env.TERM==="alacritty"||Ae.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Wg={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Hg={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},$O={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},EO={...Wg,...Hg},IO={...Wg,...$O},SO=wO(),xO=SO?EO:IO,kr=xO,CM=Object.entries(Hg);var RO={prefix:{idle:ke.styleText("blue","?"),done:ke.styleText("green",kr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>ke.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>ke.styleText("cyan",e),message:(e)=>ke.styleText("bold",e),error:(e)=>ke.styleText("red",`> ${e}`),defaultAnswer:(e)=>ke.styleText("dim",`(${e})`),help:(e)=>ke.styleText("dim",e),highlight:(e)=>ke.styleText("cyan",e),key:(e)=>ke.styleText("cyan",ke.styleText("bold",`<${e}>`))}};function Jg(){return{...RO,keybindings:Bg()}}function Qg(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Yg(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Qg(s)&&Qg(n)?Yg(s,n):n}return t}function Gi(...e){let t=[Jg(),...e.filter((r)=>r!=null)];return Yg(...t)}function dc({status:e="idle",theme:t}){let[r,i]=et(!1),[n,s]=et(0),{prefix:o,spinner:a}=Gi(t);if(Qt(()=>{if(e==="loading"){let u,l=-1,d=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Vi(e,t){return Ar((r)=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,s)=>n!==t[s])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function Yt(e){return et({current:e})[0]}function uc(e){let t=Yt(e);t.current=e,Qt((r)=>{let i=!1,n=cc((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var hy=xe(Zg(),1);var ey=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),ty=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ry=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var FO=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,OO=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,iy=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,TO=/\t{1,1000}/y,ny=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,AO=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,kO=/\p{M}+/gu,DO={limit:1/0,ellipsis:""},sy=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?sy(n,DO,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.emojiWidth??2,l=2,d=r.regularWidth??1,p=r.wideWidth??2,f=[[AO,d],[FO,0],[OO,a],[TO,c],[ny,u],[iy,p]],m=0,h=0,g=e.length,y=0,P=!1,v=g,w=Math.max(0,i-s),I=0,E=0,x=0,T=0;e:while(!0){if(E>I||h>=g&&h>m){let R=e.slice(I,E)||e.slice(m,h);y=0;for(let V of R.replaceAll(kO,"")){let J=V.codePointAt(0)||0;if(ty(J))T=2;else if(ry(J))T=p;else T=d;if(x+T>w)v=Math.min(v,Math.max(I,m)+y);if(x+T>i){P=!0;break e}y+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,X]=f[R];if(J.lastIndex=h,J.test(e)){if(y=J===iy?ey(e.slice(h,J.lastIndex)):J===ny?1:J.lastIndex-h,T=y*X,x+T>w)v=Math.min(v,h+Math.floor((w-x)/X));if(x+T>i){P=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:P?w:x,index:P?v:g,truncated:P,ellipsed:P&&i>=s}},oy=sy;var NO={limit:1/0,ellipsis:"",ellipsisWidth:0},LO=(e,t={})=>oy(e,NO,t).width,pt=LO;var js="\x1B",uy="\x9B",qO=39,fc="\x07",py="[",MO="]",fy="m",mc=`${MO}8;;`,ay=new RegExp(`(?:\\${py}(?<code>\\d+)m|\\${mc}(?<uri>.*)${fc})`,"y"),ly=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},cy=(e)=>`${js}${py}${e}${fy}`,dy=(e)=>`${js}${mc}${e}${fc}`,pc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:pt(o),c=i.next(),u=i.next(),l=0;while(!c.done){let d=c.value,p=pt(d);if(a+p<=r)e[e.length-1]+=d;else e.push(d),a=0;if(d===js||d===uy)n=!0,s=t.startsWith(mc,l+1);if(n){if(s){if(d===fc)n=!1,s=!1}else if(d===fy)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;c=u,u=i.next(),l+=d.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},UO=(e)=>{let t=e.split(" "),r=t.length;while(r){if(pt(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},BO=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],c=0;for(let d=0;d<o.length;d++){let p=o[d];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=pt(h)}if(d!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=pt(p);if(r.hard&&f>t){let m=t-c,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");pc(a,p,t),c=pt(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){pc(a,p,t),c=pt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){pc(a,p,t),c=pt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}if(r.trim!==!1)a=a.map((d)=>UO(d));let u=a.join(`
137
+ `),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(i+=p,!l){if(l=p>="\uD800"&&p<="\uDBFF",l)continue}else l=!1;if(p===js||p===uy){ay.lastIndex=d+1;let m=ay.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);n=h===qO?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(u[d+1]===`
138
+ `){if(s)i+=dy("");let f=n?ly(n):void 0;if(n&&f)i+=cy(f)}else if(p===`
139
+ `){if(n&&ly(n))i+=cy(n);if(s)i+=dy(s)}}return i},GO=/\r?\n/;function my(e,t,r){return String(e).normalize().split(GO).map((i)=>BO(i,t,r)).join(`
140
140
  `)}function Ki(e,t){return e.split(`
141
- `).flatMap((r)=>fy(r,t,{trim:!1,wordWrap:!1}).split(`
141
+ `).flatMap((r)=>my(r,t,{trim:!1,wordWrap:!1}).split(`
142
142
  `).map((i)=>i.trimEnd())).join(`
143
- `)}function Fs(){return my.default({defaultWidth:80,output:lc().output})}function GO({active:e,renderedItems:t,pageSize:r,loop:i}){let n=Yt({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:o}=n.current,a=Math.floor(r/2),c=t.reduce((d,p)=>d+p.length,0),u=t.slice(0,e).reduce((d,p)=>d+p.length,0),l=u;if(c>r)if(i){if(l=s,o!=null&&o<e&&e-o<r)l=Math.min(a,Math.abs(e-o)===1?Math.min(s+(t[o]?.length??0),Math.max(u,s)):s+e-o)}else{let d=t.slice(e).reduce((p,f)=>p+f.length,0);l=d<r-a?r-d:Math.min(u,a)}return n.current.lastPointer=l,n.current.lastActive=e,l}function hc({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let s=Fs(),o=(y)=>(y%e.length+e.length)%e.length,a=e.map((y,P)=>{if(y==null)return[];return Ki(r({item:y,index:P,isActive:P===t}),s).split(`
144
- `)}),c=a.reduce((y,P)=>y+P.length,0),u=(y)=>a[y]??[],l=GO({active:t,renderedItems:a,pageSize:i,loop:n}),d=u(t).slice(0,i),p=l+d.length<=i?l:i-d.length,f=Array.from({length:i});f.splice(p,d.length,...d);let m=new Set([t]),h=p+d.length,g=o(t+1);while(h<i&&!m.has(g)&&(n&&c>i?g!==t:g>t)){let P=u(g).slice(0,i-h);f.splice(h,P.length,...P),m.add(g),h+=P.length,g=o(g+1)}h=p-1,g=o(t-1);while(h>=0&&!m.has(g)&&(n&&c>i?g!==t:g<t)){let y=u(g),P=y.slice(Math.max(0,y.length-h-1));f.splice(h-P.length+1,P.length,...P),m.add(g),h-=P.length,g=o(g-1)}return f.filter((y)=>typeof y==="string").join(`
145
- `)}var xy=xe(require("readline")),Ry=require("async_hooks"),Cy=xe(yy(),1);var Xt=[];Xt.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")Xt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Xt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Os=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",gc=Symbol.for("signal-exit emitter"),yc=globalThis,KO=Object.defineProperty.bind(Object);class _y{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(yc[gc])return yc[gc];KO(yc,gc,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],i=r.indexOf(t);if(i===-1)return;if(i===0&&r.length===1)r.length=0;else r.splice(i,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let n of this.listeners[e])i=n(t,r)===!0||i;if(e==="exit")i=this.emit("afterExit",t,r)||i;return i}}class Pc{}var zO=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class Py extends Pc{onExit(){return()=>{}}load(){}unload(){}}class by extends Pc{#r=_c.platform==="win32"?"SIGINT":"SIGHUP";#t=new _y;#e;#s;#o;#n={};#i=!1;constructor(e){super();this.#e=e,this.#n={};for(let t of Xt)this.#n[t]=()=>{let r=this.#e.listeners(t),{count:i}=this.#t,n=e;if(typeof n.__signal_exit_emitter__==="object"&&typeof n.__signal_exit_emitter__.count==="number")i+=n.__signal_exit_emitter__.count;if(r.length===i){this.unload();let s=this.#t.emit("exit",null,t),o=t==="SIGHUP"?this.#r:t;if(!s)e.kill(e.pid,o)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(e,t){if(!Os(this.#e))return()=>{};if(this.#i===!1)this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{if(this.#t.removeListener(r,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#i)return;this.#i=!0,this.#t.count+=1;for(let e of Xt)try{let t=this.#n[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#l(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#i)return;this.#i=!1,Xt.forEach((e)=>{let t=this.#n[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(r){}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#o,this.#t.count-=1}#a(e){if(!Os(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#o.call(this.#e,this.#e.exitCode)}#l(e,...t){let r=this.#s;if(e==="exit"&&Os(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let i=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),i}else return r.call(this.#e,e,...t)}}var _c=globalThis.process,{onExit:vy,load:dU,unload:uU}=zO(Os(_c)?new by(_c):new Py);var Sy=require("util");var bc="\x1B[G",$y="\x1B[?25l",Ey="\x1B[?25h",vc=(e=1)=>e>0?`\x1B[${e}A`:"",wc=(e=1)=>e>0?`\x1B[${e}B`:"",$c=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},wy="\x1B[2K",Ec=(e)=>e>0?(wy+vc(1)).repeat(e-1)+wy+bc:"";var Iy=(e)=>e.split(`
146
- `).length,WO=(e)=>e.split(`
147
- `).pop()??"";class Ts{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let r=WO(e),i=Sy.stripVTControlCharacters(r),n=i;if(this.rl.line.length>0)n=n.slice(0,-this.rl.line.length);this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let s=Fs();if(e=Ki(e,s),t=Ki(t,s),i.length%s===0)e+=`
143
+ `)}function Fs(){return hy.default({defaultWidth:80,output:lc().output})}function VO({active:e,renderedItems:t,pageSize:r,loop:i}){let n=Yt({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:o}=n.current,a=Math.floor(r/2),c=t.reduce((d,p)=>d+p.length,0),u=t.slice(0,e).reduce((d,p)=>d+p.length,0),l=u;if(c>r)if(i){if(l=s,o!=null&&o<e&&e-o<r)l=Math.min(a,Math.abs(e-o)===1?Math.min(s+(t[o]?.length??0),Math.max(u,s)):s+e-o)}else{let d=t.slice(e).reduce((p,f)=>p+f.length,0);l=d<r-a?r-d:Math.min(u,a)}return n.current.lastPointer=l,n.current.lastActive=e,l}function hc({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let s=Fs(),o=(y)=>(y%e.length+e.length)%e.length,a=e.map((y,P)=>{if(y==null)return[];return Ki(r({item:y,index:P,isActive:P===t}),s).split(`
144
+ `)}),c=a.reduce((y,P)=>y+P.length,0),u=(y)=>a[y]??[],l=VO({active:t,renderedItems:a,pageSize:i,loop:n}),d=u(t).slice(0,i),p=l+d.length<=i?l:i-d.length,f=Array.from({length:i});f.splice(p,d.length,...d);let m=new Set([t]),h=p+d.length,g=o(t+1);while(h<i&&!m.has(g)&&(n&&c>i?g!==t:g>t)){let P=u(g).slice(0,i-h);f.splice(h,P.length,...P),m.add(g),h+=P.length,g=o(g+1)}h=p-1,g=o(t-1);while(h>=0&&!m.has(g)&&(n&&c>i?g!==t:g<t)){let y=u(g),P=y.slice(Math.max(0,y.length-h-1));f.splice(h-P.length+1,P.length,...P),m.add(g),h-=P.length,g=o(g-1)}return f.filter((y)=>typeof y==="string").join(`
145
+ `)}var Ry=xe(require("readline")),Cy=require("async_hooks"),jy=xe(_y(),1);var Xt=[];Xt.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")Xt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Xt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Os=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",gc=Symbol.for("signal-exit emitter"),yc=globalThis,zO=Object.defineProperty.bind(Object);class Py{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(yc[gc])return yc[gc];zO(yc,gc,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],i=r.indexOf(t);if(i===-1)return;if(i===0&&r.length===1)r.length=0;else r.splice(i,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let n of this.listeners[e])i=n(t,r)===!0||i;if(e==="exit")i=this.emit("afterExit",t,r)||i;return i}}class Pc{}var WO=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class by extends Pc{onExit(){return()=>{}}load(){}unload(){}}class vy extends Pc{#r=_c.platform==="win32"?"SIGINT":"SIGHUP";#t=new Py;#e;#s;#o;#n={};#i=!1;constructor(e){super();this.#e=e,this.#n={};for(let t of Xt)this.#n[t]=()=>{let r=this.#e.listeners(t),{count:i}=this.#t,n=e;if(typeof n.__signal_exit_emitter__==="object"&&typeof n.__signal_exit_emitter__.count==="number")i+=n.__signal_exit_emitter__.count;if(r.length===i){this.unload();let s=this.#t.emit("exit",null,t),o=t==="SIGHUP"?this.#r:t;if(!s)e.kill(e.pid,o)}};this.#o=e.reallyExit,this.#s=e.emit}onExit(e,t){if(!Os(this.#e))return()=>{};if(this.#i===!1)this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{if(this.#t.removeListener(r,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#i)return;this.#i=!0,this.#t.count+=1;for(let e of Xt)try{let t=this.#n[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#l(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#i)return;this.#i=!1,Xt.forEach((e)=>{let t=this.#n[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(r){}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#o,this.#t.count-=1}#a(e){if(!Os(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#o.call(this.#e,this.#e.exitCode)}#l(e,...t){let r=this.#s;if(e==="exit"&&Os(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let i=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),i}else return r.call(this.#e,e,...t)}}var _c=globalThis.process,{onExit:wy,load:uU,unload:pU}=WO(Os(_c)?new vy(_c):new by);var xy=require("util");var bc="\x1B[G",Ey="\x1B[?25l",Iy="\x1B[?25h",vc=(e=1)=>e>0?`\x1B[${e}A`:"",wc=(e=1)=>e>0?`\x1B[${e}B`:"",$c=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},$y="\x1B[2K",Ec=(e)=>e>0?($y+vc(1)).repeat(e-1)+$y+bc:"";var Sy=(e)=>e.split(`
146
+ `).length,HO=(e)=>e.split(`
147
+ `).pop()??"";class Ts{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let r=HO(e),i=xy.stripVTControlCharacters(r),n=i;if(this.rl.line.length>0)n=n.slice(0,-this.rl.line.length);this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let s=Fs();if(e=Ki(e,s),t=Ki(t,s),i.length%s===0)e+=`
148
148
  `;let o=e+(t?`
149
- `+t:""),c=Math.floor(i.length/s)-this.cursorPos.rows+(t?Iy(t):0);if(c>0)o+=vc(c);o+=$c(this.cursorPos.cols),this.write(wc(this.extraLinesUnderPrompt)+Ec(this.height)+o),this.extraLinesUnderPrompt=c,this.height=Iy(o)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write($c(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=wc(this.extraLinesUnderPrompt);t+=e?Ec(this.height):`
150
- `,t+=bc,t+=Ey,this.write(t),this.rl.close()}}class Ic extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,n)=>{e=i,t=n}),resolve:e,reject:t}}}var jy=xe(require("path")),HO=globalThis.setImmediate;function JO(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,i)=>{let n=i.slice(1);return t=n,n},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function Sc(e){let t=JO();return(i,n={})=>{let{input:s=process.stdin,signal:o}=n,a=new Set,c=new Cy.default;c.pipe(n.output??process.stdout);let u=xy.createInterface({terminal:!0,input:s,output:c});c.mute();let l=new Ts(u),{promise:d,resolve:p,reject:f}=Ic.withResolver(),m=()=>f(new oc);if(o){let g=()=>f(new sc({cause:o.reason}));if(o.aborted)return g(),Object.assign(d,{cancel:m});o.addEventListener("abort",g),a.add(()=>o.removeEventListener("abort",g))}a.add(vy((g,y)=>{f(new Rs(`User force closed the prompt with ${g} ${y}`))}));let h=()=>f(new Rs("User force closed the prompt with SIGINT"));return u.on("SIGINT",h),a.add(()=>u.removeListener("SIGINT",h)),Gg(u,(g)=>{let y=Ry.AsyncResource.bind(()=>Jt.clearAll());u.on("close",y),a.add(()=>u.removeListener("close",y));let P=()=>{let v=()=>l.checkCursorPos();u.input.on("keypress",v),a.add(()=>u.input.removeListener("keypress",v));let w=null;g(()=>{let I=!1;try{let E=e(i,(R)=>{if(I)p(R);else w={value:R}});if(E===void 0){let R=t[1]?.getFileName();if(R&&!R.startsWith("file://"))R=jy.default.resolve(R);throw Error(`Prompt functions must return a string.
151
- at ${R}`)}let[x,T]=typeof E==="string"?[E]:E;l.render(x,T),Jt.run()}catch(E){f(E)}if(I=!0,w!==null){let{value:E}=w;w=null,p(E)}})};if("readableFlowing"in s)HO(P);else P();return Object.assign(d.then((v)=>(Jt.clearAll(),v),(v)=>{throw Jt.clearAll(),v}).finally(()=>{a.forEach((v)=>v()),l.done({clearContent:Boolean(n.clearPromptOnDone)}),c.end()}).then(()=>d),{cancel:m})})}}var Fy=require("util");class rt{separator=Fy.styleText("dim",Array.from({length:15}).join(kr.line));type="separator";constructor(e){if(e)this.separator=e}static isSeparator(e){return Boolean(e&&typeof e==="object"&&"type"in e&&e.type==="separator")}}var Dr=require("util");var QO={icon:{cursor:kr.pointer},style:{disabled:(e)=>Dr.styleText("dim",e),description:(e)=>Dr.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Dr.styleText("bold",t)} ${Dr.styleText("dim",r)}`).join(Dr.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function xc(e){return!rt.isSeparator(e)&&!e.disabled}function Rc(e){return!rt.isSeparator(e)}function YO(e){return e.map((t)=>{if(rt.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let n=String(t);return{value:t,name:n,short:n,disabled:!1}}let r=t.name??String(t.value),i={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)i.description=t.description;return i})}var Oy=Sc((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=Gi(QO,e.theme),{keybindings:s}=n,[o,a]=tt("idle"),c=dc({status:o,theme:n}),u=Yt(),l=!s.includes("vim"),d=Vi(()=>YO(e.choices),[e.choices]),p=Vi(()=>{let R=d.findIndex(Rc),V=d.findLastIndex(Rc);if(R===-1)throw new Bi("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:V}},[d]),f=Vi(()=>{if(!("default"in e))return-1;return d.findIndex((R)=>xc(R)&&R.value===e.default)},[e.default,d]),[m,h]=tt(f===-1?p.first:f),g=d[m];if(g==null||rt.isSeparator(g))throw Error("Active index does not point to a choice");let[y,P]=tt();uc((R,V)=>{if(clearTimeout(u.current),y)P(void 0);if(nc(R))if(g.disabled)P(n.i18n.disabledError);else a("done"),t(g.value);else if(Ui(R,s)||xs(R,s)){if(V.clearLine(0),r||Ui(R,s)&&m!==p.first||xs(R,s)&&m!==p.last){let J=Ui(R,s)?-1:1,X=m;do X=(X+J+d.length)%d.length;while(!Rc(d[X]));h(X)}}else if(ic(R)&&!Number.isNaN(Number(V.line))){let J=Number(V.line)-1,X=-1,Se=d.findIndex((Mr)=>{if(rt.isSeparator(Mr))return!1;return X++,X===J}),qr=d[Se];if(qr!=null&&xc(qr))h(Se);u.current=setTimeout(()=>{V.clearLine(0)},700)}else if(rc(R))V.clearLine(0);else if(l){let J=V.line.toLowerCase(),X=d.findIndex((Se)=>{if(rt.isSeparator(Se)||!xc(Se))return!1;return Se.name.toLowerCase().startsWith(J)});if(X!==-1)h(X);u.current=setTimeout(()=>{V.clearLine(0)},700)}}),Qt(()=>()=>{clearTimeout(u.current)},[]);let v=n.style.message(e.message,o),w=n.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),I=0,E=hc({items:d,active:m,renderItem({item:R,isActive:V,index:J}){if(rt.isSeparator(R))return I++,` ${R.separator}`;let X=V?n.icon.cursor:" ",Se=n.indexMode==="number"?`${J+1-I}. `:"";if(R.disabled){let Mr=typeof R.disabled==="string"?R.disabled:"(disabled)",Jy=V?n.icon.cursor:"-";return n.style.disabled(`${Jy} ${Se}${R.name} ${Mr}`)}return(V?n.style.highlight:(Mr)=>Mr)(`${X} ${Se}${R.name}`)},pageSize:i,loop:r});if(o==="done")return[c,v,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:x}=g;return`${[[c,v].filter(Boolean).join(" "),E," ",x?n.style.description(x):"",y?n.style.error(y):"",w].filter(Boolean).join(`
152
- `).trimEnd()}${$y}`});var XO="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",ZO=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},eT=(e,t)=>{if(t===void 0||t.projectId!==e)return new Map;let r=new Map;for(let[n,s]of Object.entries(t.pipelines)){let o=r.get(s.pipelineId)??[];o.push(n),r.set(s.pipelineId,o)}let i=new Map;for(let[n,s]of r){let[o,...a]=s;if(o!==void 0&&a.length===0)i.set(n,o)}return i},tT=(e,t)=>{let r=t.get(e.id);return{pipelineId:e.id,name:e.name,...r===void 0?{}:{sourceDirectory:r}}},Nr=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,rT=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(Nr).join(", ")}.`;async function Ay(e){return Oy({message:"This project tracks several pipelines. Select one",choices:e})}async function ky(e){let t=await Dy(e.client,e.projectId,e.state);if(t.length===0)return{outcome:"reported",output:"This project has no pipelines."};return{outcome:"reported",output:t.map((r)=>r.sourceDirectory===void 0?`${r.name} ${r.pipelineId}`:`${r.name} ${r.pipelineId} ${r.sourceDirectory}`).join(`
153
- `)}}var Dy=async(e,t,r)=>{let i=await ZO(e.pipelines.listAll({projectId:t})),n=eT(t,r);return i.map((s)=>tT(s,n)).toSorted((s,o)=>{let a=s.name.localeCompare(o.name);return a===0?s.pipelineId.localeCompare(o.pipelineId):a})},As=(e,t,r)=>{if(_(e.length<=1,t),e.length!==1)return;let[i]=e;return _(i,r),i},Ty=(e,t)=>{let r=rT(t),i=As(t.filter((u)=>u.pipelineId===e),r,r);if(i!==void 0)return i;let n=t.filter((u)=>u.name===e),s=As(n,`Multiple pipelines are named ${e}: ${n.map(Nr).join(", ")}.`,r);if(s!==void 0)return s;let o=As(t.filter((u)=>u.sourceDirectory===e),r,r);if(o!==void 0)return o;let a=t.filter((u)=>{if(u.sourceDirectory===void 0)return!1;let l=u.sourceDirectory.split("/");return l[l.length-1]===e}),c=As(a,`Multiple pipelines match ${e}: ${a.map(Nr).join(", ")}.`,r);if(c!==void 0)return c;_(!1,r)};async function zi(e){let t=await Dy(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return Ty(e.pipeline,t);if(_(t.length>0,"This project has no pipelines."),t.length>1&&e.select!==void 0){let r=await e.select(t.map((i)=>({name:Nr(i),value:i.pipelineId})));return Ty(r,t)}if(t.length===1){let[r]=t;_(r,"This project has no pipelines."),_(!1,`Pass a pipeline name. This project has: ${Nr(r)}.`)}_(!1,`This project tracks several pipelines, so name one: ${t.map(Nr).join(", ")}.`)}var Ny=(e)=>`run ${e.id} is ${e.status}`,Ly=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function qy(e,t){let r=await zi({client:e,...t}),i=await e.runs.start({pipelineId:r.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${Ny(i)} for ${r.name}.`,`Follow it with toloka pipeline status ${r.pipelineId}, or re-run with --wait.`].join(`
154
- `)};try{let n=await e.waitFor({type:"pipelineRun",runId:i.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),s=Ly(n);return{outcome:s,output:s==="failed"?[`Run ${n.id} failed.`,`Inspect items with toloka pipeline results ${n.id} --failed.`].join(`
149
+ `+t:""),c=Math.floor(i.length/s)-this.cursorPos.rows+(t?Sy(t):0);if(c>0)o+=vc(c);o+=$c(this.cursorPos.cols),this.write(wc(this.extraLinesUnderPrompt)+Ec(this.height)+o),this.extraLinesUnderPrompt=c,this.height=Sy(o)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write($c(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=wc(this.extraLinesUnderPrompt);t+=e?Ec(this.height):`
150
+ `,t+=bc,t+=Iy,this.write(t),this.rl.close()}}class Ic extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,n)=>{e=i,t=n}),resolve:e,reject:t}}}var Fy=xe(require("path")),JO=globalThis.setImmediate;function QO(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,i)=>{let n=i.slice(1);return t=n,n},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function Sc(e){let t=QO();return(i,n={})=>{let{input:s=process.stdin,signal:o}=n,a=new Set,c=new jy.default;c.pipe(n.output??process.stdout);let u=Ry.createInterface({terminal:!0,input:s,output:c});c.mute();let l=new Ts(u),{promise:d,resolve:p,reject:f}=Ic.withResolver(),m=()=>f(new oc);if(o){let g=()=>f(new sc({cause:o.reason}));if(o.aborted)return g(),Object.assign(d,{cancel:m});o.addEventListener("abort",g),a.add(()=>o.removeEventListener("abort",g))}a.add(wy((g,y)=>{f(new Rs(`User force closed the prompt with ${g} ${y}`))}));let h=()=>f(new Rs("User force closed the prompt with SIGINT"));return u.on("SIGINT",h),a.add(()=>u.removeListener("SIGINT",h)),Vg(u,(g)=>{let y=Cy.AsyncResource.bind(()=>Jt.clearAll());u.on("close",y),a.add(()=>u.removeListener("close",y));let P=()=>{let v=()=>l.checkCursorPos();u.input.on("keypress",v),a.add(()=>u.input.removeListener("keypress",v));let w=null;g(()=>{let I=!1;try{let E=e(i,(R)=>{if(I)p(R);else w={value:R}});if(E===void 0){let R=t[1]?.getFileName();if(R&&!R.startsWith("file://"))R=Fy.default.resolve(R);throw Error(`Prompt functions must return a string.
151
+ at ${R}`)}let[x,T]=typeof E==="string"?[E]:E;l.render(x,T),Jt.run()}catch(E){f(E)}if(I=!0,w!==null){let{value:E}=w;w=null,p(E)}})};if("readableFlowing"in s)JO(P);else P();return Object.assign(d.then((v)=>(Jt.clearAll(),v),(v)=>{throw Jt.clearAll(),v}).finally(()=>{a.forEach((v)=>v()),l.done({clearContent:Boolean(n.clearPromptOnDone)}),c.end()}).then(()=>d),{cancel:m})})}}var Oy=require("util");class tt{separator=Oy.styleText("dim",Array.from({length:15}).join(kr.line));type="separator";constructor(e){if(e)this.separator=e}static isSeparator(e){return Boolean(e&&typeof e==="object"&&"type"in e&&e.type==="separator")}}var Dr=require("util");var YO={icon:{cursor:kr.pointer},style:{disabled:(e)=>Dr.styleText("dim",e),description:(e)=>Dr.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Dr.styleText("bold",t)} ${Dr.styleText("dim",r)}`).join(Dr.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function xc(e){return!tt.isSeparator(e)&&!e.disabled}function Rc(e){return!tt.isSeparator(e)}function XO(e){return e.map((t)=>{if(tt.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let n=String(t);return{value:t,name:n,short:n,disabled:!1}}let r=t.name??String(t.value),i={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)i.description=t.description;return i})}var Ty=Sc((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=Gi(YO,e.theme),{keybindings:s}=n,[o,a]=et("idle"),c=dc({status:o,theme:n}),u=Yt(),l=!s.includes("vim"),d=Vi(()=>XO(e.choices),[e.choices]),p=Vi(()=>{let R=d.findIndex(Rc),V=d.findLastIndex(Rc);if(R===-1)throw new Bi("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:V}},[d]),f=Vi(()=>{if(!("default"in e))return-1;return d.findIndex((R)=>xc(R)&&R.value===e.default)},[e.default,d]),[m,h]=et(f===-1?p.first:f),g=d[m];if(g==null||tt.isSeparator(g))throw Error("Active index does not point to a choice");let[y,P]=et();uc((R,V)=>{if(clearTimeout(u.current),y)P(void 0);if(nc(R))if(g.disabled)P(n.i18n.disabledError);else a("done"),t(g.value);else if(Ui(R,s)||xs(R,s)){if(V.clearLine(0),r||Ui(R,s)&&m!==p.first||xs(R,s)&&m!==p.last){let J=Ui(R,s)?-1:1,X=m;do X=(X+J+d.length)%d.length;while(!Rc(d[X]));h(X)}}else if(ic(R)&&!Number.isNaN(Number(V.line))){let J=Number(V.line)-1,X=-1,Se=d.findIndex((Mr)=>{if(tt.isSeparator(Mr))return!1;return X++,X===J}),qr=d[Se];if(qr!=null&&xc(qr))h(Se);u.current=setTimeout(()=>{V.clearLine(0)},700)}else if(rc(R))V.clearLine(0);else if(l){let J=V.line.toLowerCase(),X=d.findIndex((Se)=>{if(tt.isSeparator(Se)||!xc(Se))return!1;return Se.name.toLowerCase().startsWith(J)});if(X!==-1)h(X);u.current=setTimeout(()=>{V.clearLine(0)},700)}}),Qt(()=>()=>{clearTimeout(u.current)},[]);let v=n.style.message(e.message,o),w=n.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),I=0,E=hc({items:d,active:m,renderItem({item:R,isActive:V,index:J}){if(tt.isSeparator(R))return I++,` ${R.separator}`;let X=V?n.icon.cursor:" ",Se=n.indexMode==="number"?`${J+1-I}. `:"";if(R.disabled){let Mr=typeof R.disabled==="string"?R.disabled:"(disabled)",Qy=V?n.icon.cursor:"-";return n.style.disabled(`${Qy} ${Se}${R.name} ${Mr}`)}return(V?n.style.highlight:(Mr)=>Mr)(`${X} ${Se}${R.name}`)},pageSize:i,loop:r});if(o==="done")return[c,v,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:x}=g;return`${[[c,v].filter(Boolean).join(" "),E," ",x?n.style.description(x):"",y?n.style.error(y):"",w].filter(Boolean).join(`
152
+ `).trimEnd()}${Ey}`});var ZO="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",eT=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},tT=(e,t)=>{if(t===void 0||t.projectId!==e)return new Map;let r=new Map;for(let[n,s]of Object.entries(t.pipelines)){let o=r.get(s.pipelineId)??[];o.push(n),r.set(s.pipelineId,o)}let i=new Map;for(let[n,s]of r){let[o,...a]=s;if(o!==void 0&&a.length===0)i.set(n,o)}return i},rT=(e,t)=>{let r=t.get(e.id);return{pipelineId:e.id,name:e.name,...r===void 0?{}:{sourceDirectory:r}}},Nr=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,iT=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(Nr).join(", ")}.`;async function ky(e){return Ty({message:"This project tracks several pipelines. Select one",choices:e})}async function Dy(e){let t=await Ny(e.client,e.projectId,e.state);if(t.length===0)return{outcome:"reported",output:"This project has no pipelines."};return{outcome:"reported",output:t.map((r)=>r.sourceDirectory===void 0?`${r.name} ${r.pipelineId}`:`${r.name} ${r.pipelineId} ${r.sourceDirectory}`).join(`
153
+ `)}}var Ny=async(e,t,r)=>{let i=await eT(e.pipelines.listAll({projectId:t})),n=tT(t,r);return i.map((s)=>rT(s,n)).toSorted((s,o)=>{let a=s.name.localeCompare(o.name);return a===0?s.pipelineId.localeCompare(o.pipelineId):a})},As=(e,t,r)=>{if(_(e.length<=1,t),e.length!==1)return;let[i]=e;return _(i,r),i},Ay=(e,t)=>{let r=iT(t),i=As(t.filter((u)=>u.pipelineId===e),r,r);if(i!==void 0)return i;let n=t.filter((u)=>u.name===e),s=As(n,`Multiple pipelines are named ${e}: ${n.map(Nr).join(", ")}.`,r);if(s!==void 0)return s;let o=As(t.filter((u)=>u.sourceDirectory===e),r,r);if(o!==void 0)return o;let a=t.filter((u)=>{if(u.sourceDirectory===void 0)return!1;let l=u.sourceDirectory.split("/");return l[l.length-1]===e}),c=As(a,`Multiple pipelines match ${e}: ${a.map(Nr).join(", ")}.`,r);if(c!==void 0)return c;_(!1,r)};async function zi(e){let t=await Ny(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return Ay(e.pipeline,t);if(_(t.length>0,"This project has no pipelines."),t.length>1&&e.select!==void 0){let r=await e.select(t.map((i)=>({name:Nr(i),value:i.pipelineId})));return Ay(r,t)}if(t.length===1){let[r]=t;_(r,"This project has no pipelines."),_(!1,`Pass a pipeline name. This project has: ${Nr(r)}.`)}_(!1,`This project tracks several pipelines, so name one: ${t.map(Nr).join(", ")}.`)}var Ly=(e)=>`run ${e.id} is ${e.status}`,qy=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function My(e,t){let r=await zi({client:e,...t}),i=await e.runs.start({pipelineId:r.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${Ly(i)} for ${r.name}.`,`Follow it with toloka pipeline status ${r.pipelineId}, or re-run with --wait.`].join(`
154
+ `)};try{let n=await e.waitFor({type:"pipelineRun",runId:i.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),s=qy(n);return{outcome:s,output:s==="failed"?[`Run ${n.id} failed.`,`Inspect items with toloka pipeline results ${n.id} --failed.`].join(`
155
155
  `):`Run ${n.id} succeeded.`}}catch(n){if(n instanceof re&&n.code==="wait_timeout")return{outcome:"timedOut",output:[`Stopped waiting for run ${i.id}; it has not reached a terminal state yet and may still be running.`,`Check it with toloka pipeline status ${r.pipelineId}.`].join(`
156
- `)};throw n}}async function My(e,t){let r=await zi({client:e,...t}),i=await e.runs.listPage({pipelineId:r.pipelineId,limit:t.limit??10});if(i.runs.length===0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let n=[];for(let s of i.runs){let o=await e.runs.get({runId:s.id});n.push(` ${o.id} ${o.status.padEnd(9)} ${s.createdAt}`)}return{outcome:"reported",output:[`Runs for ${r.name} (${i.pagination.total} total):`,...n].join(`
157
- `)}}async function Uy(e,t){let r=await zi({client:e,...t}),n=(await e.runs.listPage({pipelineId:r.pipelineId,limit:1})).runs[0];if(n===void 0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let s=await e.runs.get({runId:n.id}),o=t.itemScanLimit??500,a=new Map,c=0;for await(let l of e.runs.listAllItems({runId:s.id}))if(a.set(l.state.status,(a.get(l.state.status)??0)+1),c+=1,c>=o)break;let u=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([l],[d])=>l.localeCompare(d)).map(([l,d])=>` ${l.padEnd(12)} ${d}`);return{outcome:Ly(s),output:[`Latest ${Ny(s)} (started ${n.createdAt}).`,c>=o?`Items (first ${o}):`:"Items:",...u].join(`
158
- `)}}async function By(e,t){let r=await e.runs.cancel({runId:t.runId});return{outcome:"canceled",output:`Requested cancellation of run ${r.id}; it is now ${r.status}.`}}var iT=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
159
- ${XO}`;return e.state.error===null?t:`${t}
160
- ${e.state.error}`};async function Gy(e,t){let r=t.limit??20,i=t.itemScanLimit??Math.max(500,r),n=[],s=0;for await(let c of e.runs.listAllItems({runId:t.runId})){if(s+=1,t.failedOnly!==!0||c.state.status==="failed")n.push(c);if(n.length>=r||s>=i)break}if(n.length===0)return{outcome:"reported",output:t.failedOnly===!0&&s>=i?`No failed items in the first ${i} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[s>=i&&n.length<r?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length} after scanning ${i}, limit ${r}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length}, limit ${r}):`,...n.map(iT)].join(`
161
- `)}}var Vy=(e)=>{if(typeof e!=="object"||e===null)return!1;if(!("label"in e)||typeof e.label!=="string")return!1;if(!("expectedTotal"in e)||typeof e.expectedTotal!=="string")return!1;if(!("maxTotal"in e)||typeof e.maxTotal!=="string")return!1;if("subLines"in e&&e.subLines!==void 0&&!Array.isArray(e.subLines))return!1;return!0},nT=(e)=>{let t=[0,0,0];for(let r of e)for(let i=0;i<3;i+=1){let n=r[i];t[i]=Math.max(t[i]??0,n?.length??0)}return e.map((r)=>r.map((i,n)=>n===0?i.padEnd(t[0]??0):i.padStart(t[n]??0)).join(" "))},Ky=(e,t)=>{let i=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let n of e.subLines??[])if(Vy(n))i.push(...Ky(n,t+1));return i},sT=(e)=>{let t=[],r=[];for(let i of e){if(i.kind==="priced"){t.push([i.nodeNameDisplay,i.expectedTotal,i.maxTotal]);for(let n of i.displayBreakdown)if(Vy(n))t.push(...Ky(n,1));continue}r.push(i.kind==="validation-errors"?` ${i.nodeNameDisplay} skipped (validation errors)`:` ${i.nodeNameDisplay} not billed`)}return{billed:t,unpriced:r}},oT=(e)=>{let t=[["Total",e.expected,e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,""]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},aT=(e,t)=>{let{billed:r,unpriced:i}=sT(e.nodes),n=oT(e.total),s=nT([["Item","Expected","Maximum"],...r,...n]),o=s.slice(0,1+r.length),a=s.slice(1+r.length),c=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...o];if(r.length===0)c.push(" (no billed nodes)");if(c.push("",...a),i.length>0)c.push("","Not billed",...i);if(e.isInternalPricing===!0)c.push("","Internal-team pricing.");return c.push("",e.disclaimer),c.join(`
162
- `)};async function zy(e,t){let r=await zi({client:e,...t}),i=await e.pipelines.estimateCost({pipelineId:r.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:aT(i,r.name)}}var lT=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. POTATO_API_KEY / POTATO_BASE_URL"," 3. the file written by toloka login",`The platform defaults to ${_r}.`].join(`
163
- `),Lr=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new pt("Expected a positive integer.");return t},Cc=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},Wi=async(e,t)=>{if(e.sourceRoot!==void 0)return Ji.resolve(e.sourceRoot);let r=process.cwd(),i=await $g(r);if(i===void 0||i===r)return r;return t.stderr(`Using project root ${i} (found from ${r}).`),i},cT=(e)=>e.sourceRoot===void 0?process.cwd():Ji.resolve(e.sourceRoot),Fc=async(e,t)=>{let{found:r,warning:i}=await yi(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(i!==void 0)t.io.stderr(i);return r?.credentials},Hi=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},te=async(e,t)=>{let r=await Wi(e,t.io),i=await $e(r),n=await Fc(e,t),s=rl(e,i,t.environment,n),o=t.injectedClient??nt({apiKey:s.apiKey,baseUrl:s.baseUrl});return await Hi(o,t.analytics),{sourceRoot:r,client:o,state:i,stored:n,...s.projectId===void 0?{}:{projectId:s.projectId}}},jc=(e,t,r,i)=>Pi({flags:e,environment:t.environment,stored:r,...i===void 0?{}:{state:i}});function dT(e){let t=new Zt("toloka"),r={value:0},i=!1;t.description("Preview. Build and operate Toloka pipeline projects from TypeScript source. The public API may change.").option("--source-root <directory>","project root; discovered from the working directory when omitted").option("--api-key <key>","API key for this command only").option("--base-url <url>","platform base URL for this command only").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
164
- ${lT}`).configureOutput({writeOut:(l)=>e.io.stdout(l.replace(/\n$/u,"")),writeErr:(l)=>e.io.stderr(l.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(l)=>{if(i)return;let d=[];for(let m=l;m!==null;m=m.parent)d.push(m.name());if(d.includes("init")||d.includes("help"))return;let p=await Wi(n(),e.io),f=await Oh(p).catch(()=>{return});if(f===void 0)return;i=!0,e.io.stderr(f)}),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let l=await Uf({...n().apiKey===void 0?{}:{apiKey:n().apiKey},...n().baseUrl===void 0?{}:{baseUrl:n().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(l.output);try{let d=await Cf(e.environment);if(d===void 0)return;let p=e.injectedClient??nt(d);await Hi(p,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let l=await Bf(e.environment);e.io.stdout(l.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(l)=>{let d=n(),p=await yi(e.environment,d.apiKey??e.environment.POTATO_API_KEY),f=p.found?.credentials,m=await Wi(d,e.io),h=await $e(m),g=jc(d,e,f,h),y=e.injectedClient,P=await Vf({environment:e.environment,showToken:l.showToken,credentialLookup:p,...d.apiKey===void 0?{}:{flagApiKey:d.apiKey},...d.baseUrl===void 0?{}:{flagBaseUrl:d.baseUrl},...y===void 0?{}:{probe:()=>y},...g===void 0?{}:{project:g}});if(e.io.stdout(P.output),!P.authenticated){r.value=1;return}try{let v=rl(d,h,e.environment,f),w=e.injectedClient??nt({apiKey:v.apiKey,baseUrl:v.baseUrl});await Hi(w,e.analytics)}catch{}});let s=t.command("project").description("select and manage the current platform project");s.command("list").description("list remote projects this key can see").action(async()=>{let l=n(),{client:d,stored:p,state:f}=await te(l,e),m=jc(l,e,p,f);await Af({client:d,io:e.io,...m===void 0?{}:{context:m}})}),s.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??nt(f.credentials);await kf({environment:e.environment,flags:p,client:m,io:e.io,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d===void 0?{}:{projectId:d}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(l)=>{await Df({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let l=n(),d=await Fc(l,e),p=await Wi(l,e.io),f=await $e(p);if(Lf({flags:l,environment:e.environment,stored:d,...f===void 0?{}:{state:f},io:e.io}).project===void 0)r.value=1}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(l)=>{await Nf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??nt(f.credentials),h=await Wi(p,e.io);await qf({environment:e.environment,flags:p,client:m,io:e.io,sourceRoot:h,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d.name===void 0?{}:{name:d.name},...d.teamId===void 0?{}:{teamId:d.teamId}})}),t.command("init").description("initialize this project directory and install agent skills").action(async()=>{let l=n(),d=cT(l),p=await Fc(l,e),f=await $e(d),m=jc(l,e,p,f),h=await Fh(d,m===void 0?{}:{projectId:m.id});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=l??m;_(h,he);let g=await xg(f,{sourceRoot:p,projectId:h,...d?.force===!0?{force:!0}:{}});e.io.stdout(g.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Rg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Fg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});if(e.io.stdout(f.output),!f.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await jg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(l,d)=>{let{client:p,projectId:f}=await te(n(),e);_(f,he);let m=d.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[d.fromEnv];_(m!==void 0,`Missing secret value. Set ${d.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let h=await Mg(p,{projectId:f,name:l,value:m});e.io.stdout(h.output)}catch{e.io.stderr(`Failed to set secret ${l}.`),r.value=1}});let a=t.command("dataset").description("inspect and move dataset catalog and rows");a.command("list").description("list live datasets in the selected project").action(async()=>{let{client:l,projectId:d}=await te(n(),e);_(d,he);let p=await Lg(l,{projectId:d});e.io.stdout(p.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(l)=>{let{sourceRoot:d,client:p,projectId:f}=await te(n(),e),m=await Ng(p,{sourceRoot:d,datasetName:l,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),a.command("load").argument("<name>","dataset name or id").requiredOption("--out <file>","JSONL file to write").option("--limit <n>","how many rows to keep after download",Lr).option("--timeout <ms>","how long to wait for the export",Lr).description("download live dataset rows into a JSONL file").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await qg(f,{sourceRoot:p,datasetName:l,outPath:Ji.resolve(d.out),...m===void 0?{}:{projectId:m},...d.limit===void 0?{}:{limit:d.limit},...d.timeout===void 0?{}:{timeoutMs:d.timeout}});e.io.stdout(h.output)}),a.command("upload").argument("<name>","dataset name or id").argument("<file>","JSONL file, one JSON object per line").description("append rows to a dataset").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Dg(f,{sourceRoot:p,datasetName:l,filePath:Ji.resolve(d),...m===void 0?{}:{projectId:m}});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)});let c="pipeline name or id; required unless a TTY picker can choose among several",u=t.command("pipeline").description("operate on a live pipeline in the selected project");return u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:l,projectId:d,state:p}=await te(n(),e);_(d,he);let f=await ky({client:l,projectId:d,state:p});e.io.stdout(f.output)}),u.command("run").argument("[name]",c).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Lr).description("start a run on a deployed pipeline").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await qy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},wait:d.wait,...d.timeout===void 0?{}:{timeoutMs:d.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Cc(h.outcome)}),u.command("status").argument("[name]",c).description("report the latest run's state and item counts").action(async(l)=>{let{client:d,state:p,projectId:f}=await te(n(),e);_(f,he);let m=await Uy(d,{projectId:f,state:p,...l===void 0?{}:{pipeline:l},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(m.output),r.value=Cc(m.outcome)}),u.command("runs").argument("[name]",c).option("--limit <n>","how many runs to list",Lr).description("list recent runs").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await My(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.limit===void 0?{}:{limit:d.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cost").argument("[name]",c).option("--item-limit <n>","cap how many items to price",Lr).description("forecast what a run of this pipeline would bill").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await zy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.itemLimit===void 0?{}:{itemLimit:d.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(l)=>{let{client:d}=await te(n(),e),p=await By(d,{runId:l});e.io.stdout(p.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Lr).option("--failed","only report failed items",!1).description("report a run's items").action(async(l,d)=>{let{client:p}=await te(n(),e),f=await Gy(p,{runId:l,failedOnly:d.failed,...d.limit===void 0?{}:{limit:d.limit}});e.io.stdout(f.output),r.value=Cc(f.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e);_(p,he);let f=await Cg(d,{sourceRoot:l,projectId:p});e.io.stdout(f.output)}),{program:t,exitCode:r}}var uT=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},pT=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:r,resolve:i,reject:n}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",l),process.stdin.off("end",c),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
156
+ `)};throw n}}async function Uy(e,t){let r=await zi({client:e,...t}),i=await e.runs.listPage({pipelineId:r.pipelineId,limit:t.limit??10});if(i.runs.length===0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let n=[];for(let s of i.runs){let o=await e.runs.get({runId:s.id});n.push(` ${o.id} ${o.status.padEnd(9)} ${s.createdAt}`)}return{outcome:"reported",output:[`Runs for ${r.name} (${i.pagination.total} total):`,...n].join(`
157
+ `)}}async function By(e,t){let r=await zi({client:e,...t}),n=(await e.runs.listPage({pipelineId:r.pipelineId,limit:1})).runs[0];if(n===void 0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let s=await e.runs.get({runId:n.id}),o=t.itemScanLimit??500,a=new Map,c=0;for await(let l of e.runs.listAllItems({runId:s.id}))if(a.set(l.state.status,(a.get(l.state.status)??0)+1),c+=1,c>=o)break;let u=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([l],[d])=>l.localeCompare(d)).map(([l,d])=>` ${l.padEnd(12)} ${d}`);return{outcome:qy(s),output:[`Latest ${Ly(s)} (started ${n.createdAt}).`,c>=o?`Items (first ${o}):`:"Items:",...u].join(`
158
+ `)}}async function Gy(e,t){let r=await e.runs.cancel({runId:t.runId});return{outcome:"canceled",output:`Requested cancellation of run ${r.id}; it is now ${r.status}.`}}var nT=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
159
+ ${ZO}`;return e.state.error===null?t:`${t}
160
+ ${e.state.error}`};async function Vy(e,t){let r=t.limit??20,i=t.itemScanLimit??Math.max(500,r),n=[],s=0;for await(let c of e.runs.listAllItems({runId:t.runId})){if(s+=1,t.failedOnly!==!0||c.state.status==="failed")n.push(c);if(n.length>=r||s>=i)break}if(n.length===0)return{outcome:"reported",output:t.failedOnly===!0&&s>=i?`No failed items in the first ${i} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[s>=i&&n.length<r?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length} after scanning ${i}, limit ${r}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${n.length}, limit ${r}):`,...n.map(nT)].join(`
161
+ `)}}var Ky=(e)=>{if(typeof e!=="object"||e===null)return!1;if(!("label"in e)||typeof e.label!=="string")return!1;if(!("expectedTotal"in e)||typeof e.expectedTotal!=="string")return!1;if(!("maxTotal"in e)||typeof e.maxTotal!=="string")return!1;if("subLines"in e&&e.subLines!==void 0&&!Array.isArray(e.subLines))return!1;return!0},sT=(e)=>{let t=[0,0,0];for(let r of e)for(let i=0;i<3;i+=1){let n=r[i];t[i]=Math.max(t[i]??0,n?.length??0)}return e.map((r)=>r.map((i,n)=>n===0?i.padEnd(t[0]??0):i.padStart(t[n]??0)).join(" "))},zy=(e,t)=>{let i=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let n of e.subLines??[])if(Ky(n))i.push(...zy(n,t+1));return i},oT=(e)=>{let t=[],r=[];for(let i of e){if(i.kind==="priced"){t.push([i.nodeNameDisplay,i.expectedTotal,i.maxTotal]);for(let n of i.displayBreakdown)if(Ky(n))t.push(...zy(n,1));continue}r.push(i.kind==="validation-errors"?` ${i.nodeNameDisplay} skipped (validation errors)`:` ${i.nodeNameDisplay} not billed`)}return{billed:t,unpriced:r}},aT=(e)=>{let t=[["Total",e.expected,e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,""]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},lT=(e,t)=>{let{billed:r,unpriced:i}=oT(e.nodes),n=aT(e.total),s=sT([["Item","Expected","Maximum"],...r,...n]),o=s.slice(0,1+r.length),a=s.slice(1+r.length),c=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...o];if(r.length===0)c.push(" (no billed nodes)");if(c.push("",...a),i.length>0)c.push("","Not billed",...i);if(e.isInternalPricing===!0)c.push("","Internal-team pricing.");return c.push("",e.disclaimer),c.join(`
162
+ `)};async function Wy(e,t){let r=await zi({client:e,...t}),i=await e.pipelines.estimateCost({pipelineId:r.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:lT(i,r.name)}}var cT=["Credentials resolve in this order, highest first:"," 1. --api-key / --base-url"," 2. POTATO_API_KEY / POTATO_BASE_URL"," 3. the file written by toloka login",`The platform defaults to ${_r}.`].join(`
163
+ `),Lr=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new ft("Expected a positive integer.");return t},Cc=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},Wi=async(e,t)=>{if(e.sourceRoot!==void 0)return Ji.resolve(e.sourceRoot);let r=process.cwd(),i=await Eg(r);if(i===void 0||i===r)return r;return t.stderr(`Using project root ${i} (found from ${r}).`),i},dT=(e)=>e.sourceRoot===void 0?process.cwd():Ji.resolve(e.sourceRoot),Fc=async(e,t)=>{let{found:r,warning:i}=await yi(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(i!==void 0)t.io.stderr(i);return r?.credentials},Hi=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},te=async(e,t)=>{let r=await Wi(e,t.io),i=await $e(r),n=await Fc(e,t),s=rl(e,i,t.environment,n),o=t.injectedClient??it({apiKey:s.apiKey,baseUrl:s.baseUrl});return await Hi(o,t.analytics),{sourceRoot:r,client:o,state:i,stored:n,...s.projectId===void 0?{}:{projectId:s.projectId}}},jc=(e,t,r,i)=>Pi({flags:e,environment:t.environment,stored:r,...i===void 0?{}:{state:i}});function uT(e){let t=new Zt("toloka"),r={value:0},i=!1;t.description("Preview. Build and operate Toloka pipeline projects from TypeScript source. The public API may change.").option("--source-root <directory>","project root; discovered from the working directory when omitted").option("--api-key <key>","API key for this command only").option("--base-url <url>","platform base URL for this command only").option("--project-id <id>","target project; overrides toloka.json").addHelpText("after",`
164
+ ${cT}`).configureOutput({writeOut:(l)=>e.io.stdout(l.replace(/\n$/u,"")),writeErr:(l)=>e.io.stderr(l.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(l)=>{if(i)return;let d=[];for(let m=l;m!==null;m=m.parent)d.push(m.name());if(d.includes("init")||d.includes("help"))return;let p=await Wi(n(),e.io),f=await Th(p).catch(()=>{return});if(f===void 0)return;i=!0,e.io.stderr(f)}),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let l=await Bf({...n().apiKey===void 0?{}:{apiKey:n().apiKey},...n().baseUrl===void 0?{}:{baseUrl:n().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(l.output);try{let d=await jf(e.environment);if(d===void 0)return;let p=e.injectedClient??it(d);await Hi(p,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let l=await Gf(e.environment);e.io.stdout(l.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(l)=>{let d=n(),p=await yi(e.environment,d.apiKey??e.environment.POTATO_API_KEY),f=p.found?.credentials,m=await Wi(d,e.io),h=await $e(m),g=jc(d,e,f,h),y=e.injectedClient,P=await Kf({environment:e.environment,showToken:l.showToken,credentialLookup:p,...d.apiKey===void 0?{}:{flagApiKey:d.apiKey},...d.baseUrl===void 0?{}:{flagBaseUrl:d.baseUrl},...y===void 0?{}:{probe:()=>y},...g===void 0?{}:{project:g}});if(e.io.stdout(P.output),!P.authenticated){r.value=1;return}try{let v=rl(d,h,e.environment,f),w=e.injectedClient??it({apiKey:v.apiKey,baseUrl:v.baseUrl});await Hi(w,e.analytics)}catch{}});let s=t.command("project").description("select and manage the current platform project");s.command("list").description("list remote projects this key can see").action(async()=>{let l=n(),{client:d,stored:p,state:f}=await te(l,e),m=jc(l,e,p,f);await kf({client:d,io:e.io,...m===void 0?{}:{context:m}})}),s.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??it(f.credentials);await Df({environment:e.environment,flags:p,client:m,io:e.io,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d===void 0?{}:{projectId:d}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(l)=>{await Nf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let l=n(),d=await Fc(l,e),p=await Wi(l,e.io),f=await $e(p);if(qf({flags:l,environment:e.environment,stored:d,...f===void 0?{}:{state:f},io:e.io}).project===void 0)r.value=1}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(l)=>{await Lf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??it(f.credentials),h=await Wi(p,e.io);await Mf({environment:e.environment,flags:p,client:m,io:e.io,sourceRoot:h,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d.name===void 0?{}:{name:d.name},...d.teamId===void 0?{}:{teamId:d.teamId}})}),t.command("init").description("initialize this project directory and install agent skills").action(async()=>{let l=n(),d=dT(l),p=await Fc(l,e),f=await $e(d),m=jc(l,e,p,f),h=await Oh(d,m===void 0?{}:{projectId:m.id});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=l??m;_(h,he);let g=await Rg(f,{sourceRoot:p,projectId:h,...d?.force===!0?{force:!0}:{}});e.io.stdout(g.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Cg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Og(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});if(e.io.stdout(f.output),!f.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Fg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(l,d)=>{let{client:p,projectId:f}=await te(n(),e);_(f,he);let m=d.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[d.fromEnv];_(m!==void 0,`Missing secret value. Set ${d.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let h=await Ug(p,{projectId:f,name:l,value:m});e.io.stdout(h.output)}catch{e.io.stderr(`Failed to set secret ${l}.`),r.value=1}});let a=t.command("dataset").description("inspect and move dataset catalog and rows");a.command("list").description("list live datasets in the selected project").action(async()=>{let{client:l,projectId:d}=await te(n(),e);_(d,he);let p=await qg(l,{projectId:d});e.io.stdout(p.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(l)=>{let{sourceRoot:d,client:p,projectId:f}=await te(n(),e),m=await Lg(p,{sourceRoot:d,datasetName:l,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),a.command("load").argument("<name>","dataset name or id").requiredOption("--out <file>","JSONL file to write").option("--limit <n>","how many rows to keep after download",Lr).option("--timeout <ms>","how long to wait for the export",Lr).description("download live dataset rows into a JSONL file").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Mg(f,{sourceRoot:p,datasetName:l,outPath:Ji.resolve(d.out),...m===void 0?{}:{projectId:m},...d.limit===void 0?{}:{limit:d.limit},...d.timeout===void 0?{}:{timeoutMs:d.timeout}});e.io.stdout(h.output)}),a.command("upload").argument("<name>","dataset name or id").argument("<file>","JSONL file, one JSON object per line").description("append rows to a dataset").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Ng(f,{sourceRoot:p,datasetName:l,filePath:Ji.resolve(d),...m===void 0?{}:{projectId:m}});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)});let c="pipeline name or id; required unless a TTY picker can choose among several",u=t.command("pipeline").description("operate on a live pipeline in the selected project");return u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:l,projectId:d,state:p}=await te(n(),e);_(d,he);let f=await Dy({client:l,projectId:d,state:p});e.io.stdout(f.output)}),u.command("run").argument("[name]",c).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Lr).description("start a run on a deployed pipeline").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await My(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},wait:d.wait,...d.timeout===void 0?{}:{timeoutMs:d.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Cc(h.outcome)}),u.command("status").argument("[name]",c).description("report the latest run's state and item counts").action(async(l)=>{let{client:d,state:p,projectId:f}=await te(n(),e);_(f,he);let m=await By(d,{projectId:f,state:p,...l===void 0?{}:{pipeline:l},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(m.output),r.value=Cc(m.outcome)}),u.command("runs").argument("[name]",c).option("--limit <n>","how many runs to list",Lr).description("list recent runs").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await Uy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.limit===void 0?{}:{limit:d.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cost").argument("[name]",c).option("--item-limit <n>","cap how many items to price",Lr).description("forecast what a run of this pipeline would bill").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await Wy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.itemLimit===void 0?{}:{itemLimit:d.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(l)=>{let{client:d}=await te(n(),e),p=await Gy(d,{runId:l});e.io.stdout(p.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Lr).option("--failed","only report failed items",!1).description("report a run's items").action(async(l,d)=>{let{client:p}=await te(n(),e),f=await Vy(p,{runId:l,failedOnly:d.failed,...d.limit===void 0?{}:{limit:d.limit}});e.io.stdout(f.output),r.value=Cc(f.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e);_(p,he);let f=await jg(d,{sourceRoot:l,projectId:p});e.io.stdout(f.output)}),{program:t,exitCode:r}}var pT=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},fT=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:r,resolve:i,reject:n}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",l),process.stdin.off("end",c),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
165
165
  `)},c=()=>{a(),n(Error("Standard input closed before an API key was entered."))},u=(d)=>{a(),n(d)},l=(d)=>{for(let p of d){if(p==="\r"||p===`
166
- `){a(),i(s);return}if(p==="\x03"||p==="\x04"){a(),n(Error(p==="\x03"?"Canceled.":"Standard input closed before an API key was entered."));return}if(p==="\x7F"||p==="\b"){if(s.length>0)s=s.slice(0,-1),process.stdout.write("\b \b");continue}s+=p,process.stdout.write("*")}};process.stdin.on("data",l),process.stdin.once("end",c),process.stdin.once("error",u);try{return await r}finally{o()}},fT=async(e,t={})=>{if(t.mask===!0)return pT(e);let r=Wy.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await r.question(e)}finally{r.close()}},mT=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:uT,...process.stdin.isTTY?{prompt:fT,select:Ay}:{}}),hT=(e)=>{if(e instanceof re){let t=typeof e.body==="string"?e.body:e.body===void 0?void 0:JSON.stringify(e.body);return t===void 0||t.length===0?e.message:`${e.message}
167
- ${t}`}return e instanceof Error?e.message:String(e)},gT=async(e,t,r,i)=>{try{await e.parseAsync([...r],{from:"user"});let n=t.value;return{code:n,outcome:n===0?"succeeded":"failed"}}catch(n){if(n instanceof it){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(hT(n)),{code:1,outcome:"failed",error:n}}};async function Hy(e,t=process.env,r=mT(),i,n=kh({environment:t})){let{program:s,exitCode:o}=dT({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),c=await gT(s,o,e,r);try{n.captureCommand({command:Ah(e),durationMs:Date.now()-a,exitCode:c.code,outcome:c.outcome,...c.error===void 0?{}:{error:c.error}}),await n.shutdown()}catch{}return c.code}Hy(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
166
+ `){a(),i(s);return}if(p==="\x03"||p==="\x04"){a(),n(Error(p==="\x03"?"Canceled.":"Standard input closed before an API key was entered."));return}if(p==="\x7F"||p==="\b"){if(s.length>0)s=s.slice(0,-1),process.stdout.write("\b \b");continue}s+=p,process.stdout.write("*")}};process.stdin.on("data",l),process.stdin.once("end",c),process.stdin.once("error",u);try{return await r}finally{o()}},mT=async(e,t={})=>{if(t.mask===!0)return fT(e);let r=Hy.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await r.question(e)}finally{r.close()}},hT=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:pT,...process.stdin.isTTY?{prompt:mT,select:ky}:{}}),gT=(e)=>{if(e instanceof re){let t=typeof e.body==="string"?e.body:e.body===void 0?void 0:JSON.stringify(e.body);return t===void 0||t.length===0?e.message:`${e.message}
167
+ ${t}`}return e instanceof Error?e.message:String(e)},yT=async(e,t,r,i)=>{try{await e.parseAsync([...r],{from:"user"});let n=t.value;return{code:n,outcome:n===0?"succeeded":"failed"}}catch(n){if(n instanceof rt){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(gT(n)),{code:1,outcome:"failed",error:n}}};async function Jy(e,t=process.env,r=hT(),i,n=Dh({environment:t})){let{program:s,exitCode:o}=uT({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),c=await yT(s,o,e,r);try{n.captureCommand({command:kh(e),durationMs:Date.now()-a,exitCode:c.code,outcome:c.outcome,...c.error===void 0?{}:{error:c.error}}),await n.shutdown()}catch{}return c.code}Jy(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})