@toloka-platform/sdk 0.1.0-preview.5 → 0.1.0-preview.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/cli/toloka.js +121 -120
  2. package/dist/cli/toloka.js.jsc +0 -0
  3. package/dist/cli/toloka.js.jsc.sha256 +1 -1
  4. package/dist/cli/toloka.js.sha256 +1 -1
  5. package/docs/cli.md +26 -1
  6. package/docs/datasets.md +8 -9
  7. package/docs/limitations.md +5 -8
  8. package/docs/troubleshooting.md +0 -11
  9. package/openapi/gen/api.ts +779 -895
  10. package/openapi/gen/models/baseModel.ts +9 -0
  11. package/openapi/gen/models/baseModelId.ts +2 -0
  12. package/openapi/gen/models/baseModelIdProperty.ts +2 -0
  13. package/openapi/gen/models/createProjectModelBody.ts +8 -0
  14. package/openapi/gen/models/createProjectModelBodyDescription.ts +2 -0
  15. package/openapi/gen/models/generationNodeSettingsAudienceAndPricingOneOfOneone.ts +1 -0
  16. package/openapi/gen/models/index.ts +16 -0
  17. package/openapi/gen/models/listBaseModels200.ts +5 -0
  18. package/openapi/gen/models/listModelVersions200.ts +7 -0
  19. package/openapi/gen/models/listModelVersionsParams.ts +5 -0
  20. package/openapi/gen/models/listProjectModels200.ts +7 -0
  21. package/openapi/gen/models/listProjectModelsParams.ts +5 -0
  22. package/openapi/gen/models/model.ts +16 -0
  23. package/openapi/gen/models/modelArchivedAt.ts +2 -0
  24. package/openapi/gen/models/modelDescription.ts +2 -0
  25. package/openapi/gen/models/modelId.ts +2 -0
  26. package/openapi/gen/models/modelVersion.ts +9 -0
  27. package/openapi/gen/models/modelVersionId.ts +2 -0
  28. package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneone.ts +1 -0
  29. package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneone.ts +1 -0
  30. package/package.json +1 -1
  31. package/skills/catalog.json +4 -4
  32. package/skills/toloka-build/SKILL.md +1 -1
  33. package/skills/toloka-build/references/workflow-and-cli.md +12 -1
  34. package/skills/toloka-report-issue/references/report-template.md +1 -1
  35. package/src/cli/data.ts +148 -25
  36. package/src/cli/models.ts +188 -0
  37. package/src/cli/program.ts +99 -1
  38. package/src/client.ts +109 -35
  39. package/src/errors.ts +25 -10
  40. package/src/transport.ts +16 -13
@@ -1,172 +1,173 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun @bytecode @bun-cjs
3
- (function(exports, require, module, __filename, __dirname) {var F_=Object.create;var{getPrototypeOf:T_,defineProperty:Vs,getOwnPropertyNames:k_}=Object;var A_=Object.prototype.hasOwnProperty;function D_(e){return this[e]}var N_,L_,Ce=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?N_??=new WeakMap:L_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?F_(T_(e)):{};let o=t||!e||!e.__esModule?Vs(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of k_(e))if(!A_.call(o,a))Vs(o,a,{get:D_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var q_=(e)=>e;function M_(e,t){this[e]=q_.bind(null,t)}var U_=(e,t)=>{for(var r in t)Vs(e,r,{get:t[r],enumerable:!0,configurable:!0,set:M_.bind(t,r)})};var ei=P(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 cn{}M._CodeOrName=cn;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class ar extends cn{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=ar;class Le extends cn{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 ar)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=Le;M.nil=new Le("");function kd(e,...t){let r=[e[0]],i=0;while(i<t.length)lo(r,t[i]),r.push(e[++i]);return new Le(r)}M._=kd;var ao=new Le("+");function Ad(e,...t){let r=[Zr(e[0])],i=0;while(i<t.length)r.push(ao),lo(r,t[i]),r.push(ao,Zr(e[++i]));return Yv(r),new Le(r)}M.str=Ad;function lo(e,t){if(t instanceof Le)e.push(...t._items);else if(t instanceof ar)e.push(t);else e.push(ew(t))}M.addCodeArg=lo;function Yv(e){let t=1;while(t<e.length-1){if(e[t]===ao){let r=Xv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Xv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof ar||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 ar))return`"${e}${t.slice(1)}`;return}function Zv(e,t){return t.emptyStr()?e:e.emptyStr()?t:Ad`${e}${t}`}M.strConcat=Zv;function ew(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zr(Array.isArray(e)?e.join(","):e)}function tw(e){return new Le(Zr(e))}M.stringify=tw;function Zr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Zr;function rw(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new Le(`.${e}`):kd`[${e}]`}M.getProperty=rw;function iw(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new Le(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=iw;function nw(e){return new Le(e.toString())}M.regexpCode=nw});var po=P(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var be=ei();class Dd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var dn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(dn||(Pe.UsedValueState=dn={}));Pe.varKinds={const:new be.Name("const"),let:new be.Name("let"),var:new be.Name("var")};class co{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof be.Name?e:this.name(e)}name(e){return new be.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}}}Pe.Scope=co;class uo extends be.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=be._`.${new be.Name(t)}[${r}]`}}Pe.ValueScopeName=uo;var sw=be._`\n`;class Nd extends co{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sw:be.nil}}get(){return this._scope}name(e){return new uo(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]=[]),d=a.length;return a[d]=t.ref,i.setValue(t,{property:n,itemIndex:d}),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 be._`${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=be.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((d)=>{if(a.has(d))return;a.set(d,dn.Started);let u=t(d);if(u){let l=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;n=be._`${n}${l} ${d} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(d))n=be._`${n}${u}${this.opts._n}`;else throw new Dd(d);a.set(d,dn.Completed)})}return n}}Pe.ValueScope=Nd});var j=P(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.or=k.and=k.not=k.CodeGen=k.operators=k.varKinds=k.ValueScopeName=k.ValueScope=k.Scope=k.Name=k.regexpCode=k.stringify=k.getProperty=k.nil=k.strConcat=k.str=k._=void 0;var N=ei(),qe=po(),Pt=ei();Object.defineProperty(k,"_",{enumerable:!0,get:function(){return Pt._}});Object.defineProperty(k,"str",{enumerable:!0,get:function(){return Pt.str}});Object.defineProperty(k,"strConcat",{enumerable:!0,get:function(){return Pt.strConcat}});Object.defineProperty(k,"nil",{enumerable:!0,get:function(){return Pt.nil}});Object.defineProperty(k,"getProperty",{enumerable:!0,get:function(){return Pt.getProperty}});Object.defineProperty(k,"stringify",{enumerable:!0,get:function(){return Pt.stringify}});Object.defineProperty(k,"regexpCode",{enumerable:!0,get:function(){return Pt.regexpCode}});Object.defineProperty(k,"Name",{enumerable:!0,get:function(){return Pt.Name}});var gn=po();Object.defineProperty(k,"Scope",{enumerable:!0,get:function(){return gn.Scope}});Object.defineProperty(k,"ValueScope",{enumerable:!0,get:function(){return gn.ValueScope}});Object.defineProperty(k,"ValueScopeName",{enumerable:!0,get:function(){return gn.ValueScopeName}});Object.defineProperty(k,"varKinds",{enumerable:!0,get:function(){return gn.varKinds}});k.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 vt{optimizeNodes(){return this}optimizeNames(e,t){return this}}class Ld extends vt{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?qe.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=cr(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class ho extends vt{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=cr(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return hn(e,this.rhs)}}class qd extends ho{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Md extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Ud extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Bd extends vt{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class Gd extends vt{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=cr(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class yn extends vt{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;ow(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>At(e,t.names),{})}}class wt extends yn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Vd extends yn{}class ti extends wt{}ti.kind="else";class dt extends wt{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 ti(r):r}if(t){if(e===!1)return t instanceof dt?t:t.nodes;if(this.nodes.length)return this;return new dt(Jd(e),t instanceof dt?[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=cr(this.condition,e,t),this}get names(){let e=super.names;if(hn(e,this.condition),this.else)At(e,this.else.names);return e}}dt.kind="if";class lr extends wt{}lr.kind="for";class Kd extends lr{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=cr(this.iteration,e,t),this}get names(){return At(super.names,this.iteration.names)}}class zd extends lr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?qe.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=hn(super.names,this.from);return hn(e,this.to)}}class fo extends lr{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=cr(this.iterable,e,t),this}get names(){return At(super.names,this.iterable.names)}}class un extends wt{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)}}un.kind="func";class pn extends yn{render(e){return"return "+super.render(e)}}pn.kind="return";class Wd extends wt{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)At(e,this.catch.names);if(this.finally)At(e,this.finally.names);return e}}class fn extends wt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}fn.kind="catch";class mn extends wt{render(e){return"finally"+super.render(e)}}mn.kind="finally";class Hd{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
4
- `:""},this._extScope=e,this._scope=new qe.Scope({parent:e}),this._nodes=[new Vd]}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 Ld(e,n,r)),n}const(e,t,r){return this._def(qe.varKinds.const,e,t,r)}let(e,t,r){return this._def(qe.varKinds.let,e,t,r)}var(e,t,r){return this._def(qe.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new ho(e,t,r))}add(e,t){return this._leafNode(new qd(e,k.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new Gd(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 dt(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 dt(e))}else(){return this._elseNode(new ti)}endIf(){return this._endBlockNode(dt,ti)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Kd(e),t)}forRange(e,t,r,i,n=this.opts.es5?qe.varKinds.var:qe.varKinds.let){let s=this._scope.toName(e);return this._for(new zd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=qe.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 fo("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?qe.varKinds.var:qe.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 fo("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(lr)}label(e){return this._leafNode(new Md(e))}break(e){return this._leafNode(new Ud(e))}return(e){let t=new pn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(pn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Wd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new fn(n),t(n)}if(r)this._currNode=i.finally=new mn,this.code(r);return this._endBlockNode(fn,mn)}throw(e){return this._leafNode(new Bd(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 un(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(un)}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 dt))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}}k.CodeGen=Hd;function At(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function hn(e,t){return t instanceof N._CodeOrName?At(e,t.names):e}function cr(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 ow(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Jd(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${mo(e)}`}k.not=Jd;var aw=Qd(k.operators.AND);function lw(...e){return e.reduce(aw)}k.and=lw;var cw=Qd(k.operators.OR);function dw(...e){return e.reduce(cw)}k.or=dw;function Qd(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${mo(t)} ${e} ${mo(r)}`}function mo(e){return e instanceof N.Name?e:N._`(${e})`}});var D=P(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.checkStrictMode=A.getErrorPath=A.Type=A.useFunc=A.setEvaluated=A.evaluatedPropsToName=A.mergeEvaluated=A.eachItem=A.unescapeJsonPointer=A.escapeJsonPointer=A.escapeFragment=A.unescapeFragment=A.schemaRefOrVal=A.schemaHasRulesButRef=A.schemaHasRules=A.checkUnknownRules=A.alwaysValidSchema=A.toHash=void 0;var G=j(),uw=ei();function pw(e){let t={};for(let r of e)t[r]=!0;return t}A.toHash=pw;function fw(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Zd(e,t),!eu(t,e.self.RULES.all)}A.alwaysValidSchema=fw;function Zd(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])iu(e,`unknown keyword: "${s}"`)}A.checkUnknownRules=Zd;function eu(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}A.schemaHasRules=eu;function mw(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}A.schemaHasRulesButRef=mw;function hw({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)}`}A.schemaRefOrVal=hw;function gw(e){return tu(decodeURIComponent(e))}A.unescapeFragment=gw;function yw(e){return encodeURIComponent(yo(e))}A.escapeFragment=yw;function yo(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}A.escapeJsonPointer=yo;function tu(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}A.unescapeJsonPointer=tu;function _w(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}A.eachItem=_w;function Yd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let d=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&&!(d instanceof G.Name)?i(n,d):d}}A.mergeEvaluated={props:Yd({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} || {}`),_o(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:ru}),items:Yd({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 ru(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)_o(e,r,t);return r}A.evaluatedPropsToName=ru;function _o(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}A.setEvaluated=_o;var Xd={};function bw(e,t){return e.scopeValue("func",{ref:t,code:Xd[t.code]||(Xd[t.code]=new uw._Code(t.code))})}A.useFunc=bw;var go;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(go||(A.Type=go={}));function Pw(e,t,r){if(e instanceof G.Name){let i=t===go.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():"/"+yo(e)}A.getErrorPath=Pw;function iu(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}A.checkStrictMode=iu});var Oe=P(function(bo){Object.defineProperty(bo,"__esModule",{value:!0});var ae=j(),vw={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")};bo.default=vw});var ri=P(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=j(),_n=D(),me=Oe();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 ww(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,d=ou(e,t,r);if(i!==null&&i!==void 0?i:o||a)nu(s,d);else su(n,L._`[${d}]`)}le.reportError=ww;function $w(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=ou(e,t,r);if(nu(n,a),!(s||o))su(i,me.default.vErrors)}le.reportExtraError=$w;function Ew(e,t){e.assign(me.default.errors,t),e.if(L._`${me.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${me.default.vErrors}.length`,t),()=>e.assign(me.default.vErrors,null)))}le.resetErrorsCount=Ew;function Iw({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,me.default.errors,(a)=>{if(e.const(o,L._`${me.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(me.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=Iw;function nu(e,t){let r=e.const("err",t);e.if(L._`${me.default.vErrors} === null`,()=>e.assign(me.default.vErrors,L._`[${r}]`),L._`${me.default.vErrors}.push(${r})`),e.code(L._`${me.default.errors}++`)}function su(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 Dt={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 ou(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Sw(e,t,r)}function Sw(e,t,r={}){let{gen:i,it:n}=e,s=[xw(n,r),Rw(e,r)];return Cw(e,t,s),i.object(...s)}function xw({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,_n.getErrorPath)(t,_n.Type.Str)}`:e;return[me.default.instancePath,(0,L.strConcat)(me.default.instancePath,r)]}function Rw({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,_n.getErrorPath)(r,_n.Type.Str)}`;return[Dt.schemaPath,n]}function Cw(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:d,propertyName:u,topSchemaRef:l,schemaPath:c}=a;if(i.push([Dt.keyword,n],[Dt.params,typeof t=="function"?t(e):t||L._`{}`]),d.messages)i.push([Dt.message,typeof r=="function"?r(e):r]);if(d.verbose)i.push([Dt.schema,o],[Dt.parentSchema,L._`${l}${c}`],[me.default.data,s]);if(u)i.push([Dt.propertyName,u])}});var lu=P(function(dr){Object.defineProperty(dr,"__esModule",{value:!0});dr.boolOrEmptySchema=dr.topBoolOrEmptySchema=void 0;var Ow=ri(),jw=j(),Fw=Oe(),Tw={message:"boolean schema is false"};function kw(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)au(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Fw.default.data);else t.assign(jw._`${i}.errors`,null),t.return(!0)}dr.topBoolOrEmptySchema=kw;function Aw(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),au(e);else r.var(t,!0)}dr.boolOrEmptySchema=Aw;function au(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,Ow.reportError)(n,Tw,void 0,t)}});var Po=P(function(ur){Object.defineProperty(ur,"__esModule",{value:!0});ur.getRules=ur.isJSONType=void 0;var Dw=["string","number","integer","boolean","null","object","array"],Nw=new Set(Dw);function Lw(e){return typeof e=="string"&&Nw.has(e)}ur.isJSONType=Lw;function qw(){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:{}}}ur.getRules=qw});var vo=P(function($t){Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function Mw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&cu(e,i)}$t.schemaHasRulesForType=Mw;function cu(e,t){return t.rules.some((r)=>du(e,r))}$t.shouldUseGroup=cu;function du(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=du});var ii=P(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 Uw=Po(),Bw=vo(),Gw=ri(),F=j(),uu=D(),pr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(pr||(ce.DataType=pr={}));function Vw(e){let t=pu(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=Vw;function pu(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Uw.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=pu;function Kw(e,t){let{gen:r,data:i,opts:n}=e,s=zw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,Bw.schemaHasRulesForType)(e,t[0]));if(o){let a=$o(t,i,n.strictNumbers,pr.Wrong);r.if(a,()=>{if(s.length)Ww(e,t,s);else Eo(e)})}return o}ce.coerceAndCheckDataType=Kw;var fu=new Set(["string","number","integer","boolean","null"]);function zw(e,t){return t?e.filter((r)=>fu.has(r)||t==="array"&&r==="array"):[]}function Ww(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",F._`typeof ${n}`),a=i.let("coerced",F._`undefined`);if(s.coerceTypes==="array")i.if(F._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,F._`${n}[0]`).assign(o,F._`typeof ${n}`).if($o(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(F._`${a} !== undefined`);for(let u of r)if(fu.has(u)||u==="array"&&s.coerceTypes==="array")d(u);i.else(),Eo(e),i.endIf(),i.if(F._`${a} !== undefined`,()=>{i.assign(n,a),Hw(e,a)});function d(u){switch(u){case"string":i.elseIf(F._`${o} == "number" || ${o} == "boolean"`).assign(a,F._`"" + ${n}`).elseIf(F._`${n} === null`).assign(a,F._`""`);return;case"number":i.elseIf(F._`${o} == "boolean" || ${n} === null
5
- || (${o} == "string" && ${n} && ${n} == +${n})`).assign(a,F._`+${n}`);return;case"integer":i.elseIf(F._`${o} === "boolean" || ${n} === null
6
- || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(a,F._`+${n}`);return;case"boolean":i.elseIf(F._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(a,!1).elseIf(F._`${n} === "true" || ${n} === 1`).assign(a,!0);return;case"null":i.elseIf(F._`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(a,null);return;case"array":i.elseIf(F._`${o} === "string" || ${o} === "number"
7
- || ${o} === "boolean" || ${n} === null`).assign(a,F._`[${n}]`)}}}function Hw({gen:e,parentData:t,parentDataProperty:r},i){e.if(F._`${t} !== undefined`,()=>e.assign(F._`${t}[${r}]`,i))}function wo(e,t,r,i=pr.Correct){let n=i===pr.Correct?F.operators.EQ:F.operators.NEQ,s;switch(e){case"null":return F._`${t} ${n} null`;case"array":s=F._`Array.isArray(${t})`;break;case"object":s=F._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(F._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return F._`typeof ${t} ${n} ${e}`}return i===pr.Correct?s:(0,F.not)(s);function o(a=F.nil){return(0,F.and)(F._`typeof ${t} == "number"`,a,r?F._`isFinite(${t})`:F.nil)}}ce.checkDataType=wo;function $o(e,t,r,i){if(e.length===1)return wo(e[0],t,r,i);let n,s=(0,uu.toHash)(e);if(s.array&&s.object){let o=F._`typeof ${t} != "object"`;n=s.null?o:F._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=F.nil;if(s.number)delete s.integer;for(let o in s)n=(0,F.and)(n,wo(o,t,r,i));return n}ce.checkDataTypes=$o;var Jw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?F._`{type: ${e}}`:F._`{type: ${t}}`};function Eo(e){let t=Qw(e);(0,Gw.reportError)(t,Jw)}ce.reportTypeError=Eo;function Qw(e){let{gen:t,data:r,schema:i}=e,n=(0,uu.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var hu=P(function(bn){Object.defineProperty(bn,"__esModule",{value:!0});bn.assignDefaults=void 0;var fr=j(),Yw=D();function Xw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)mu(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>mu(e,s,n.default))}bn.assignDefaults=Xw;function mu(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=fr._`${s}${(0,fr.getProperty)(t)}`;if(n){(0,Yw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let d=fr._`${a} === undefined`;if(o.useDefaults==="empty")d=fr._`${d} || ${a} === null || ${a} === ""`;i.if(d,fr._`${a} = ${(0,fr.stringify)(r)}`)}});var je=P(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=j(),Io=D(),Et=Oe(),Zw=D();function e$(e,t){let{gen:r,data:i,it:n}=e;r.if(xo(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=e$;function t$({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(xo(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=t$;function r$(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=r$;function gu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=gu;function So(e,t,r){return K._`${gu(e)}.call(${t}, ${r})`}B.isOwnProperty=So;function i$(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${So(e,t,r)}`:n}B.propertyInData=i$;function xo(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(So(e,t,r))):n}B.noPropertyInData=xo;function yu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=yu;function n$(e,t){return yu(t).filter((r)=>!(0,Io.alwaysValidSchema)(e,t[r]))}B.schemaProperties=n$;function s$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,d,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,c=[[Et.default.instancePath,(0,K.strConcat)(Et.default.instancePath,s)],[Et.default.parentData,o.parentData],[Et.default.parentDataProperty,o.parentDataProperty],[Et.default.rootData,Et.default.rootData]];if(o.opts.dynamicRef)c.push([Et.default.dynamicAnchors,Et.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...c)}`;return d!==K.nil?K._`${a}.call(${d}, ${p})`:K._`${a}(${p})`}B.callValidateCode=s$;var o$=K._`new RegExp`;function a$({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"?o$:(0,Zw.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=a$;function l$(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 d=t.const("len",K._`${r}.length`);t.forRange("i",0,d,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:Io.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=l$;function c$(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((d)=>(0,Io.alwaysValidSchema)(n,d))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((d,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=c$});var Pu=P(function(Je){Object.defineProperty(Je,"__esModule",{value:!0});Je.validateKeywordUsage=Je.validSchemaType=Je.funcKeywordCode=Je.macroKeywordCode=void 0;var he=j(),Nt=Oe(),d$=je(),u$=ri();function p$(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),d=bu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:he.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:d,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Je.macroKeywordCode=p$;function f$(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:d}=e;h$(d,t);let u=!a&&t.compile?t.compile.call(d.self,s,o,d):t.validate,l=bu(i,n,u),c=i.let("valid");e.block$data(c,p),e.ok((r=t.valid)!==null&&r!==void 0?r:c);function p(){if(t.errors===!1){if(h(),t.modifying)_u(e);g(()=>e.error())}else{let _=t.async?f():m();if(t.modifying)_u(e);g(()=>m$(e,_))}}function f(){let _=i.let("ruleErrs",null);return i.try(()=>h(he._`await `),(b)=>i.assign(c,!1).if(he._`${b} instanceof ${d.ValidationError}`,()=>i.assign(_,he._`${b}.errors`),()=>i.throw(b))),_}function m(){let _=he._`${l}.errors`;return i.assign(_,null),h(he.nil),_}function h(_=t.async?he._`await `:he.nil){let b=d.opts.passContext?Nt.default.this:Nt.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(c,he._`${_}${(0,d$.callValidateCode)(e,l,b,v)}`,t.modifying)}function g(_){var b;i.if((0,he.not)((b=t.valid)!==null&&b!==void 0?b:c),_)}}Je.funcKeywordCode=f$;function _u(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,he._`${i.parentData}[${i.parentDataProperty}]`))}function m$(e,t){let{gen:r}=e;r.if(he._`Array.isArray(${t})`,()=>{r.assign(Nt.default.vErrors,he._`${Nt.default.vErrors} === null ? ${t} : ${Nt.default.vErrors}.concat(${t})`).assign(Nt.default.errors,he._`${Nt.default.vErrors}.length`),(0,u$.extendErrors)(e)},()=>e.error())}function h$({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function bu(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,he.stringify)(r)})}function g$(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")}Je.validSchemaType=g$;function y$({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 d=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw Error(d)}}}Je.validateKeywordUsage=y$});var wu=P(function(It){Object.defineProperty(It,"__esModule",{value:!0});It.extendSubschemaMode=It.extendSubschemaData=It.getSubschema=void 0;var Qe=j(),vu=D();function _$(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:Qe._`${e.schemaPath}${(0,Qe.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Qe._`${e.schemaPath}${(0,Qe.getProperty)(t)}${(0,Qe.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,vu.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')}It.getSubschema=_$;function b$(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:c}=t,p=a.let("data",Qe._`${t.data}${(0,Qe.getProperty)(r)}`,!0);d(p),e.errorPath=Qe.str`${u}${(0,vu.getErrorPath)(r,i,c.jsPropertySyntax)}`,e.parentDataProperty=Qe._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Qe.Name?n:a.let("data",n,!0);if(d(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function d(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}It.extendSubschemaData=b$;function P$(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}It.extendSubschemaMode=P$});var Ro=P(function(lA,$u){$u.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 Iu=P(function(cA,Eu){var St=Eu.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)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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,d,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,d,u);for(var l in i){var c=i[l];if(Array.isArray(c)){if(l in St.arrayKeywords)for(var p=0;p<c.length;p++)Pn(e,t,r,c[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in St.propsKeywords){if(c&&typeof c=="object")for(var f in c)Pn(e,t,r,c[f],n+"/"+l+"/"+v$(f),s,n,l,i,f)}else if(l in St.keywords||e.allKeys&&!(l in St.skipKeywords))Pn(e,t,r,c,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,d,u)}}function v$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ni=P(function(ve){Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var w$=D(),$$=Ro(),E$=Iu(),I$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function S$(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!Co(e);if(!t)return!1;return Su(e)<=t}ve.inlineRef=S$;var x$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Co(e){for(let t in e){if(x$.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Co))return!0;if(typeof r=="object"&&Co(r))return!0}return!1}function Su(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,I$.has(r))continue;if(typeof e[r]=="object")(0,w$.eachItem)(e[r],(i)=>t+=Su(i));if(t===1/0)return 1/0}return t}function xu(e,t="",r){if(r!==!1)t=mr(t);let i=e.parse(t);return Ru(e,i)}ve.getFullPath=xu;function Ru(e,t){return e.serialize(t).split("#")[0]+"#"}ve._getFullPath=Ru;var R$=/#\/?$/;function mr(e){return e?e.replace(R$,""):""}ve.normalizeId=mr;function C$(e,t,r){return r=mr(r),e.resolve(t,r)}ve.resolveUrl=C$;var O$=/^[a-z_][-a-z0-9._]*$/i;function j$(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=mr(e[r]||t),s={"":n},o=xu(i,n,!1),a={},d=new Set;return E$(e,{allKeys:!0},(c,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof c[r]=="string")g=_.call(this,c[r]);b.call(this,c.$anchor),b.call(this,c.$dynamicAnchor),s[p]=g;function _(v){let w=this.opts.uriResolver.resolve;if(v=mr(g?w(g,v):v),d.has(v))throw l(v);d.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(c,I.schema,v);else if(v!==mr(h))if(v[0]==="#")u(c,a[v],v),a[v]=c;else this.refs[v]=h;return v}function b(v){if(typeof v=="string"){if(!O$.test(v))throw Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(c,p,f){if(p!==void 0&&!$$(c,p))throw l(f)}function l(c){return Error(`reference "${c}" resolves to more than one schema`)}}ve.getSchemaRefs=j$});var hr=P(function(xt){Object.defineProperty(xt,"__esModule",{value:!0});xt.getData=xt.KeywordCxt=xt.validateFunctionCode=void 0;var Tu=lu(),Cu=ii(),jo=vo(),vn=ii(),F$=hu(),oi=Pu(),Oo=wu(),S=j(),O=Oe(),T$=ni(),ut=D(),si=ri();function k$(e){if(Du(e)){if(Nu(e),Au(e)){N$(e);return}}ku(e,()=>(0,Tu.topBoolOrEmptySchema)(e))}xt.validateFunctionCode=k$;function ku({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${O.default.data}, ${O.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${Ou(r,n)}`),D$(e,n),e.code(s)});else e.func(t,S._`${O.default.data}, ${A$(n)}`,i.$async,()=>e.code(Ou(r,n)).code(s))}function A$(e){return S._`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${e.dynamicRef?S._`, ${O.default.dynamicAnchors}={}`:S.nil}}={}`}function D$(e,t){e.if(O.default.valCxt,()=>{if(e.var(O.default.instancePath,S._`${O.default.valCxt}.${O.default.instancePath}`),e.var(O.default.parentData,S._`${O.default.valCxt}.${O.default.parentData}`),e.var(O.default.parentDataProperty,S._`${O.default.valCxt}.${O.default.parentDataProperty}`),e.var(O.default.rootData,S._`${O.default.valCxt}.${O.default.rootData}`),t.dynamicRef)e.var(O.default.dynamicAnchors,S._`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{if(e.var(O.default.instancePath,S._`""`),e.var(O.default.parentData,S._`undefined`),e.var(O.default.parentDataProperty,S._`undefined`),e.var(O.default.rootData,O.default.data),t.dynamicRef)e.var(O.default.dynamicAnchors,S._`{}`)})}function N$(e){let{schema:t,opts:r,gen:i}=e;ku(e,()=>{if(r.$comment&&t.$comment)qu(e);if(B$(e),i.let(O.default.vErrors,null),i.let(O.default.errors,0),r.unevaluated)L$(e);Lu(e),K$(e)});return}function L$(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 Ou(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function q$(e,t){if(Du(e)){if(Nu(e),Au(e)){M$(e,t);return}}(0,Tu.boolOrEmptySchema)(e,t)}function Au({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 Du(e){return typeof e.schema!="boolean"}function M$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)qu(e);G$(e),V$(e);let s=i.const("_errs",O.default.errors);Lu(e,s),i.var(t,S._`${s} === ${O.default.errors}`)}function Nu(e){(0,ut.checkUnknownRules)(e),U$(e)}function Lu(e,t){if(e.opts.jtd)return ju(e,[],!1,t);let r=(0,Cu.getSchemaTypes)(e.schema),i=(0,Cu.coerceAndCheckDataType)(e,r);ju(e,r,!i,t)}function U$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,ut.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function B$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,ut.checkStrictMode)(e,"default is ignored in the schema root")}function G$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,T$.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function V$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function qu({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${O.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._`${O.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function K$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${O.default.errors} === 0`,()=>t.return(O.default.data),()=>t.throw(S._`new ${n}(${O.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,O.default.vErrors),s.unevaluated)z$(e);t.return(S._`${O.default.errors} === 0`)}}function z$({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 ju(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:d,self:u}=e,{RULES:l}=u;if(s.$ref&&(d.ignoreKeywordsWithRef||!(0,ut.schemaHasRulesButRef)(s,l))){n.block(()=>Uu(e,"$ref",l.all.$ref.definition));return}if(!d.jtd)W$(e,t);n.block(()=>{for(let p of l.rules)c(p);c(l.post)});function c(p){if(!(0,jo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,vn.checkDataType)(p.type,o,d.strictNumbers)),Fu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,vn.reportTypeError)(e);n.endIf()}else Fu(e,p);if(!a)n.if(S._`${O.default.errors} === ${i||0}`)}}function Fu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,F$.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,jo.shouldUseRule)(i,s))Uu(e,s.keyword,s.definition,t.type)})}function W$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(H$(e,t),!e.opts.allowUnionTypes)J$(e,t);Q$(e,e.dataTypes)}function H$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Mu(e.dataTypes,r))Fo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),X$(e,t)}function J$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Fo(e,"use allowUnionTypes to allow union type keyword")}function Q$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,jo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>Y$(t,o)))Fo(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function Y$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Mu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function X$(e,t){let r=[];for(let i of e.dataTypes)if(Mu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function Fo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,ut.checkStrictMode)(e,t,e.opts.strictTypes)}class To{constructor(e,t,r){if((0,oi.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,ut.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",Bu(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,oi.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",O.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?si.reportExtraError:si.reportError)(this,this.def.error,t)}$dataError(){(0,si.reportError)(this,this.def.$dataError||si.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,si.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,vn.checkDataTypes)(a,t,n.opts.strictNumbers,vn.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,Oo.getSubschema)(this.it,e);(0,Oo.extendSubschemaData)(r,this.it,e),(0,Oo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return q$(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=ut.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=ut.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}}xt.KeywordCxt=To;function Uu(e,t,r,i){let n=new To(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,oi.funcKeywordCode)(n,r);else if("macro"in r)(0,oi.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,oi.funcKeywordCode)(n,r)}var Z$=/^\/(?:[^~]|~0|~1)*$/,eE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Bu(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return O.default.rootData;if(e[0]==="/"){if(!Z$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=O.default.rootData}else{let u=eE.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(d("property/index",l));return i[t-l]}if(l>t)throw Error(d("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,ut.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function d(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}xt.getData=Bu});var ai=P(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});class Gu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}ko.default=Gu});var gr=P(function(Do){Object.defineProperty(Do,"__esModule",{value:!0});var Ao=ni();class Vu extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,Ao.resolveUrl)(e,t,r),this.missingSchema=(0,Ao.normalizeId)((0,Ao.getFullPath)(e,this.missingRef))}}Do.default=Vu});var ci=P(function(Fe){Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var Me=j(),tE=ai(),Lt=Oe(),Ue=ni(),Ku=D(),rE=hr();class li{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,Ue.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={}}}Fe.SchemaEnv=li;function Lo(e){let t=zu.call(this,e);if(t)return t;let r=(0,Ue.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Me.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:tE.default,code:Me._`require("ajv/dist/runtime/validation_error").default`});let d=o.scopeName("validate");e.validateName=d;let u={gen:o,allErrors:this.opts.allErrors,data:Lt.default.data,parentData:Lt.default.parentData,parentDataProperty:Lt.default.parentDataProperty,dataNames:[Lt.default.data],dataPathArr:[Me.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Me.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Me.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Me._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,rE.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let c=o.toString();if(l=`${o.scopeRefs(Lt.default.scope)}return ${c}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Lt.default.self}`,`${Lt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{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:d,validateCode:c,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Me.Name?void 0:m,items:h instanceof Me.Name?void 0:h,dynamicProps:m instanceof Me.Name,dynamicItems:h instanceof Me.Name},f.source)f.source.evaluated=(0,Me.stringify)(f.evaluated)}return e.validate=f,e}catch(c){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw c}finally{this._compilations.delete(e)}}Fe.compileSchema=Lo;function iE(e,t,r){var i;r=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=oE.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 li({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=nE.call(this,s)}Fe.resolveRef=iE;function nE(e){if((0,Ue.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Lo.call(this,e)}function zu(e){for(let t of this._compilations)if(sE(t,e))return t}Fe.getCompilingSchema=zu;function sE(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function oE(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||wn.call(this,e,t)}function wn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,Ue._getFullPath)(this.opts.uriResolver,r),n=(0,Ue.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return No.call(this,r,e);let s=(0,Ue.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=wn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return No.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Lo.call(this,o);if(s===(0,Ue.normalizeId)(t)){let{schema:a}=o,{schemaId:d}=this.opts,u=a[d];if(u)n=(0,Ue.resolveUrl)(this.opts.uriResolver,n,u);return new li({schema:a,schemaId:d,root:e,baseId:n})}return No.call(this,r,o)}Fe.resolveSchema=wn;var aE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function No(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 d=r[(0,Ku.unescapeFragment)(a)];if(d===void 0)return;r=d;let u=typeof r==="object"&&r[this.opts.schemaId];if(!aE.has(a)&&u)t=(0,Ue.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Ku.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=wn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new li({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Wu=P(function(hA,lE){lE.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 Mo=P(function(gA,Yu){var cE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ju=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 qo(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 dE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hu(e){return e.length=0,!0}function uE(e,t,r){if(e.length){let i=qo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function pE(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=uE;for(let d=0;d<e.length;d++){let u=e[d];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(d>0&&e[d-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Hu}else{n.push(u);continue}}if(n.length)if(a===Hu)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(qo(n));return r.address=i.join(""),r}function Qu(e){if(fE(e,":")<2)return{host:e,isIPV6:!1};let t=pE(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 fE(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function mE(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 hE(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 gE(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(!Ju(r)){let i=Qu(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}Yu.exports={nonSimpleDomain:dE,recomposeAuthority:gE,normalizeComponentEncoding:hE,removeDotSegments:mE,isIPv4:Ju,isUUID:cE,normalizeIPv6:Qu,stringArrayToHexStripped:qo}});var rp=P(function(yA,tp){var{isUUID:yE}=Mo(),_E=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bE=["http","https","ws","wss","urn","urn:uuid"];function PE(e){return bE.indexOf(e)!==-1}function Uo(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 Xu(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Zu(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 vE(e){return e.secure=Uo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function wE(e){if(e.port===(Uo(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 $E(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(_E);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=Bo(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 EE(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=Bo(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 IE(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!yE(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function SE(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var ep={scheme:"http",domainHost:!0,parse:Xu,serialize:Zu},xE={scheme:"https",domainHost:ep.domainHost,parse:Xu,serialize:Zu},$n={scheme:"ws",domainHost:!0,parse:vE,serialize:wE},RE={scheme:"wss",domainHost:$n.domainHost,parse:$n.parse,serialize:$n.serialize},CE={scheme:"urn",parse:$E,serialize:EE,skipNormalize:!0},OE={scheme:"urn:uuid",parse:IE,serialize:SE,skipNormalize:!0},En={http:ep,https:xE,ws:$n,wss:RE,urn:CE,"urn:uuid":OE};Object.setPrototypeOf(En,null);function Bo(e){return e&&(En[e]||En[e.toLowerCase()])||void 0}tp.exports={wsIsSecure:Uo,SCHEMES:En,isValidSchemeName:PE,getSchemeHandler:Bo}});var sp=P(function(_A,Sn){var{normalizeIPv6:jE,removeDotSegments:di,recomposeAuthority:FE,normalizeComponentEncoding:In,isIPv4:TE,nonSimpleDomain:kE}=Mo(),{SCHEMES:AE,getSchemeHandler:ip}=rp();function DE(e,t){if(typeof e==="string")e=Ye(pt(e,t),t);else if(typeof e==="object")e=pt(Ye(e,t),t);return e}function NE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=np(pt(e,i),pt(t,i),i,!0);return i.skipEscape=!0,Ye(n,i)}function np(e,t,r,i){let n={};if(!i)e=pt(Ye(e,r),r),t=pt(Ye(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=di(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=di(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=di(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=di(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 LE(e,t,r){if(typeof e==="string")e=unescape(e),e=Ye(In(pt(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=Ye(In(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=Ye(In(pt(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=Ye(In(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function Ye(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=ip(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=FE(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=di(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 qE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pt(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(qE);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(TE(i.host)===!1){let d=jE(i.host);i.host=d.host.toLowerCase(),n=d.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=ip(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&kE(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 Go={SCHEMES:AE,normalize:DE,resolve:NE,resolveComponent:np,equal:LE,serialize:Ye,parse:pt};Sn.exports=Go;Sn.exports.default=Go;Sn.exports.fastUri=Go});var ap=P(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});var op=sp();op.code='require("ajv/dist/runtime/uri").default';Vo.default=op});var Wo=P(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var ME=hr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return ME.KeywordCxt}});var yr=j();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return yr._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return yr.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return yr.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return yr.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return yr.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return yr.CodeGen}});var UE=ai(),pp=gr(),BE=Po(),ui=ci(),GE=j(),pi=ni(),xn=ii(),zo=D(),lp=Wu(),VE=ap(),fp=(e,t)=>new RegExp(e,t);fp.code="new RegExp";var KE=["removeAdditional","useDefaults","coerceTypes"],zE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),WE={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."},HE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cp=200;function JE(e){var t,r,i,n,s,o,a,d,u,l,c,p,f,m,h,g,_,b,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,Z=J===!0||J===void 0?1:J||0,Re=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:fp,Hr=(n=e.uriResolver)!==null&&n!==void 0?n:VE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(d=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&d!==void 0?d:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(c=e.strictTuples)!==null&&c!==void 0?c: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:Z,regExp:Re}:{optimize:Z,regExp:Re},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:cp,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:cp,meta:(_=e.meta)!==null&&_!==void 0?_:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!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:Hr}}class Rn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...JE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new GE.ValueScope({scope:{},prefixes:zE,es5:t,lines:r}),this.logger=tI(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,BE.getRules)(),dp.call(this,WE,e,"NOT SUPPORTED"),dp.call(this,HE,e,"DEPRECATED","warn"),this._metaOpts=ZE.call(this),e.formats)YE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)XE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);QE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=lp;if(r==="id")i={...lp},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 c=this._addSchema(u,l);return c.validate||s.call(this,c)}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 pp.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 d.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function d(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,pi.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=up.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ui.SchemaEnv({schema:{},schemaId:r});if(t=ui.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=up.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,pi.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(iI.call(this,r,t),!t)return(0,zo.eachItem)(r,(n)=>Ko.call(this,n)),this;sI.call(this,t);let i={...t,type:(0,xn.getJSONTypes)(t.type),schemaType:(0,xn.getJSONTypes)(t.schemaType)};return(0,zo.eachItem)(r,i.type.length===0?(n)=>Ko.call(this,n,i):(n)=>i.type.forEach((s)=>Ko.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:d}=a.definition,u=s[o];if(d&&u)s[o]=mp(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,pi.normalizeId)(s||r);let d=pi.getSchemaRefs.call(this,e,r);if(a=new ui.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:d}),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 ui.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{ui.compileSchema.call(this,e)}finally{this.opts=t}}}Rn.ValidationError=UE.default;Rn.MissingRefError=pp.default;ie.default=Rn;function dp(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 up(e){return e=(0,pi.normalizeId)(e),this.schemas[e]||this.refs[e]}function QE(){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 YE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function XE(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 ZE(){let e={...this.opts};for(let t of KE)delete e[t];return e}var eI={log(){},warn(){},error(){}};function tI(e){if(e===!1)return eI;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 rI=/^[a-z_$][a-z0-9_$:-]*$/i;function iI(e,t){let{RULES:r}=this;if((0,zo.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!rI.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 Ko(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:d})=>d===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,xn.getJSONTypes)(t.type),schemaType:(0,xn.getJSONTypes)(t.schemaType)}};if(t.before)nI.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((d)=>this.addKeyword(d))}function nI(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 sI(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=mp(t);e.validateSchema=this.compile(t,!0)}var oI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function mp(e){return{anyOf:[e,oI]}}});var hp=P(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var aI={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ho.default=aI});var jn=P(function(qt){Object.defineProperty(qt,"__esModule",{value:!0});qt.callRef=qt.getValidate=void 0;var lI=gr(),gp=je(),we=j(),_r=Oe(),yp=ci(),Cn=D(),cI={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:d}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return c();let l=yp.resolveRef.call(d,u,n,r);if(l===void 0)throw new lI.default(i.opts.uriResolver,n,r);if(l instanceof yp.SchemaEnv)return p(l);return f(l);function c(){if(s===u)return On(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return On(e,we._`${m}.validate`,u,u.$async)}function p(m){let h=_p(e,m);On(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,we.stringify)(m)}:{ref:m}),g=t.name("valid"),_=e.subschema({schema:m,dataTypes:[],schemaPath:we.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(_),e.ok(g)}}};function _p(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):we._`${r.scopeValue("wrapper",{ref:t})}.validate`}qt.getValidate=_p;function On(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:d}=s,u=d.passContext?_r.default.this:we.nil;if(i)l();else c();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(we._`await ${(0,gp.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(we._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function c(){e.result((0,gp.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=we._`${m}.errors`;n.assign(_r.default.vErrors,we._`${_r.default.vErrors} === null ? ${h} : ${_r.default.vErrors}.concat(${h})`),n.assign(_r.default.errors,we._`${_r.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=Cn.mergeEvaluated.props(n,g.props,s.props)}else{let _=n.var("props",we._`${m}.evaluated.props`);s.props=Cn.mergeEvaluated.props(n,_,s.props,we.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=Cn.mergeEvaluated.items(n,g.items,s.items)}else{let _=n.var("items",we._`${m}.evaluated.items`);s.items=Cn.mergeEvaluated.items(n,_,s.items,we.Name)}}}qt.callRef=On;qt.default=cI});var Qo=P(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var dI=hp(),uI=jn(),pI=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dI.default,uI.default];Jo.default=pI});var bp=P(function(Yo){Object.defineProperty(Yo,"__esModule",{value:!0});var Fn=j(),Rt=Fn.operators,Tn={maximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},minimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},exclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},exclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},fI={message:({keyword:e,schemaCode:t})=>Fn.str`must be ${Tn[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Fn._`{comparison: ${Tn[e].okStr}, limit: ${t}}`},mI={keyword:Object.keys(Tn),type:"number",schemaType:"number",$data:!0,error:fI,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(Fn._`${r} ${Tn[t].fail} ${i} || isNaN(${r})`)}};Yo.default=mI});var Pp=P(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var fi=j(),hI={message:({schemaCode:e})=>fi.str`must be multiple of ${e}`,params:({schemaCode:e})=>fi._`{multipleOf: ${e}}`},gI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hI,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?fi._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:fi._`${o} !== parseInt(${o})`;e.fail$data(fi._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Xo.default=gI});var wp=P(function(Zo){Object.defineProperty(Zo,"__esModule",{value:!0});function vp(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}Zo.default=vp;vp.code='require("ajv/dist/runtime/ucs2length").default'});var $p=P(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Mt=j(),yI=D(),_I=wp(),bI={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return Mt.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>Mt._`{limit: ${e}}`},PI={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bI,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?Mt.operators.GT:Mt.operators.LT,o=n.opts.unicode===!1?Mt._`${r}.length`:Mt._`${(0,yI.useFunc)(e.gen,_I.default)}(${r})`;e.fail$data(Mt._`${o} ${s} ${i}`)}};ea.default=PI});var Ep=P(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var vI=je(),kn=j(),wI={message:({schemaCode:e})=>kn.str`must match pattern "${e}"`,params:({schemaCode:e})=>kn._`{pattern: ${e}}`},$I={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:wI,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?kn._`(new RegExp(${n}, ${o}))`:(0,vI.usePattern)(e,i);e.fail$data(kn._`!${a}.test(${t})`)}};ta.default=$I});var Ip=P(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var mi=j(),EI={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return mi.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>mi._`{limit: ${e}}`},II={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EI,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?mi.operators.GT:mi.operators.LT;e.fail$data(mi._`Object.keys(${r}).length ${n} ${i}`)}};ra.default=II});var Sp=P(function(ia){Object.defineProperty(ia,"__esModule",{value:!0});var hi=je(),gi=j(),SI=D(),xI={message:({params:{missingProperty:e}})=>gi.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>gi._`{missingProperty: ${e}}`},RI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:xI,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 d=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,_=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,SI.checkStrictMode)(o,_,o.opts.strictRequired)}}function u(){if(d||s)e.block$data(gi.nil,c);else for(let f of r)(0,hi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(d||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,hi.checkMissingProp)(e,r,f)),(0,hi.reportMissingProp)(e,f),t.else()}function c(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,hi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,hi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,gi.not)(m),()=>{e.error(),t.break()})},gi.nil)}}};ia.default=RI});var xp=P(function(na){Object.defineProperty(na,"__esModule",{value:!0});var yi=j(),CI={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return yi.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>yi._`{limit: ${e}}`},OI={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CI,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?yi.operators.GT:yi.operators.LT;e.fail$data(yi._`${r}.length ${n} ${i}`)}};na.default=OI});var An=P(function(sa){Object.defineProperty(sa,"__esModule",{value:!0});var Rp=Ro();Rp.code='require("ajv/dist/runtime/equal").default';sa.default=Rp});var Cp=P(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var oa=ii(),ne=j(),jI=D(),FI=An(),TI={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}}`},kI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:TI,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let d=t.let("valid"),u=s.items?(0,oa.getSchemaTypes)(s.items):[];e.block$data(d,l,ne._`${o} === false`),e.ok(d);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(d,!0),t.if(ne._`${m} > 1`,()=>(c()?p:f)(m,h))}function c(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),_=(0,oa.checkDataTypes)(u,g,a.opts.strictNumbers,oa.DataType.Wrong),b=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(_,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${b}[${g}] == "number"`,()=>{t.assign(h,ne._`${b}[${g}]`),e.error(),t.assign(d,!1).break()}).code(ne._`${b}[${g}] = ${m}`)})}function f(m,h){let g=(0,jI.useFunc)(t,FI.default),_=t.name("outer");t.label(_).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(d,!1).break(_)})))}}};aa.default=kI});var Op=P(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var la=j(),AI=D(),DI=An(),NI={message:"must be equal to constant",params:({schemaCode:e})=>la._`{allowedValue: ${e}}`},LI={keyword:"const",$data:!0,error:NI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(la._`!${(0,AI.useFunc)(t,DI.default)}(${r}, ${n})`);else e.fail(la._`${s} !== ${r}`)}};ca.default=LI});var jp=P(function(da){Object.defineProperty(da,"__esModule",{value:!0});var _i=j(),qI=D(),MI=An(),UI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>_i._`{allowedValues: ${e}}`},BI={keyword:"enum",schemaType:"array",$data:!0,error:UI,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,d,u=()=>d!==null&&d!==void 0?d:d=(0,qI.useFunc)(t,MI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,c);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,_i.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function c(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(_i._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?_i._`${u()}(${r}, ${f}[${m}])`:_i._`${r} === ${h}`}}};da.default=BI});var pa=P(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var GI=bp(),VI=Pp(),KI=$p(),zI=Ep(),WI=Ip(),HI=Sp(),JI=xp(),QI=Cp(),YI=Op(),XI=jp(),ZI=[GI.default,VI.default,KI.default,zI.default,WI.default,HI.default,JI.default,QI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},YI.default,XI.default];ua.default=ZI});var ma=P(function(bi){Object.defineProperty(bi,"__esModule",{value:!0});bi.validateAdditionalItems=void 0;var Ut=j(),fa=D(),eS={message:({params:{len:e}})=>Ut.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ut._`{limit: ${e}}`},tS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:eS,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,fa.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Fp(e,i)}};function Fp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",Ut._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(Ut._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,fa.alwaysValidSchema)(o,i)){let u=r.var("valid",Ut._`${a} <= ${t.length}`);r.if((0,Ut.not)(u),()=>d(u)),e.ok(u)}function d(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:fa.Type.Num},u),!o.allErrors)r.if((0,Ut.not)(u),()=>r.break())})}}bi.validateAdditionalItems=Fp;bi.default=tS});var ha=P(function(Pi){Object.defineProperty(Pi,"__esModule",{value:!0});Pi.validateTuple=void 0;var Tp=j(),Dn=D(),rS=je(),iS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return kp(e,"additionalItems",t);if(r.items=!0,(0,Dn.alwaysValidSchema)(r,t))return;e.ok((0,rS.validateArray)(e))}};function kp(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=Dn.mergeEvaluated.items(i,r.length,a.items);let d=i.name("valid"),u=i.const("len",Tp._`${s}.length`);r.forEach((c,p)=>{if((0,Dn.alwaysValidSchema)(a,c))return;i.if(Tp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},d)),e.ok(d)});function l(c){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===c.minItems&&(m===c.maxItems||c[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,Dn.checkStrictMode)(a,g,p.strictTuples)}}}Pi.validateTuple=kp;Pi.default=iS});var Ap=P(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var nS=ha(),sS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,nS.validateTuple)(e,"items")};ga.default=sS});var Np=P(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var Dp=j(),oS=D(),aS=je(),lS=ma(),cS={message:({params:{len:e}})=>Dp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dp._`{limit: ${e}}`},dS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cS,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,oS.alwaysValidSchema)(i,t))return;if(n)(0,lS.validateAdditionalItems)(e,n);else e.ok((0,aS.validateArray)(e))}};ya.default=dS});var Lp=P(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var Te=j(),Nn=D(),uS={message:({params:{min:e,max:t}})=>t===void 0?Te.str`must contain at least ${e} valid item(s)`:Te.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Te._`{minContains: ${e}}`:Te._`{minContains: ${e}, maxContains: ${t}}`},pS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:uS,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:d,maxContains:u}=i;if(s.opts.next)o=d===void 0?1:d,a=u;else o=1;let l=t.const("len",Te._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Nn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Nn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Nn.alwaysValidSchema)(s,r)){let h=Te._`${l} >= ${o}`;if(a!==void 0)h=Te._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let c=t.name("valid");if(a===void 0&&o===1)f(c,()=>t.if(c,()=>t.break()));else if(o===0){if(t.let(c,!0),a!==void 0)t.if(Te._`${n}.length > 0`,p)}else t.let(c,!1),p();e.result(c,()=>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,(_)=>{e.subschema({keyword:"contains",dataProp:_,dataPropType:Nn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Te._`${h}++`),a===void 0)t.if(Te._`${h} >= ${o}`,()=>t.assign(c,!0).break());else if(t.if(Te._`${h} > ${a}`,()=>t.assign(c,!1).break()),o===1)t.assign(c,!0);else t.if(Te._`${h} >= ${o}`,()=>t.assign(c,!0))}}};_a.default=pS});var Ln=P(function(Xe){Object.defineProperty(Xe,"__esModule",{value:!0});Xe.validateSchemaDeps=Xe.validatePropertyDeps=Xe.error=void 0;var ba=j(),fS=D(),vi=je();Xe.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return ba.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>ba._`{property: ${e},
8
- missingProperty: ${i},
3
+ (function(exports, require, module, __filename, __dirname) {var rb=Object.create;var{getPrototypeOf:nb,defineProperty:Hs,getOwnPropertyNames:ib}=Object;var sb=Object.prototype.hasOwnProperty;function ob(e){return this[e]}var ab,lb,Re=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var i=t?ab??=new WeakMap:lb??=new WeakMap,s=i.get(e);if(s)return s}r=e!=null?rb(nb(e)):{};let o=t||!e||!e.__esModule?Hs(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of ib(e))if(!sb.call(o,a))Hs(o,a,{get:ob.bind(e,a),enumerable:!0})}if(n)i.set(e,o);return o};var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var db=(e)=>e;function cb(e,t){this[e]=db.bind(null,t)}var ub=(e,t)=>{for(var r in t)Hs(e,r,{get:t[r],enumerable:!0,configurable:!0,set:cb.bind(t,r)})};var en=P(function(q){Object.defineProperty(q,"__esModule",{value:!0});q.regexpCode=q.getEsmExportName=q.getProperty=q.safeStringify=q.stringify=q.strConcat=q.addCodeArg=q.str=q._=q.nil=q._Code=q.Name=q.IDENTIFIER=q._CodeOrName=void 0;class ui{}q._CodeOrName=ui;q.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class lr extends ui{constructor(e){super();if(!q.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}}}q.Name=lr;class Me extends ui{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 lr)t[r.str]=(t[r.str]||0)+1;return t},{})}}q._Code=Me;q.nil=new Me("");function Jc(e,...t){let r=[e[0]],n=0;while(n<t.length)ho(r,t[n]),r.push(e[++n]);return new Me(r)}q._=Jc;var mo=new Me("+");function Qc(e,...t){let r=[Zr(e[0])],n=0;while(n<t.length)r.push(mo),ho(r,t[n]),r.push(mo,Zr(e[++n]));return Cw(r),new Me(r)}q.str=Qc;function ho(e,t){if(t instanceof Me)e.push(...t._items);else if(t instanceof lr)e.push(t);else e.push(Tw(t))}q.addCodeArg=ho;function Cw(e){let t=1;while(t<e.length-1){if(e[t]===mo){let r=Ow(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function Ow(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof lr||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 lr))return`"${e}${t.slice(1)}`;return}function Fw(e,t){return t.emptyStr()?e:e.emptyStr()?t:Qc`${e}${t}`}q.strConcat=Fw;function Tw(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Zr(Array.isArray(e)?e.join(","):e)}function Aw(e){return new Me(Zr(e))}q.stringify=Aw;function Zr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}q.safeStringify=Zr;function kw(e){return typeof e=="string"&&q.IDENTIFIER.test(e)?new Me(`.${e}`):Jc`[${e}]`}q.getProperty=kw;function Dw(e){if(typeof e=="string"&&q.IDENTIFIER.test(e))return new Me(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}q.getEsmExportName=Dw;function Nw(e){return new Me(e.toString())}q.regexpCode=Nw});var _o=P(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var be=en();class Yc extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var pi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(pi||(Pe.UsedValueState=pi={}));Pe.varKinds={const:new be.Name("const"),let:new be.Name("let"),var:new be.Name("var")};class go{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof be.Name?e:this.name(e)}name(e){return new be.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}}}Pe.Scope=go;class yo extends be.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=be._`.${new be.Name(t)}[${r}]`}}Pe.ValueScopeName=yo;var Mw=be._`\n`;class Xc extends go{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Mw:be.nil}}get(){return this._scope}name(e){return new yo(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:i}=n,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[i];if(o){let d=o.get(s);if(d)return d}else o=this._values[i]=new Map;o.set(s,n);let a=this._scope[i]||(this._scope[i]=[]),l=a.length;return a[l]=t.ref,n.setValue(t,{property:i,itemIndex:l}),n}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 be._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(n)=>{if(n.value===void 0)throw Error(`CodeGen: name "${n}" has no value`);return n.value.code},t,r)}_reduceValues(e,t,r={},n){let i=be.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((l)=>{if(a.has(l))return;a.set(l,pi.Started);let d=t(l);if(d){let c=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;i=be._`${i}${c} ${l} = ${d};${this.opts._n}`}else if(d=n===null||n===void 0?void 0:n(l))i=be._`${i}${d}${this.opts._n}`;else throw new Yc(l);a.set(l,pi.Completed)})}return i}}Pe.ValueScope=Xc});var O=P(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=en(),Le=_o(),Pt=en();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return Pt._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return Pt.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return Pt.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return Pt.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return Pt.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return Pt.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return Pt.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return Pt.Name}});var _i=_o();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return _i.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return _i.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return _i.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return _i.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 vt{optimizeNodes(){return this}optimizeNames(e,t){return this}}class Zc extends vt{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?Le.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${n};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=cr(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class vo extends vt{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=cr(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return yi(e,this.rhs)}}class eu extends vo{constructor(e,t,r,n){super(e,r,n);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class tu extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class ru extends vt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class nu extends vt{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class iu extends vt{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=cr(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class bi extends vt{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,n=r.length;while(n--){let i=r[n];if(i.optimizeNames(e,t))continue;Lw(e,i.names),r.splice(n,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>kt(e,t.names),{})}}class wt extends bi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class su extends bi{}class tn extends wt{}tn.kind="else";class ut extends wt{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 tn(r):r}if(t){if(e===!1)return t instanceof ut?t:t.nodes;if(this.nodes.length)return this;return new ut(cu(e),t instanceof ut?[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=cr(this.condition,e,t),this}get names(){let e=super.names;if(yi(e,this.condition),this.else)kt(e,this.else.names);return e}}ut.kind="if";class dr extends wt{}dr.kind="for";class ou extends dr{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=cr(this.iteration,e,t),this}get names(){return kt(super.names,this.iteration.names)}}class au extends dr{constructor(e,t,r,n){super();this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){let t=e.es5?Le.varKinds.var:this.varKind,{name:r,from:n,to:i}=this;return`for(${t} ${r}=${n}; ${r}<${i}; ${r}++)`+super.render(e)}get names(){let e=yi(super.names,this.from);return yi(e,this.to)}}class bo extends dr{constructor(e,t,r,n){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=n}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=cr(this.iterable,e,t),this}get names(){return kt(super.names,this.iterable.names)}}class fi extends wt{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)}}fi.kind="func";class mi extends bi{render(e){return"return "+super.render(e)}}mi.kind="return";class lu extends wt{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,n;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(n=this.finally)===null||n===void 0||n.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)kt(e,this.catch.names);if(this.finally)kt(e,this.finally.names);return e}}class hi extends wt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}hi.kind="catch";class gi extends wt{render(e){return"finally"+super.render(e)}}gi.kind="finally";class du{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
4
+ `:""},this._extScope=e,this._scope=new Le.Scope({parent:e}),this._nodes=[new su]}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,n){let i=this._scope.toName(t);if(r!==void 0&&n)this._constants[i.str]=r;return this._leafNode(new Zc(e,i,r)),i}const(e,t,r){return this._def(Le.varKinds.const,e,t,r)}let(e,t,r){return this._def(Le.varKinds.let,e,t,r)}var(e,t,r){return this._def(Le.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new vo(e,t,r))}add(e,t){return this._leafNode(new eu(e,A.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new iu(e));return this}object(...e){let t=["{"];for(let[r,n]of e){if(t.length>1)t.push(",");if(t.push(r),r!==n||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,n)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new ut(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 ut(e))}else(){return this._elseNode(new tn)}endIf(){return this._endBlockNode(ut,tn)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new ou(e),t)}forRange(e,t,r,n,i=this.opts.es5?Le.varKinds.var:Le.varKinds.let){let s=this._scope.toName(e);return this._for(new au(i,s,t,r),()=>n(s))}forOf(e,t,r,n=Le.varKinds.const){let i=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(i,N._`${s}[${o}]`),r(i)})}return this._for(new bo("of",n,i,t),()=>r(i))}forIn(e,t,r,n=this.opts.es5?Le.varKinds.var:Le.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let i=this._scope.toName(e);return this._for(new bo("in",n,i,t),()=>r(i))}endFor(){return this._endBlockNode(dr)}label(e){return this._leafNode(new tu(e))}break(e){return this._leafNode(new ru(e))}return(e){let t=new mi;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(mi)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let n=new lu;if(this._blockNode(n),this.code(e),t){let i=this.name("e");this._currNode=n.catch=new hi(i),t(i)}if(r)this._currNode=n.finally=new gi,this.code(r);return this._endBlockNode(hi,gi)}throw(e){return this._leafNode(new nu(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,n){if(this._blockNode(new fi(e,t,r)),n)this.code(n).endFunc();return this}endFunc(){return this._endBlockNode(fi)}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 ut))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=du;function kt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function yi(e,t){return t instanceof N._CodeOrName?kt(e,t.names):e}function cr(e,t,r){if(e instanceof N.Name)return n(e);if(!i(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=n(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function n(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function i(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Lw(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function cu(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${Po(e)}`}A.not=cu;var qw=uu(A.operators.AND);function Uw(...e){return e.reduce(qw)}A.and=Uw;var Bw=uu(A.operators.OR);function Gw(...e){return e.reduce(Bw)}A.or=Gw;function uu(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${Po(t)} ${e} ${Po(r)}`}function Po(e){return e instanceof N.Name?e:N._`(${e})`}});var D=P(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=O(),Vw=en();function zw(e){let t={};for(let r of e)t[r]=!0;return t}k.toHash=zw;function Kw(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return mu(e,t),!hu(t,e.self.RULES.all)}k.alwaysValidSchema=Kw;function mu(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let i=n.RULES.keywords;for(let s in t)if(!i[s])_u(e,`unknown keyword: "${s}"`)}k.checkUnknownRules=mu;function hu(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}k.schemaHasRules=hu;function Ww(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=Ww;function Hw({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(n)}`}k.schemaRefOrVal=Hw;function Jw(e){return gu(decodeURIComponent(e))}k.unescapeFragment=Jw;function Qw(e){return encodeURIComponent($o(e))}k.escapeFragment=Qw;function $o(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}k.escapeJsonPointer=$o;function gu(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}k.unescapeJsonPointer=gu;function Yw(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}k.eachItem=Yw;function pu({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,s,o,a)=>{let l=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(i,s,o):t(i,s,o),o):s instanceof G.Name?(t(i,o,s),s):r(s,o);return a===G.Name&&!(l instanceof G.Name)?n(i,l):l}}k.mergeEvaluated={props:pu({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} || {}`),Io(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:yu}),items:pu({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 yu(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)Io(e,r,t);return r}k.evaluatedPropsToName=yu;function Io(e,t,r){Object.keys(r).forEach((n)=>e.assign(G._`${t}${(0,G.getProperty)(n)}`,!0))}k.setEvaluated=Io;var fu={};function Xw(e,t){return e.scopeValue("func",{ref:t,code:fu[t.code]||(fu[t.code]=new Vw._Code(t.code))})}k.useFunc=Xw;var wo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(wo||(k.Type=wo={}));function Zw(e,t,r){if(e instanceof G.Name){let n=t===wo.Num;return r?n?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:n?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+$o(e)}k.getErrorPath=Zw;function _u(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=_u});var Ce=P(function(Eo){Object.defineProperty(Eo,"__esModule",{value:!0});var le=O(),e$={data:new le.Name("data"),valCxt:new le.Name("valCxt"),instancePath:new le.Name("instancePath"),parentData:new le.Name("parentData"),parentDataProperty:new le.Name("parentDataProperty"),rootData:new le.Name("rootData"),dynamicAnchors:new le.Name("dynamicAnchors"),vErrors:new le.Name("vErrors"),errors:new le.Name("errors"),this:new le.Name("this"),self:new le.Name("self"),scope:new le.Name("scope"),json:new le.Name("json"),jsonPos:new le.Name("jsonPos"),jsonLen:new le.Name("jsonLen"),jsonPart:new le.Name("jsonPart")};Eo.default=e$});var rn=P(function(de){Object.defineProperty(de,"__esModule",{value:!0});de.extendErrors=de.resetErrorsCount=de.reportExtraError=de.reportError=de.keyword$DataError=de.keywordError=void 0;var M=O(),Pi=D(),me=Ce();de.keywordError={message:({keyword:e})=>M.str`must pass "${e}" keyword validation`};de.keyword$DataError={message:({keyword:e,schemaType:t})=>t?M.str`"${e}" keyword must be ${t} ($data)`:M.str`"${e}" keyword is invalid ($data)`};function t$(e,t=de.keywordError,r,n){let{it:i}=e,{gen:s,compositeRule:o,allErrors:a}=i,l=vu(e,t,r);if(n!==null&&n!==void 0?n:o||a)bu(s,l);else Pu(i,M._`[${l}]`)}de.reportError=t$;function r$(e,t=de.keywordError,r){let{it:n}=e,{gen:i,compositeRule:s,allErrors:o}=n,a=vu(e,t,r);if(bu(i,a),!(s||o))Pu(n,me.default.vErrors)}de.reportExtraError=r$;function n$(e,t){e.assign(me.default.errors,t),e.if(M._`${me.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(M._`${me.default.vErrors}.length`,t),()=>e.assign(me.default.vErrors,null)))}de.resetErrorsCount=n$;function i$({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:s}){if(i===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,me.default.errors,(a)=>{if(e.const(o,M._`${me.default.vErrors}[${a}]`),e.if(M._`${o}.instancePath === undefined`,()=>e.assign(M._`${o}.instancePath`,(0,M.strConcat)(me.default.instancePath,s.errorPath))),e.assign(M._`${o}.schemaPath`,M.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(M._`${o}.schema`,r),e.assign(M._`${o}.data`,n)})}de.extendErrors=i$;function bu(e,t){let r=e.const("err",t);e.if(M._`${me.default.vErrors} === null`,()=>e.assign(me.default.vErrors,M._`[${r}]`),M._`${me.default.vErrors}.push(${r})`),e.code(M._`${me.default.errors}++`)}function Pu(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;if(i.$async)r.throw(M._`new ${e.ValidationError}(${t})`);else r.assign(M._`${n}.errors`,t),r.return(!1)}var Dt={keyword:new M.Name("keyword"),schemaPath:new M.Name("schemaPath"),params:new M.Name("params"),propertyName:new M.Name("propertyName"),message:new M.Name("message"),schema:new M.Name("schema"),parentSchema:new M.Name("parentSchema")};function vu(e,t,r){let{createErrors:n}=e.it;if(n===!1)return M._`{}`;return s$(e,t,r)}function s$(e,t,r={}){let{gen:n,it:i}=e,s=[o$(i,r),a$(e,r)];return l$(e,t,s),n.object(...s)}function o$({errorPath:e},{instancePath:t}){let r=t?M.str`${e}${(0,Pi.getErrorPath)(t,Pi.Type.Str)}`:e;return[me.default.instancePath,(0,M.strConcat)(me.default.instancePath,r)]}function a$({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:M.str`${t}/${e}`;if(r)i=M.str`${i}${(0,Pi.getErrorPath)(r,Pi.Type.Str)}`;return[Dt.schemaPath,i]}function l$(e,{params:t,message:r},n){let{keyword:i,data:s,schemaValue:o,it:a}=e,{opts:l,propertyName:d,topSchemaRef:c,schemaPath:p}=a;if(n.push([Dt.keyword,i],[Dt.params,typeof t=="function"?t(e):t||M._`{}`]),l.messages)n.push([Dt.message,typeof r=="function"?r(e):r]);if(l.verbose)n.push([Dt.schema,o],[Dt.parentSchema,M._`${c}${p}`],[me.default.data,s]);if(d)n.push([Dt.propertyName,d])}});var $u=P(function(ur){Object.defineProperty(ur,"__esModule",{value:!0});ur.boolOrEmptySchema=ur.topBoolOrEmptySchema=void 0;var d$=rn(),c$=O(),u$=Ce(),p$={message:"boolean schema is false"};function f$(e){let{gen:t,schema:r,validateName:n}=e;if(r===!1)wu(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(u$.default.data);else t.assign(c$._`${n}.errors`,null),t.return(!0)}ur.topBoolOrEmptySchema=f$;function m$(e,t){let{gen:r,schema:n}=e;if(n===!1)r.var(t,!1),wu(e);else r.var(t,!0)}ur.boolOrEmptySchema=m$;function wu(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,d$.reportError)(i,p$,void 0,t)}});var So=P(function(pr){Object.defineProperty(pr,"__esModule",{value:!0});pr.getRules=pr.isJSONType=void 0;var h$=["string","number","integer","boolean","null","object","array"],g$=new Set(h$);function y$(e){return typeof e=="string"&&g$.has(e)}pr.isJSONType=y$;function _$(){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:{}}}pr.getRules=_$});var xo=P(function($t){Object.defineProperty($t,"__esModule",{value:!0});$t.shouldUseRule=$t.shouldUseGroup=$t.schemaHasRulesForType=void 0;function b$({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Iu(e,n)}$t.schemaHasRulesForType=b$;function Iu(e,t){return t.rules.some((r)=>Eu(e,r))}$t.shouldUseGroup=Iu;function Eu(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((n)=>e[n]!==void 0))}$t.shouldUseRule=Eu});var nn=P(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 P$=So(),v$=xo(),w$=rn(),F=O(),Su=D(),fr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(fr||(ce.DataType=fr={}));function $$(e){let t=xu(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=$$;function xu(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(P$.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=xu;function I$(e,t){let{gen:r,data:n,opts:i}=e,s=E$(t,i.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,v$.schemaHasRulesForType)(e,t[0]));if(o){let a=Ro(t,n,i.strictNumbers,fr.Wrong);r.if(a,()=>{if(s.length)S$(e,t,s);else Co(e)})}return o}ce.coerceAndCheckDataType=I$;var ju=new Set(["string","number","integer","boolean","null"]);function E$(e,t){return t?e.filter((r)=>ju.has(r)||t==="array"&&r==="array"):[]}function S$(e,t,r){let{gen:n,data:i,opts:s}=e,o=n.let("dataType",F._`typeof ${i}`),a=n.let("coerced",F._`undefined`);if(s.coerceTypes==="array")n.if(F._`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,F._`${i}[0]`).assign(o,F._`typeof ${i}`).if(Ro(t,i,s.strictNumbers),()=>n.assign(a,i)));n.if(F._`${a} !== undefined`);for(let d of r)if(ju.has(d)||d==="array"&&s.coerceTypes==="array")l(d);n.else(),Co(e),n.endIf(),n.if(F._`${a} !== undefined`,()=>{n.assign(i,a),x$(e,a)});function l(d){switch(d){case"string":n.elseIf(F._`${o} == "number" || ${o} == "boolean"`).assign(a,F._`"" + ${i}`).elseIf(F._`${i} === null`).assign(a,F._`""`);return;case"number":n.elseIf(F._`${o} == "boolean" || ${i} === null
5
+ || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,F._`+${i}`);return;case"integer":n.elseIf(F._`${o} === "boolean" || ${i} === null
6
+ || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,F._`+${i}`);return;case"boolean":n.elseIf(F._`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf(F._`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf(F._`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf(F._`${o} === "string" || ${o} === "number"
7
+ || ${o} === "boolean" || ${i} === null`).assign(a,F._`[${i}]`)}}}function x$({gen:e,parentData:t,parentDataProperty:r},n){e.if(F._`${t} !== undefined`,()=>e.assign(F._`${t}[${r}]`,n))}function jo(e,t,r,n=fr.Correct){let i=n===fr.Correct?F.operators.EQ:F.operators.NEQ,s;switch(e){case"null":return F._`${t} ${i} null`;case"array":s=F._`Array.isArray(${t})`;break;case"object":s=F._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(F._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return F._`typeof ${t} ${i} ${e}`}return n===fr.Correct?s:(0,F.not)(s);function o(a=F.nil){return(0,F.and)(F._`typeof ${t} == "number"`,a,r?F._`isFinite(${t})`:F.nil)}}ce.checkDataType=jo;function Ro(e,t,r,n){if(e.length===1)return jo(e[0],t,r,n);let i,s=(0,Su.toHash)(e);if(s.array&&s.object){let o=F._`typeof ${t} != "object"`;i=s.null?o:F._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=F.nil;if(s.number)delete s.integer;for(let o in s)i=(0,F.and)(i,jo(o,t,r,n));return i}ce.checkDataTypes=Ro;var j$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?F._`{type: ${e}}`:F._`{type: ${t}}`};function Co(e){let t=R$(e);(0,w$.reportError)(t,j$)}ce.reportTypeError=Co;function R$(e){let{gen:t,data:r,schema:n}=e,i=(0,Su.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var Cu=P(function(vi){Object.defineProperty(vi,"__esModule",{value:!0});vi.assignDefaults=void 0;var mr=O(),C$=D();function O$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)Ru(e,i,r[i].default);else if(t==="array"&&Array.isArray(n))n.forEach((i,s)=>Ru(e,s,i.default))}vi.assignDefaults=O$;function Ru(e,t,r){let{gen:n,compositeRule:i,data:s,opts:o}=e;if(r===void 0)return;let a=mr._`${s}${(0,mr.getProperty)(t)}`;if(i){(0,C$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let l=mr._`${a} === undefined`;if(o.useDefaults==="empty")l=mr._`${l} || ${a} === null || ${a} === ""`;n.if(l,mr._`${a} = ${(0,mr.stringify)(r)}`)}});var Oe=P(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=O(),Oo=D(),It=Ce(),F$=D();function T$(e,t){let{gen:r,data:n,it:i}=e;r.if(To(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=T$;function A$({gen:e,data:t,it:{opts:r}},n,i){return(0,K.or)(...n.map((s)=>(0,K.and)(To(e,t,s,r.ownProperties),K._`${i} = ${s}`)))}B.checkMissingProp=A$;function k$(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=k$;function Ou(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=Ou;function Fo(e,t,r){return K._`${Ou(e)}.call(${t}, ${r})`}B.isOwnProperty=Fo;function D$(e,t,r,n){let i=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return n?K._`${i} && ${Fo(e,t,r)}`:i}B.propertyInData=D$;function To(e,t,r,n){let i=K._`${t}${(0,K.getProperty)(r)} === undefined`;return n?(0,K.or)(i,(0,K.not)(Fo(e,t,r))):i}B.noPropertyInData=To;function Fu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=Fu;function N$(e,t){return Fu(t).filter((r)=>!(0,Oo.alwaysValidSchema)(e,t[r]))}B.schemaProperties=N$;function M$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,l,d){let c=d?K._`${e}, ${t}, ${n}${i}`:t,p=[[It.default.instancePath,(0,K.strConcat)(It.default.instancePath,s)],[It.default.parentData,o.parentData],[It.default.parentDataProperty,o.parentDataProperty],[It.default.rootData,It.default.rootData]];if(o.opts.dynamicRef)p.push([It.default.dynamicAnchors,It.default.dynamicAnchors]);let h=K._`${c}, ${r.object(...p)}`;return l!==K.nil?K._`${a}.call(${l}, ${h})`:K._`${a}(${h})`}B.callValidateCode=M$;var L$=K._`new RegExp`;function q$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,s=i(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${i.code==="new RegExp"?L$:(0,F$.useFunc)(e,i)}(${r}, ${n})`})}B.usePattern=q$;function U$(e){let{gen:t,data:r,keyword:n,it:i}=e,s=t.name("valid");if(i.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 l=t.const("len",K._`${r}.length`);t.forRange("i",0,l,(d)=>{e.subschema({keyword:n,dataProp:d,dataPropType:Oo.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=U$;function B$(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((l)=>(0,Oo.alwaysValidSchema)(i,l))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((l,d)=>{let c=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(c,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=B$});var ku=P(function(Qe){Object.defineProperty(Qe,"__esModule",{value:!0});Qe.validateKeywordUsage=Qe.validSchemaType=Qe.funcKeywordCode=Qe.macroKeywordCode=void 0;var he=O(),Nt=Ce(),G$=Oe(),V$=rn();function z$(e,t){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=e,a=t.macro.call(o.self,i,s,o),l=Au(r,n,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let d=r.name("valid");e.subschema({schema:a,schemaPath:he.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}Qe.macroKeywordCode=z$;function K$(e,t){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:l}=e;H$(l,t);let d=!a&&t.compile?t.compile.call(l.self,s,o,l):t.validate,c=Au(n,i,d),p=n.let("valid");e.block$data(p,h),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function h(){if(t.errors===!1){if(m(),t.modifying)Tu(e);g(()=>e.error())}else{let y=t.async?u():f();if(t.modifying)Tu(e);g(()=>W$(e,y))}}function u(){let y=n.let("ruleErrs",null);return n.try(()=>m(he._`await `),(b)=>n.assign(p,!1).if(he._`${b} instanceof ${l.ValidationError}`,()=>n.assign(y,he._`${b}.errors`),()=>n.throw(b))),y}function f(){let y=he._`${c}.errors`;return n.assign(y,null),m(he.nil),y}function m(y=t.async?he._`await `:he.nil){let b=l.opts.passContext?Nt.default.this:Nt.default.self,v=!(("compile"in t)&&!a||t.schema===!1);n.assign(p,he._`${y}${(0,G$.callValidateCode)(e,c,b,v)}`,t.modifying)}function g(y){var b;n.if((0,he.not)((b=t.valid)!==null&&b!==void 0?b:p),y)}}Qe.funcKeywordCode=K$;function Tu(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,he._`${n.parentData}[${n.parentDataProperty}]`))}function W$(e,t){let{gen:r}=e;r.if(he._`Array.isArray(${t})`,()=>{r.assign(Nt.default.vErrors,he._`${Nt.default.vErrors} === null ? ${t} : ${Nt.default.vErrors}.concat(${t})`).assign(Nt.default.errors,he._`${Nt.default.vErrors}.length`),(0,V$.extendErrors)(e)},()=>e.error())}function H$({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function Au(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,he.stringify)(r)})}function J$(e,t,r=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Qe.validSchemaType=J$;function Q$({schema:e,opts:t,self:r,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw Error("ajv implementation error");let o=i.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(i.validateSchema){if(!i.validateSchema(e[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw Error(l)}}}Qe.validateKeywordUsage=Q$});var Nu=P(function(Et){Object.defineProperty(Et,"__esModule",{value:!0});Et.extendSubschemaMode=Et.extendSubschemaData=Et.getSubschema=void 0;var Ye=O(),Du=D();function Y$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&n!==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:Ye._`${e.schemaPath}${(0,Ye.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Ye._`${e.schemaPath}${(0,Ye.getProperty)(t)}${(0,Ye.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Du.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}Et.getSubschema=Y$;function X$(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==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:d,dataPathArr:c,opts:p}=t,h=a.let("data",Ye._`${t.data}${(0,Ye.getProperty)(r)}`,!0);l(h),e.errorPath=Ye.str`${d}${(0,Du.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=Ye._`${r}`,e.dataPathArr=[...c,e.parentDataProperty]}if(i!==void 0){let d=i instanceof Ye.Name?i:a.let("data",i,!0);if(l(d),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function l(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}Et.extendSubschemaData=X$;function Z$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:s}){if(n!==void 0)e.compositeRule=n;if(i!==void 0)e.createErrors=i;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}Et.extendSubschemaMode=Z$});var Ao=P(function(Kk,Mu){Mu.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))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),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var qu=P(function(Wk,Lu){var St=Lu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};wi(t,n,i,e,"",e)};St.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};St.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};St.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};St.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 wi(e,t,r,n,i,s,o,a,l,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,s,o,a,l,d);for(var c in n){var p=n[c];if(Array.isArray(p)){if(c in St.arrayKeywords)for(var h=0;h<p.length;h++)wi(e,t,r,p[h],i+"/"+c+"/"+h,s,i,c,n,h)}else if(c in St.propsKeywords){if(p&&typeof p=="object")for(var u in p)wi(e,t,r,p[u],i+"/"+c+"/"+eI(u),s,i,c,n,u)}else if(c in St.keywords||e.allKeys&&!(c in St.skipKeywords))wi(e,t,r,p,i+"/"+c,s,i,c,n)}r(n,i,s,o,a,l,d)}}function eI(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var sn=P(function(ve){Object.defineProperty(ve,"__esModule",{value:!0});ve.getSchemaRefs=ve.resolveUrl=ve.normalizeId=ve._getFullPath=ve.getFullPath=ve.inlineRef=void 0;var tI=D(),rI=Ao(),nI=qu(),iI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function sI(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!ko(e);if(!t)return!1;return Uu(e)<=t}ve.inlineRef=sI;var oI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ko(e){for(let t in e){if(oI.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(ko))return!0;if(typeof r=="object"&&ko(r))return!0}return!1}function Uu(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,iI.has(r))continue;if(typeof e[r]=="object")(0,tI.eachItem)(e[r],(n)=>t+=Uu(n));if(t===1/0)return 1/0}return t}function Bu(e,t="",r){if(r!==!1)t=hr(t);let n=e.parse(t);return Gu(e,n)}ve.getFullPath=Bu;function Gu(e,t){return e.serialize(t).split("#")[0]+"#"}ve._getFullPath=Gu;var aI=/#\/?$/;function hr(e){return e?e.replace(aI,""):""}ve.normalizeId=hr;function lI(e,t,r){return r=hr(r),e.resolve(t,r)}ve.resolveUrl=lI;var dI=/^[a-z_][-a-z0-9._]*$/i;function cI(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=hr(e[r]||t),s={"":i},o=Bu(n,i,!1),a={},l=new Set;return nI(e,{allKeys:!0},(p,h,u,f)=>{if(f===void 0)return;let m=o+h,g=s[f];if(typeof p[r]=="string")g=y.call(this,p[r]);b.call(this,p.$anchor),b.call(this,p.$dynamicAnchor),s[h]=g;function y(v){let I=this.opts.uriResolver.resolve;if(v=hr(g?I(g,v):v),l.has(v))throw c(v);l.add(v);let E=this.refs[v];if(typeof E=="string")E=this.refs[E];if(typeof E=="object")d(p,E.schema,v);else if(v!==hr(m))if(v[0]==="#")d(p,a[v],v),a[v]=p;else this.refs[v]=m;return v}function b(v){if(typeof v=="string"){if(!dI.test(v))throw Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function d(p,h,u){if(h!==void 0&&!rI(p,h))throw c(u)}function c(p){return Error(`reference "${p}" resolves to more than one schema`)}}ve.getSchemaRefs=cI});var gr=P(function(xt){Object.defineProperty(xt,"__esModule",{value:!0});xt.getData=xt.KeywordCxt=xt.validateFunctionCode=void 0;var Hu=$u(),Vu=nn(),No=xo(),$i=nn(),uI=Cu(),an=ku(),Do=Nu(),S=O(),C=Ce(),pI=sn(),pt=D(),on=rn();function fI(e){if(Yu(e)){if(Xu(e),Qu(e)){gI(e);return}}Ju(e,()=>(0,Hu.topBoolOrEmptySchema)(e))}xt.validateFunctionCode=fI;function Ju({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},s){if(i.code.es5)e.func(t,S._`${C.default.data}, ${C.default.valCxt}`,n.$async,()=>{e.code(S._`"use strict"; ${zu(r,i)}`),hI(e,i),e.code(s)});else e.func(t,S._`${C.default.data}, ${mI(i)}`,n.$async,()=>e.code(zu(r,i)).code(s))}function mI(e){return S._`{${C.default.instancePath}="", ${C.default.parentData}, ${C.default.parentDataProperty}, ${C.default.rootData}=${C.default.data}${e.dynamicRef?S._`, ${C.default.dynamicAnchors}={}`:S.nil}}={}`}function hI(e,t){e.if(C.default.valCxt,()=>{if(e.var(C.default.instancePath,S._`${C.default.valCxt}.${C.default.instancePath}`),e.var(C.default.parentData,S._`${C.default.valCxt}.${C.default.parentData}`),e.var(C.default.parentDataProperty,S._`${C.default.valCxt}.${C.default.parentDataProperty}`),e.var(C.default.rootData,S._`${C.default.valCxt}.${C.default.rootData}`),t.dynamicRef)e.var(C.default.dynamicAnchors,S._`${C.default.valCxt}.${C.default.dynamicAnchors}`)},()=>{if(e.var(C.default.instancePath,S._`""`),e.var(C.default.parentData,S._`undefined`),e.var(C.default.parentDataProperty,S._`undefined`),e.var(C.default.rootData,C.default.data),t.dynamicRef)e.var(C.default.dynamicAnchors,S._`{}`)})}function gI(e){let{schema:t,opts:r,gen:n}=e;Ju(e,()=>{if(r.$comment&&t.$comment)ep(e);if(vI(e),n.let(C.default.vErrors,null),n.let(C.default.errors,0),r.unevaluated)yI(e);Zu(e),II(e)});return}function yI(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 zu(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(Yu(e)){if(Xu(e),Qu(e)){bI(e,t);return}}(0,Hu.boolOrEmptySchema)(e,t)}function Qu({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 Yu(e){return typeof e.schema!="boolean"}function bI(e,t){let{schema:r,gen:n,opts:i}=e;if(i.$comment&&r.$comment)ep(e);wI(e),$I(e);let s=n.const("_errs",C.default.errors);Zu(e,s),n.var(t,S._`${s} === ${C.default.errors}`)}function Xu(e){(0,pt.checkUnknownRules)(e),PI(e)}function Zu(e,t){if(e.opts.jtd)return Ku(e,[],!1,t);let r=(0,Vu.getSchemaTypes)(e.schema),n=(0,Vu.coerceAndCheckDataType)(e,r);Ku(e,r,!n,t)}function PI(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&(0,pt.schemaHasRulesButRef)(t,i.RULES))i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function vI(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,pt.checkStrictMode)(e,"default is ignored in the schema root")}function wI(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,pI.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function $I(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function ep({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let s=r.$comment;if(i.$comment===!0)e.code(S._`${C.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=S.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${C.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function II(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:s}=e;if(r.$async)t.if(S._`${C.default.errors} === 0`,()=>t.return(C.default.data),()=>t.throw(S._`new ${i}(${C.default.vErrors})`));else{if(t.assign(S._`${n}.errors`,C.default.vErrors),s.unevaluated)EI(e);t.return(S._`${C.default.errors} === 0`)}}function EI({gen:e,evaluated:t,props:r,items:n}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(n instanceof S.Name)e.assign(S._`${t}.items`,n)}function Ku(e,t,r,n){let{gen:i,schema:s,data:o,allErrors:a,opts:l,self:d}=e,{RULES:c}=d;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,pt.schemaHasRulesButRef)(s,c))){i.block(()=>rp(e,"$ref",c.all.$ref.definition));return}if(!l.jtd)SI(e,t);i.block(()=>{for(let h of c.rules)p(h);p(c.post)});function p(h){if(!(0,No.shouldUseGroup)(s,h))return;if(h.type){if(i.if((0,$i.checkDataType)(h.type,o,l.strictNumbers)),Wu(e,h),t.length===1&&t[0]===h.type&&r)i.else(),(0,$i.reportTypeError)(e);i.endIf()}else Wu(e,h);if(!a)i.if(S._`${C.default.errors} === ${n||0}`)}}function Wu(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;if(i)(0,uI.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,No.shouldUseRule)(n,s))rp(e,s.keyword,s.definition,t.type)})}function SI(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(xI(e,t),!e.opts.allowUnionTypes)jI(e,t);RI(e,e.dataTypes)}function xI(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!tp(e.dataTypes,r))Mo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),OI(e,t)}function jI(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Mo(e,"use allowUnionTypes to allow union type keyword")}function RI(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,No.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;if(s.length&&!s.some((o)=>CI(t,o)))Mo(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function CI(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function tp(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function OI(e,t){let r=[];for(let n of e.dataTypes)if(tp(t,n))r.push(n);else if(t.includes("integer")&&n==="number")r.push("integer");e.dataTypes=r}function Mo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,pt.checkStrictMode)(e,t,e.opts.strictTypes)}class Lo{constructor(e,t,r){if((0,an.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,pt.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",np(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,an.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",C.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?on.reportExtraError:on.reportError)(this,this.def.error,t)}$dataError(){(0,on.reportError)(this,this.def.$dataError||on.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,on.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:n,schemaType:i,def:s}=this;if(r.if((0,S.or)(S._`${n} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(i.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:n,it:i}=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,$i.checkDataTypes)(a,t,i.opts.strictNumbers,$i.DataType.Wrong)}`}return S.nil}function o(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,Do.getSubschema)(this.it,e);(0,Do.extendSubschemaData)(r,this.it,e),(0,Do.extendSubschemaMode)(r,e);let n={...this.it,...r,items:void 0,props:void 0};return _I(n,t),n}mergeEvaluated(e,t){let{it:r,gen:n}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=pt.mergeEvaluated.props(n,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=pt.mergeEvaluated.items(n,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}xt.KeywordCxt=Lo;function rp(e,t,r,n){let i=new Lo(e,r,t);if("code"in r)r.code(i,n);else if(i.$data&&r.validate)(0,an.funcKeywordCode)(i,r);else if("macro"in r)(0,an.macroKeywordCode)(i,r);else if(r.compile||r.validate)(0,an.funcKeywordCode)(i,r)}var FI=/^\/(?:[^~]|~0|~1)*$/,TI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function np(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,s;if(e==="")return C.default.rootData;if(e[0]==="/"){if(!FI.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,s=C.default.rootData}else{let d=TI.exec(e);if(!d)throw Error(`Invalid JSON-pointer: ${e}`);let c=+d[1];if(i=d[2],i==="#"){if(c>=t)throw Error(l("property/index",c));return n[t-c]}if(c>t)throw Error(l("data",c));if(s=r[t-c],!i)return s}let o=s,a=i.split("/");for(let d of a)if(d)s=S._`${s}${(0,S.getProperty)((0,pt.unescapeJsonPointer)(d))}`,o=S._`${o} && ${s}`;return o;function l(d,c){return`Cannot access ${d} ${c} levels up, current level is ${t}`}}xt.getData=np});var ln=P(function(qo){Object.defineProperty(qo,"__esModule",{value:!0});class ip extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}qo.default=ip});var yr=P(function(Bo){Object.defineProperty(Bo,"__esModule",{value:!0});var Uo=sn();class sp extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,Uo.resolveUrl)(e,t,r),this.missingSchema=(0,Uo.normalizeId)((0,Uo.getFullPath)(e,this.missingRef))}}Bo.default=sp});var cn=P(function(Fe){Object.defineProperty(Fe,"__esModule",{value:!0});Fe.resolveSchema=Fe.getCompilingSchema=Fe.resolveRef=Fe.compileSchema=Fe.SchemaEnv=void 0;var qe=O(),AI=ln(),Mt=Ce(),Ue=sn(),op=D(),kI=gr();class dn{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,Ue.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={}}}Fe.SchemaEnv=dn;function Vo(e){let t=ap.call(this,e);if(t)return t;let r=(0,Ue.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new qe.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:AI.default,code:qe._`require("ajv/dist/runtime/validation_error").default`});let l=o.scopeName("validate");e.validateName=l;let d={gen:o,allErrors:this.opts.allErrors,data:Mt.default.data,parentData:Mt.default.parentData,parentDataProperty:Mt.default.parentDataProperty,dataNames:[Mt.default.data],dataPathArr:[qe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,qe.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:qe.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:qe._`""`,opts:this.opts,self:this},c;try{this._compilations.add(e),(0,kI.validateFunctionCode)(d),o.optimize(this.opts.code.optimize);let p=o.toString();if(c=`${o.scopeRefs(Mt.default.scope)}return ${p}`,this.opts.code.process)c=this.opts.code.process(c,e);let u=Function(`${Mt.default.self}`,`${Mt.default.scope}`,c)(this,this.scope.get());if(this.scope.value(l,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async)u.$async=!0;if(this.opts.code.source===!0)u.source={validateName:l,validateCode:p,scopeValues:o._values};if(this.opts.unevaluated){let{props:f,items:m}=d;if(u.evaluated={props:f instanceof qe.Name?void 0:f,items:m instanceof qe.Name?void 0:m,dynamicProps:f instanceof qe.Name,dynamicItems:m instanceof qe.Name},u.source)u.source.evaluated=(0,qe.stringify)(u.evaluated)}return e.validate=u,e}catch(p){if(delete e.validate,delete e.validateName,c)this.logger.error("Error compiling schema, function code:",c);throw p}finally{this._compilations.delete(e)}}Fe.compileSchema=Vo;function DI(e,t,r){var n;r=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let s=LI.call(this,e,r);if(s===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;if(o)s=new dn({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=NI.call(this,s)}Fe.resolveRef=DI;function NI(e){if((0,Ue.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Vo.call(this,e)}function ap(e){for(let t of this._compilations)if(MI(t,e))return t}Fe.getCompilingSchema=ap;function MI(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function LI(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||Ii.call(this,e,t)}function Ii(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ue._getFullPath)(this.opts.uriResolver,r),i=(0,Ue.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Go.call(this,r,e);let s=(0,Ue.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ii.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Go.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Vo.call(this,o);if(s===(0,Ue.normalizeId)(t)){let{schema:a}=o,{schemaId:l}=this.opts,d=a[l];if(d)i=(0,Ue.resolveUrl)(this.opts.uriResolver,i,d);return new dn({schema:a,schemaId:l,root:e,baseId:i})}return Go.call(this,r,o)}Fe.resolveSchema=Ii;var qI=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Go(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let l=r[(0,op.unescapeFragment)(a)];if(l===void 0)return;r=l;let d=typeof r==="object"&&r[this.opts.schemaId];if(!qI.has(a)&&d)t=(0,Ue.resolveUrl)(this.opts.uriResolver,t,d)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,op.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ue.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=Ii.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new dn({schema:r,schemaId:o,root:n,baseId:t}),s.schema!==s.root.schema)return s;return}});var lp=P(function(Zk,UI){UI.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 Ko=P(function(eD,pp){var BI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cp=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 zo(e){let t="",r=0,n=0;for(n=0;n<e.length;n++){if(r=e[n].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var GI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function dp(e){return e.length=0,!0}function VI(e,t,r){if(e.length){let n=zo(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function zI(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=VI;for(let l=0;l<e.length;l++){let d=e[l];if(d==="["||d==="]")continue;if(d===":"){if(s===!0)o=!0;if(!a(i,n,r))break;if(++t>7){r.error=!0;break}if(l>0&&e[l-1]===":")s=!0;n.push(":");continue}else if(d==="%"){if(!a(i,n,r))break;a=dp}else{i.push(d);continue}}if(i.length)if(a===dp)r.zone=i.join("");else if(o)n.push(i.join(""));else n.push(zo(i));return r.address=n.join(""),r}function up(e){if(KI(e,":")<2)return{host:e,isIPV6:!1};let t=zI(e);if(!t.error){let{address:r,address:n}=t;if(t.zone)r+="%"+t.zone,n+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:n}}else return{host:e,isIPV6:!1}}function KI(e,t){let r=0;for(let n=0;n<e.length;n++)if(e[n]===t)r++;return r}function WI(e){let t=e,r=[],n=-1,i=0;while(i=t.length){if(i===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(i===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(i===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((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function HI(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 JI(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(!cp(r)){let n=up(r);if(n.isIPV6===!0)r=`[${n.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}pp.exports={nonSimpleDomain:GI,recomposeAuthority:JI,normalizeComponentEncoding:HI,removeDotSegments:WI,isIPv4:cp,isUUID:BI,normalizeIPv6:up,stringArrayToHexStripped:zo}});var yp=P(function(tD,gp){var{isUUID:QI}=Ko(),YI=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,XI=["http","https","ws","wss","urn","urn:uuid"];function ZI(e){return XI.indexOf(e)!==-1}function Wo(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 fp(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function mp(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 eE(e){return e.secure=Wo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function tE(e){if(e.port===(Wo(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 rE(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(YI);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,s=Ho(i);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function nE(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,s=Ho(i);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${n||t.nid}:${a}`,t.skipEscape=!0,o}function iE(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!QI(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function sE(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var hp={scheme:"http",domainHost:!0,parse:fp,serialize:mp},oE={scheme:"https",domainHost:hp.domainHost,parse:fp,serialize:mp},Ei={scheme:"ws",domainHost:!0,parse:eE,serialize:tE},aE={scheme:"wss",domainHost:Ei.domainHost,parse:Ei.parse,serialize:Ei.serialize},lE={scheme:"urn",parse:rE,serialize:nE,skipNormalize:!0},dE={scheme:"urn:uuid",parse:iE,serialize:sE,skipNormalize:!0},Si={http:hp,https:oE,ws:Ei,wss:aE,urn:lE,"urn:uuid":dE};Object.setPrototypeOf(Si,null);function Ho(e){return e&&(Si[e]||Si[e.toLowerCase()])||void 0}gp.exports={wsIsSecure:Wo,SCHEMES:Si,isValidSchemeName:ZI,getSchemeHandler:Ho}});var Pp=P(function(rD,ji){var{normalizeIPv6:cE,removeDotSegments:un,recomposeAuthority:uE,normalizeComponentEncoding:xi,isIPv4:pE,nonSimpleDomain:fE}=Ko(),{SCHEMES:mE,getSchemeHandler:_p}=yp();function hE(e,t){if(typeof e==="string")e=Xe(ft(e,t),t);else if(typeof e==="object")e=ft(Xe(e,t),t);return e}function gE(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=bp(ft(e,n),ft(t,n),n,!0);return n.skipEscape=!0,Xe(i,n)}function bp(e,t,r,n){let i={};if(!n)e=ft(Xe(e,r),r),t=ft(Xe(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=un(t.path||""),i.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=un(t.path||""),i.query=t.query;else{if(!t.path)if(i.path=e.path,t.query!==void 0)i.query=t.query;else i.query=e.query;else{if(t.path[0]==="/")i.path=un(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)i.path="/"+t.path;else if(!e.path)i.path=t.path;else i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;i.path=un(i.path)}i.query=t.query}i.userinfo=e.userinfo,i.host=e.host,i.port=e.port}i.scheme=e.scheme}return i.fragment=t.fragment,i}function yE(e,t,r){if(typeof e==="string")e=unescape(e),e=Xe(xi(ft(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=Xe(xi(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=Xe(xi(ft(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=Xe(xi(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function Xe(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],s=_p(n.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,n);if(r.path!==void 0)if(!n.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(n.reference!=="suffix"&&r.scheme)i.push(r.scheme,":");let o=uE(r);if(o!==void 0){if(n.reference!=="suffix")i.push("//");if(i.push(o),r.path&&r.path[0]!=="/")i.push("/")}if(r.path!==void 0){let a=r.path;if(!n.absolutePath&&(!s||!s.absolutePath))a=un(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);i.push(a)}if(r.query!==void 0)i.push("?",r.query);if(r.fragment!==void 0)i.push("#",r.fragment);return i.join("")}var _E=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ft(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(_E);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port))n.port=s[5];if(n.host)if(pE(n.host)===!1){let l=cE(n.host);n.host=l.host.toLowerCase(),i=l.isIPV6}else i=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==n.reference)n.error=n.error||"URI is not a "+r.reference+" reference.";let o=_p(r.scheme||n.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(n.host&&(r.domainHost||o&&o.domainHost)&&i===!1&&fE(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(n.scheme!==void 0)n.scheme=unescape(n.scheme);if(n.host!==void 0)n.host=unescape(n.host)}if(n.path)n.path=escape(unescape(n.path));if(n.fragment)n.fragment=encodeURI(decodeURIComponent(n.fragment))}if(o&&o.parse)o.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Jo={SCHEMES:mE,normalize:hE,resolve:gE,resolveComponent:bp,equal:yE,serialize:Xe,parse:ft};ji.exports=Jo;ji.exports.default=Jo;ji.exports.fastUri=Jo});var wp=P(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});var vp=Pp();vp.code='require("ajv/dist/runtime/uri").default';Qo.default=vp});var Zo=P(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var bE=gr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return bE.KeywordCxt}});var _r=O();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return _r._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return _r.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return _r.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return _r.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return _r.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return _r.CodeGen}});var PE=ln(),xp=yr(),vE=So(),pn=cn(),wE=O(),fn=sn(),Ri=nn(),Xo=D(),$p=lp(),$E=wp(),jp=(e,t)=>new RegExp(e,t);jp.code="new RegExp";var IE=["removeAdditional","useDefaults","coerceTypes"],EE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),SE={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."},xE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ip=200;function jE(e){var t,r,n,i,s,o,a,l,d,c,p,h,u,f,m,g,y,b,v,I,E,w,x,T,R;let V=e.strict,Q=(t=e.code)===null||t===void 0?void 0:t.optimize,ee=Q===!0||Q===void 0?1:Q||0,je=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:jp,Hr=(i=e.uriResolver)!==null&&i!==void 0?i:$E.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(l=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&l!==void 0?l:!0,strictTypes:(c=(d=e.strictTypes)!==null&&d!==void 0?d:V)!==null&&c!==void 0?c:"log",strictTuples:(h=(p=e.strictTuples)!==null&&p!==void 0?p:V)!==null&&h!==void 0?h:"log",strictRequired:(f=(u=e.strictRequired)!==null&&u!==void 0?u:V)!==null&&f!==void 0?f:!1,code:e.code?{...e.code,optimize:ee,regExp:je}:{optimize:ee,regExp:je},loopRequired:(m=e.loopRequired)!==null&&m!==void 0?m:Ip,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Ip,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(I=e.schemaId)!==null&&I!==void 0?I:"$id",addUsedSchema:(E=e.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(w=e.validateSchema)!==null&&w!==void 0?w:!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:Hr}}class Ci{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...jE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new wE.ValueScope({scope:{},prefixes:EE,es5:t,lines:r}),this.logger=AE(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,vE.getRules)(),Ep.call(this,SE,e,"NOT SUPPORTED"),Ep.call(this,xE,e,"DEPRECATED","warn"),this._metaOpts=FE.call(this),e.formats)CE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)OE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);RE.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=$p;if(r==="id")n={...$p},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[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 n=r(t);if(!("$async"in r))this.errors=r.errors;return n}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 n.call(this,e,t);async function n(d,c){await i.call(this,d.$schema);let p=this._addSchema(d,c);return p.validate||s.call(this,p)}async function i(d){if(d&&!this.getSchema(d))await n.call(this,{$ref:d},!0)}async function s(d){try{return this._compileSchemaEnv(d)}catch(c){if(!(c instanceof xp.default))throw c;return o.call(this,c),await a.call(this,c.missingSchema),s.call(this,d)}}function o({missingSchema:d,missingRef:c}){if(this.refs[d])throw Error(`AnySchema ${d} is loaded but ${c} cannot be resolved`)}async function a(d){let c=await l.call(this,d);if(!this.refs[d])await i.call(this,c.$schema);if(!this.refs[d])this.addSchema(c,d,t)}async function l(d){let c=this._loading[d];if(c)return c;try{return await(this._loading[d]=r(d))}finally{delete this._loading[d]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,n);return this}let i;if(typeof e==="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw Error(`schema ${s} must be string`)}return t=(0,fn.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!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 n=this.validate(r,e);if(!n&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw Error(i)}return n}getSchema(e){let t;while(typeof(t=Sp.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,n=new pn.SchemaEnv({schema:{},schemaId:r});if(t=pn.resolveSchema.call(this,n,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=Sp.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,fn.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(DE.call(this,r,t),!t)return(0,Xo.eachItem)(r,(i)=>Yo.call(this,i)),this;ME.call(this,t);let n={...t,type:(0,Ri.getJSONTypes)(t.type),schemaType:(0,Ri.getJSONTypes)(t.schemaType)};return(0,Xo.eachItem)(r,n.type.length===0?(i)=>Yo.call(this,i,n):(i)=>n.type.forEach((s)=>Yo.call(this,i,n,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 n=r.rules.findIndex((i)=>i.keyword===e);if(n>=0)r.rules.splice(n,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((n)=>`${r}${n.instancePath} ${n.message}`).reduce((n,i)=>n+t+i)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let i=n.split("/").slice(1),s=e;for(let o of i)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:l}=a.definition,d=s[o];if(l&&d)s[o]=Rp(d)}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];if(!t||t.test(r)){if(typeof n=="string")delete e[r];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[r]}}}_addSchema(e,t,r,n=this.opts.validateSchema,i=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,fn.normalizeId)(s||r);let l=fn.getSchemaRefs.call(this,e,r);if(a=new pn.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:l}),this._cache.set(a.schema,a),i&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(n)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 pn.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{pn.compileSchema.call(this,e)}finally{this.opts=t}}}Ci.ValidationError=PE.default;Ci.MissingRefError=xp.default;ie.default=Ci;function Ep(e,t,r,n="error"){for(let i in e){let s=i;if(s in t)this.logger[n](`${r}: option ${i}. ${e[s]}`)}}function Sp(e){return e=(0,fn.normalizeId)(e),this.schemas[e]||this.refs[e]}function RE(){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 CE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function OE(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 FE(){let e={...this.opts};for(let t of IE)delete e[t];return e}var TE={log(){},warn(){},error(){}};function AE(e){if(e===!1)return TE;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 kE=/^[a-z_$][a-z0-9_$:-]*$/i;function DE(e,t){let{RULES:r}=this;if((0,Xo.eachItem)(e,(n)=>{if(r.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!kE.test(n))throw Error(`Keyword ${n} 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 Yo(e,t,r){var n;let i=t===null||t===void 0?void 0:t.post;if(r&&i)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:l})=>l===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,Ri.getJSONTypes)(t.type),schemaType:(0,Ri.getJSONTypes)(t.schemaType)}};if(t.before)NE.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((l)=>this.addKeyword(l))}function NE(e,t,r){let n=e.rules.findIndex((i)=>i.keyword===r);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function ME(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Rp(t);e.validateSchema=this.compile(t,!0)}var LE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Rp(e){return{anyOf:[e,LE]}}});var Cp=P(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var qE={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ea.default=qE});var Ti=P(function(Lt){Object.defineProperty(Lt,"__esModule",{value:!0});Lt.callRef=Lt.getValidate=void 0;var UE=yr(),Op=Oe(),we=O(),br=Ce(),Fp=cn(),Oi=D(),BE={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:l}=n,{root:d}=s;if((r==="#"||r==="#/")&&i===d.baseId)return p();let c=Fp.resolveRef.call(l,d,i,r);if(c===void 0)throw new UE.default(n.opts.uriResolver,i,r);if(c instanceof Fp.SchemaEnv)return h(c);return u(c);function p(){if(s===d)return Fi(e,o,s,s.$async);let f=t.scopeValue("root",{ref:d});return Fi(e,we._`${f}.validate`,d,d.$async)}function h(f){let m=Tp(e,f);Fi(e,m,f,f.$async)}function u(f){let m=t.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,we.stringify)(f)}:{ref:f}),g=t.name("valid"),y=e.subschema({schema:f,dataTypes:[],schemaPath:we.nil,topSchemaRef:m,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function Tp(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):we._`${r.scopeValue("wrapper",{ref:t})}.validate`}Lt.getValidate=Tp;function Fi(e,t,r,n){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:a,opts:l}=s,d=l.passContext?br.default.this:we.nil;if(n)c();else p();function c(){if(!a.$async)throw Error("async schema referenced by sync schema");let f=i.let("valid");i.try(()=>{if(i.code(we._`await ${(0,Op.callValidateCode)(e,t,d)}`),u(t),!o)i.assign(f,!0)},(m)=>{if(i.if(we._`!(${m} instanceof ${s.ValidationError})`,()=>i.throw(m)),h(m),!o)i.assign(f,!1)}),e.ok(f)}function p(){e.result((0,Op.callValidateCode)(e,t,d),()=>u(t),()=>h(t))}function h(f){let m=we._`${f}.errors`;i.assign(br.default.vErrors,we._`${br.default.vErrors} === null ? ${m} : ${br.default.vErrors}.concat(${m})`),i.assign(br.default.errors,we._`${br.default.vErrors}.length`)}function u(f){var m;if(!s.opts.unevaluated)return;let g=(m=r===null||r===void 0?void 0:r.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=Oi.mergeEvaluated.props(i,g.props,s.props)}else{let y=i.var("props",we._`${f}.evaluated.props`);s.props=Oi.mergeEvaluated.props(i,y,s.props,we.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=Oi.mergeEvaluated.items(i,g.items,s.items)}else{let y=i.var("items",we._`${f}.evaluated.items`);s.items=Oi.mergeEvaluated.items(i,y,s.items,we.Name)}}}Lt.callRef=Fi;Lt.default=BE});var ra=P(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var GE=Cp(),VE=Ti(),zE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GE.default,VE.default];ta.default=zE});var Ap=P(function(na){Object.defineProperty(na,"__esModule",{value:!0});var Ai=O(),jt=Ai.operators,ki={maximum:{okStr:"<=",ok:jt.LTE,fail:jt.GT},minimum:{okStr:">=",ok:jt.GTE,fail:jt.LT},exclusiveMaximum:{okStr:"<",ok:jt.LT,fail:jt.GTE},exclusiveMinimum:{okStr:">",ok:jt.GT,fail:jt.LTE}},KE={message:({keyword:e,schemaCode:t})=>Ai.str`must be ${ki[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ai._`{comparison: ${ki[e].okStr}, limit: ${t}}`},WE={keyword:Object.keys(ki),type:"number",schemaType:"number",$data:!0,error:KE,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data(Ai._`${r} ${ki[t].fail} ${n} || isNaN(${r})`)}};na.default=WE});var kp=P(function(ia){Object.defineProperty(ia,"__esModule",{value:!0});var mn=O(),HE={message:({schemaCode:e})=>mn.str`must be multiple of ${e}`,params:({schemaCode:e})=>mn._`{multipleOf: ${e}}`},JE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:HE,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),a=s?mn._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:mn._`${o} !== parseInt(${o})`;e.fail$data(mn._`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};ia.default=JE});var Np=P(function(sa){Object.defineProperty(sa,"__esModule",{value:!0});function Dp(e){let t=e.length,r=0,n=0,i;while(n<t)if(r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t){if(i=e.charCodeAt(n),(i&64512)===56320)n++}return r}sa.default=Dp;Dp.code='require("ajv/dist/runtime/ucs2length").default'});var Mp=P(function(oa){Object.defineProperty(oa,"__esModule",{value:!0});var qt=O(),QE=D(),YE=Np(),XE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return qt.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>qt._`{limit: ${e}}`},ZE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:XE,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,s=t==="maxLength"?qt.operators.GT:qt.operators.LT,o=i.opts.unicode===!1?qt._`${r}.length`:qt._`${(0,QE.useFunc)(e.gen,YE.default)}(${r})`;e.fail$data(qt._`${o} ${s} ${n}`)}};oa.default=ZE});var Lp=P(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var eS=Oe(),Di=O(),tS={message:({schemaCode:e})=>Di.str`must match pattern "${e}"`,params:({schemaCode:e})=>Di._`{pattern: ${e}}`},rS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:tS,code(e){let{data:t,$data:r,schema:n,schemaCode:i,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?Di._`(new RegExp(${i}, ${o}))`:(0,eS.usePattern)(e,n);e.fail$data(Di._`!${a}.test(${t})`)}};aa.default=rS});var qp=P(function(la){Object.defineProperty(la,"__esModule",{value:!0});var hn=O(),nS={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return hn.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>hn._`{limit: ${e}}`},iS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:nS,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?hn.operators.GT:hn.operators.LT;e.fail$data(hn._`Object.keys(${r}).length ${i} ${n}`)}};la.default=iS});var Up=P(function(da){Object.defineProperty(da,"__esModule",{value:!0});var gn=Oe(),yn=O(),sS=D(),oS={message:({params:{missingProperty:e}})=>yn.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>yn._`{missingProperty: ${e}}`},aS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:oS,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(o.allErrors)d();else c();if(a.strictRequired){let u=e.parentSchema.properties,{definedProperties:f}=e.it;for(let m of r)if((u===null||u===void 0?void 0:u[m])===void 0&&!f.has(m)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,sS.checkStrictMode)(o,y,o.opts.strictRequired)}}function d(){if(l||s)e.block$data(yn.nil,p);else for(let u of r)(0,gn.checkReportMissingProp)(e,u)}function c(){let u=t.let("missing");if(l||s){let f=t.let("valid",!0);e.block$data(f,()=>h(u,f)),e.ok(f)}else t.if((0,gn.checkMissingProp)(e,r,u)),(0,gn.reportMissingProp)(e,u),t.else()}function p(){t.forOf("prop",n,(u)=>{e.setParams({missingProperty:u}),t.if((0,gn.noPropertyInData)(t,i,u,a.ownProperties),()=>e.error())})}function h(u,f){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(f,(0,gn.propertyInData)(t,i,u,a.ownProperties)),t.if((0,yn.not)(f),()=>{e.error(),t.break()})},yn.nil)}}};da.default=aS});var Bp=P(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var _n=O(),lS={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return _n.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>_n._`{limit: ${e}}`},dS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:lS,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?_n.operators.GT:_n.operators.LT;e.fail$data(_n._`${r}.length ${i} ${n}`)}};ca.default=dS});var Ni=P(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var Gp=Ao();Gp.code='require("ajv/dist/runtime/equal").default';ua.default=Gp});var Vp=P(function(fa){Object.defineProperty(fa,"__esModule",{value:!0});var pa=nn(),se=O(),cS=D(),uS=Ni(),pS={message:({params:{i:e,j:t}})=>se.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>se._`{i: ${e}, j: ${t}}`},fS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:pS,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=e;if(!n&&!i)return;let l=t.let("valid"),d=s.items?(0,pa.getSchemaTypes)(s.items):[];e.block$data(l,c,se._`${o} === false`),e.ok(l);function c(){let f=t.let("i",se._`${r}.length`),m=t.let("j");e.setParams({i:f,j:m}),t.assign(l,!0),t.if(se._`${f} > 1`,()=>(p()?h:u)(f,m))}function p(){return d.length>0&&!d.some((f)=>f==="object"||f==="array")}function h(f,m){let g=t.name("item"),y=(0,pa.checkDataTypes)(d,g,a.opts.strictNumbers,pa.DataType.Wrong),b=t.const("indices",se._`{}`);t.for(se._`;${f}--;`,()=>{if(t.let(g,se._`${r}[${f}]`),t.if(y,se._`continue`),d.length>1)t.if(se._`typeof ${g} == "string"`,se._`${g} += "_"`);t.if(se._`typeof ${b}[${g}] == "number"`,()=>{t.assign(m,se._`${b}[${g}]`),e.error(),t.assign(l,!1).break()}).code(se._`${b}[${g}] = ${f}`)})}function u(f,m){let g=(0,cS.useFunc)(t,uS.default),y=t.name("outer");t.label(y).for(se._`;${f}--;`,()=>t.for(se._`${m} = ${f}; ${m}--;`,()=>t.if(se._`${g}(${r}[${f}], ${r}[${m}])`,()=>{e.error(),t.assign(l,!1).break(y)})))}}};fa.default=fS});var zp=P(function(ha){Object.defineProperty(ha,"__esModule",{value:!0});var ma=O(),mS=D(),hS=Ni(),gS={message:"must be equal to constant",params:({schemaCode:e})=>ma._`{allowedValue: ${e}}`},yS={keyword:"const",$data:!0,error:gS,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:s}=e;if(n||s&&typeof s=="object")e.fail$data(ma._`!${(0,mS.useFunc)(t,hS.default)}(${r}, ${i})`);else e.fail(ma._`${s} !== ${r}`)}};ha.default=yS});var Kp=P(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var bn=O(),_S=D(),bS=Ni(),PS={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>bn._`{allowedValues: ${e}}`},vS={keyword:"enum",schemaType:"array",$data:!0,error:PS,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e;if(!n&&i.length===0)throw Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,l,d=()=>l!==null&&l!==void 0?l:l=(0,_S.useFunc)(t,bS.default),c;if(a||n)c=t.let("valid"),e.block$data(c,p);else{if(!Array.isArray(i))throw Error("ajv implementation error");let u=t.const("vSchema",s);c=(0,bn.or)(...i.map((f,m)=>h(u,m)))}e.pass(c);function p(){t.assign(c,!1),t.forOf("v",s,(u)=>t.if(bn._`${d()}(${r}, ${u})`,()=>t.assign(c,!0).break()))}function h(u,f){let m=i[f];return typeof m==="object"&&m!==null?bn._`${d()}(${r}, ${u}[${f}])`:bn._`${r} === ${m}`}}};ga.default=vS});var _a=P(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var wS=Ap(),$S=kp(),IS=Mp(),ES=Lp(),SS=qp(),xS=Up(),jS=Bp(),RS=Vp(),CS=zp(),OS=Kp(),FS=[wS.default,$S.default,IS.default,ES.default,SS.default,xS.default,jS.default,RS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},CS.default,OS.default];ya.default=FS});var Pa=P(function(Pn){Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateAdditionalItems=void 0;var Ut=O(),ba=D(),TS={message:({params:{len:e}})=>Ut.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Ut._`{limit: ${e}}`},AS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:TS,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ba.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Wp(e,n)}};function Wp(e,t){let{gen:r,schema:n,data:i,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",Ut._`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(Ut._`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,ba.alwaysValidSchema)(o,n)){let d=r.var("valid",Ut._`${a} <= ${t.length}`);r.if((0,Ut.not)(d),()=>l(d)),e.ok(d)}function l(d){r.forRange("i",t.length,a,(c)=>{if(e.subschema({keyword:s,dataProp:c,dataPropType:ba.Type.Num},d),!o.allErrors)r.if((0,Ut.not)(d),()=>r.break())})}}Pn.validateAdditionalItems=Wp;Pn.default=AS});var va=P(function(vn){Object.defineProperty(vn,"__esModule",{value:!0});vn.validateTuple=void 0;var Hp=O(),Mi=D(),kS=Oe(),DS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return Jp(e,"additionalItems",t);if(r.items=!0,(0,Mi.alwaysValidSchema)(r,t))return;e.ok((0,kS.validateArray)(e))}};function Jp(e,t,r=e.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=e;if(c(i),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Mi.mergeEvaluated.items(n,r.length,a.items);let l=n.name("valid"),d=n.const("len",Hp._`${s}.length`);r.forEach((p,h)=>{if((0,Mi.alwaysValidSchema)(a,p))return;n.if(Hp._`${d} > ${h}`,()=>e.subschema({keyword:o,schemaProp:h,dataProp:h},l)),e.ok(l)});function c(p){let{opts:h,errSchemaPath:u}=a,f=r.length,m=f===p.minItems&&(f===p.maxItems||p[t]===!1);if(h.strictTuples&&!m){let g=`"${o}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Mi.checkStrictMode)(a,g,h.strictTuples)}}}vn.validateTuple=Jp;vn.default=DS});var Qp=P(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});var NS=va(),MS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,NS.validateTuple)(e,"items")};wa.default=MS});var Xp=P(function($a){Object.defineProperty($a,"__esModule",{value:!0});var Yp=O(),LS=D(),qS=Oe(),US=Pa(),BS={message:({params:{len:e}})=>Yp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Yp._`{limit: ${e}}`},GS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:BS,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;if(n.items=!0,(0,LS.alwaysValidSchema)(n,t))return;if(i)(0,US.validateAdditionalItems)(e,i);else e.ok((0,qS.validateArray)(e))}};$a.default=GS});var Zp=P(function(Ia){Object.defineProperty(Ia,"__esModule",{value:!0});var Te=O(),Li=D(),VS={message:({params:{min:e,max:t}})=>t===void 0?Te.str`must contain at least ${e} valid item(s)`:Te.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Te._`{minContains: ${e}}`:Te._`{minContains: ${e}, maxContains: ${t}}`},zS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:VS,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e,o,a,{minContains:l,maxContains:d}=n;if(s.opts.next)o=l===void 0?1:l,a=d;else o=1;let c=t.const("len",Te._`${i}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Li.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Li.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Li.alwaysValidSchema)(s,r)){let m=Te._`${c} >= ${o}`;if(a!==void 0)m=Te._`${m} && ${c} <= ${a}`;e.pass(m);return}s.items=!0;let p=t.name("valid");if(a===void 0&&o===1)u(p,()=>t.if(p,()=>t.break()));else if(o===0){if(t.let(p,!0),a!==void 0)t.if(Te._`${i}.length > 0`,h)}else t.let(p,!1),h();e.result(p,()=>e.reset());function h(){let m=t.name("_valid"),g=t.let("count",0);u(m,()=>t.if(m,()=>f(g)))}function u(m,g){t.forRange("i",0,c,(y)=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Li.Type.Num,compositeRule:!0},m),g()})}function f(m){if(t.code(Te._`${m}++`),a===void 0)t.if(Te._`${m} >= ${o}`,()=>t.assign(p,!0).break());else if(t.if(Te._`${m} > ${a}`,()=>t.assign(p,!1).break()),o===1)t.assign(p,!0);else t.if(Te._`${m} >= ${o}`,()=>t.assign(p,!0))}}};Ia.default=zS});var qi=P(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.validateSchemaDeps=Ze.validatePropertyDeps=Ze.error=void 0;var Ea=O(),KS=D(),wn=Oe();Ze.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return Ea.str`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>Ea._`{property: ${e},
8
+ missingProperty: ${n},
9
9
  depsCount: ${t},
10
- deps: ${r}}`};var mS={keyword:"dependencies",type:"object",schemaType:"object",error:Xe.error,code(e){let[t,r]=hS(e);qp(e,t),Mp(e,r)}};function hS({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 qp(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 d=(0,vi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(d,()=>{for(let u of a)(0,vi.checkReportMissingProp)(e,u)});else r.if(ba._`${d} && (${(0,vi.checkMissingProp)(e,a,s)})`),(0,vi.reportMissingProp)(e,s),r.else()}}Xe.validatePropertyDeps=qp;function Mp(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,fS.alwaysValidSchema)(s,t[a]))continue;r.if((0,vi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let d=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(d,o)},()=>r.var(o,!0)),e.ok(o)}}Xe.validateSchemaDeps=Mp;Xe.default=mS});var Bp=P(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var Up=j(),gS=D(),yS={message:"property name must be valid",params:({params:e})=>Up._`{propertyName: ${e.propertyName}}`},_S={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yS,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,gS.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,Up.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};Pa.default=_S});var wa=P(function(va){Object.defineProperty(va,"__esModule",{value:!0});var qn=je(),Be=j(),bS=Oe(),Mn=D(),PS={message:"must NOT have additional properties",params:({params:e})=>Be._`{additionalProperty: ${e.additionalProperty}}`},vS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:PS,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:d}=o;if(o.props=!0,d.removeAdditional!=="all"&&(0,Mn.alwaysValidSchema)(o,r))return;let u=(0,qn.allSchemaProperties)(i.properties),l=(0,qn.allSchemaProperties)(i.patternProperties);c(),e.ok(Be._`${s} === ${bS.default.errors}`);function c(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let _;if(u.length>8){let b=(0,Mn.schemaRefOrVal)(o,i.properties,"properties");_=(0,qn.isOwnProperty)(t,b,g)}else if(u.length)_=(0,Be.or)(...u.map((b)=>Be._`${g} === ${b}`));else _=Be.nil;if(l.length)_=(0,Be.or)(_,...l.map((b)=>Be._`${(0,qn.usePattern)(e,b)}.test(${g})`));return(0,Be.not)(_)}function f(g){t.code(Be._`delete ${n}[${g}]`)}function m(g){if(d.removeAdditional==="all"||d.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,Mn.alwaysValidSchema)(o,r)){let _=t.name("valid");if(d.removeAdditional==="failing")h(g,_,!1),t.if((0,Be.not)(_),()=>{e.reset(),f(g)});else if(h(g,_),!a)t.if((0,Be.not)(_),()=>t.break())}}function h(g,_,b){let v={keyword:"additionalProperties",dataProp:g,dataPropType:Mn.Type.Str};if(b===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,_)}}};va.default=vS});var Kp=P(function(Ea){Object.defineProperty(Ea,"__esModule",{value:!0});var wS=hr(),Gp=je(),$a=D(),Vp=wa(),$S={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)Vp.default.code(new wS.KeywordCxt(s,Vp.default,"additionalProperties"));let o=(0,Gp.allSchemaProperties)(r);for(let c of o)s.definedProperties.add(c);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=$a.mergeEvaluated.props(t,(0,$a.toHash)(o),s.props);let a=o.filter((c)=>!(0,$a.alwaysValidSchema)(s,r[c]));if(a.length===0)return;let d=t.name("valid");for(let c of a){if(u(c))l(c);else{if(t.if((0,Gp.propertyInData)(t,n,c,s.opts.ownProperties)),l(c),!s.allErrors)t.else().var(d,!0);t.endIf()}e.it.definedProperties.add(c),e.ok(d)}function u(c){return s.opts.useDefaults&&!s.compositeRule&&r[c].default!==void 0}function l(c){e.subschema({keyword:"properties",schemaProp:c,dataProp:c},d)}}};Ea.default=$S});var Jp=P(function(Ia){Object.defineProperty(Ia,"__esModule",{value:!0});var zp=je(),Un=j(),Wp=D(),Hp=D(),ES={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,zp.allSchemaProperties)(r),d=a.filter((h)=>(0,Wp.alwaysValidSchema)(s,r[h]));if(a.length===0||d.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 Un.Name))s.props=(0,Hp.evaluatedPropsToName)(t,s.props);let{props:c}=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,Wp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Un._`${(0,zp.usePattern)(e,h)}.test(${g})`,()=>{let _=d.includes(h);if(!_)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Hp.Type.Str},l);if(s.opts.unevaluated&&c!==!0)t.assign(Un._`${c}[${g}]`,!0);else if(!_&&!s.allErrors)t.if((0,Un.not)(l),()=>t.break())})})}}};Ia.default=ES});var Qp=P(function(Sa){Object.defineProperty(Sa,"__esModule",{value:!0});var IS=D(),SS={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,IS.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"}};Sa.default=SS});var Yp=P(function(xa){Object.defineProperty(xa,"__esModule",{value:!0});var xS=je(),RS={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:xS.validateUnion,error:{message:"must match a schema in anyOf"}};xa.default=RS});var Xp=P(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var Bn=j(),CS=D(),OS={message:"must match exactly one schema in oneOf",params:({params:e})=>Bn._`{passingSchemas: ${e.passing}}`},jS={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:OS,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),d=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,c)=>{let p;if((0,CS.alwaysValidSchema)(n,l))t.var(d,!0);else p=e.subschema({keyword:"oneOf",schemaProp:c,compositeRule:!0},d);if(c>0)t.if(Bn._`${d} && ${o}`).assign(o,!1).assign(a,Bn._`[${a}, ${c}]`).else();t.if(d,()=>{if(t.assign(o,!0),t.assign(a,c),p)e.mergeEvaluated(p,Bn.Name)})})}}};Ra.default=jS});var Zp=P(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var FS=D(),TS={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,FS.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};Ca.default=TS});var rf=P(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var Gn=j(),tf=D(),kS={message:({params:e})=>Gn.str`must match "${e.ifClause}" schema`,params:({params:e})=>Gn._`{failingKeyword: ${e.ifClause}}`},AS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:kS,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,tf.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=ef(i,"then"),s=ef(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(d(),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,Gn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,c){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),c)t.assign(c,Gn._`${l}`);else e.setParams({ifClause:l})}}}};function ef(e,t){let r=e.schema[t];return r!==void 0&&!(0,tf.alwaysValidSchema)(e,r)}Oa.default=AS});var nf=P(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var DS=D(),NS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,DS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};ja.default=NS});var Ta=P(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var LS=ma(),qS=Ap(),MS=ha(),US=Np(),BS=Lp(),GS=Ln(),VS=Bp(),KS=wa(),zS=Kp(),WS=Jp(),HS=Qp(),JS=Yp(),QS=Xp(),YS=Zp(),XS=rf(),ZS=nf();function ex(e=!1){let t=[HS.default,JS.default,QS.default,YS.default,XS.default,ZS.default,VS.default,KS.default,GS.default,zS.default,WS.default];if(e)t.push(qS.default,US.default);else t.push(LS.default,MS.default);return t.push(BS.default),t}Fa.default=ex});var Aa=P(function(wi){Object.defineProperty(wi,"__esModule",{value:!0});wi.dynamicAnchor=void 0;var ka=j(),tx=Oe(),sf=ci(),rx=jn(),ix={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>of(e,e.schema)};function of(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=ka._`${tx.default.dynamicAnchors}${(0,ka.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:nx(e);r.if(ka._`!${n}`,()=>r.assign(n,s))}wi.dynamicAnchor=of;function nx(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:d}=i.opts,u=new sf.SchemaEnv({schema:r,schemaId:d,root:n,baseId:s,localRefs:o,meta:a});return sf.compileSchema.call(i,u),(0,rx.getValidate)(e,u)}wi.default=ix});var Da=P(function($i){Object.defineProperty($i,"__esModule",{value:!0});$i.dynamicRef=void 0;var af=j(),sx=Oe(),lf=jn(),ox={keyword:"$dynamicRef",schemaType:"string",code:(e)=>cf(e,e.schema)};function cf(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 d=r.let("valid",!1);o(d),e.ok(d)}function o(d){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",af._`${sx.default.dynamicAnchors}${(0,af.getProperty)(s)}`);r.if(u,a(u,d),a(n.validateName,d))}else a(n.validateName,d)()}function a(d,u){return u?()=>r.block(()=>{(0,lf.callRef)(e,d),r.let(u,!0)}):()=>(0,lf.callRef)(e,d)}}$i.dynamicRef=cf;$i.default=ox});var df=P(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var ax=Aa(),lx=D(),cx={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,ax.dynamicAnchor)(e,"");else(0,lx.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Na.default=cx});var uf=P(function(La){Object.defineProperty(La,"__esModule",{value:!0});var dx=Da(),ux={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,dx.dynamicRef)(e,e.schema)};La.default=ux});var pf=P(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var px=Aa(),fx=Da(),mx=df(),hx=uf(),gx=[px.default,fx.default,mx.default,hx.default];qa.default=gx});var mf=P(function(Ma){Object.defineProperty(Ma,"__esModule",{value:!0});var ff=Ln(),yx={keyword:"dependentRequired",type:"object",schemaType:"object",error:ff.error,code:(e)=>(0,ff.validatePropertyDeps)(e)};Ma.default=yx});var hf=P(function(Ua){Object.defineProperty(Ua,"__esModule",{value:!0});var _x=Ln(),bx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,_x.validateSchemaDeps)(e)};Ua.default=bx});var gf=P(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var Px=D(),vx={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,Px.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ba.default=vx});var yf=P(function(Ga){Object.defineProperty(Ga,"__esModule",{value:!0});var wx=mf(),$x=hf(),Ex=gf(),Ix=[wx.default,$x.default,Ex.default];Ga.default=Ix});var bf=P(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var Ct=j(),_f=D(),Sx=Oe(),xx={message:"must NOT have unevaluated properties",params:({params:e})=>Ct._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},Rx={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:xx,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 Ct.Name)t.if(Ct._`${a} !== true`,()=>t.forIn("key",i,(c)=>t.if(u(a,c),()=>d(c))));else if(a!==!0)t.forIn("key",i,(c)=>a===void 0?d(c):t.if(l(a,c),()=>d(c)));s.props=!0,e.ok(Ct._`${n} === ${Sx.default.errors}`);function d(c){if(r===!1){if(e.setParams({unevaluatedProperty:c}),e.error(),!o)t.break();return}if(!(0,_f.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:c,dataPropType:_f.Type.Str},p),!o)t.if((0,Ct.not)(p),()=>t.break())}}function u(c,p){return Ct._`!${c} || !${c}[${p}]`}function l(c,p){let f=[];for(let m in c)if(c[m]===!0)f.push(Ct._`${p} !== ${m}`);return(0,Ct.and)(...f)}}};Va.default=Rx});var vf=P(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});var Bt=j(),Pf=D(),Cx={message:({params:{len:e}})=>Bt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Bt._`{limit: ${e}}`},Ox={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Cx,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",Bt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Bt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,Pf.alwaysValidSchema)(n,r)){let d=t.var("valid",Bt._`${o} <= ${s}`);t.if((0,Bt.not)(d),()=>a(d,s)),e.ok(d)}n.items=!0;function a(d,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Pf.Type.Num},d),!n.allErrors)t.if((0,Bt.not)(d),()=>t.break())})}}};Ka.default=Ox});var wf=P(function(za){Object.defineProperty(za,"__esModule",{value:!0});var jx=bf(),Fx=vf(),Tx=[jx.default,Fx.default];za.default=Tx});var $f=P(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});var Q=j(),kx={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},Ax={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:kx,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:d,errSchemaPath:u,schemaEnv:l,self:c}=a;if(!d.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:c.formats,code:d.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),_=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(_,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(_,h)),e.fail$data((0,Q.or)(b(),v()));function b(){if(d.strictSchema===!1)return Q.nil;return Q._`${o} && !${_}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${_}(${i}) : ${_}(${i}))`:Q._`${_}(${i})`,I=Q._`(typeof ${_} == "function" ? ${w} : ${_}.test(${i}))`;return Q._`${_} && ${_} !== true && ${g} === ${t} && !${I}`}}function f(){let m=c.formats[s];if(!m){b();return}if(m===!0)return;let[h,g,_]=v(m);if(h===t)e.pass(w());function b(){if(d.strictSchema===!1){c.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):d.code.formats?Q._`${d.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 ${_}(${i})`}return typeof g=="function"?Q._`${_}(${i})`:Q._`${_}.test(${i})`}}}};Wa.default=Ax});var Ja=P(function(Ha){Object.defineProperty(Ha,"__esModule",{value:!0});var Dx=$f(),Nx=[Dx.default];Ha.default=Nx});var Qa=P(function(br){Object.defineProperty(br,"__esModule",{value:!0});br.contentVocabulary=br.metadataVocabulary=void 0;br.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];br.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var If=P(function(Ya){Object.defineProperty(Ya,"__esModule",{value:!0});var Lx=Qo(),qx=pa(),Mx=Ta(),Ux=pf(),Bx=yf(),Gx=wf(),Vx=Ja(),Ef=Qa(),Kx=[Ux.default,Lx.default,qx.default,(0,Mx.default)(!0),Vx.default,Ef.metadataVocabulary,Ef.contentVocabulary,Bx.default,Gx.default];Ya.default=Kx});var xf=P(function(Vn){Object.defineProperty(Vn,"__esModule",{value:!0});Vn.DiscrError=void 0;var Sf;(function(e){e.Tag="tag",e.Mapping="mapping"})(Sf||(Vn.DiscrError=Sf={}))});var el=P(function(Za){Object.defineProperty(Za,"__esModule",{value:!0});var Pr=j(),Xa=xf(),Rf=ci(),zx=gr(),Wx=D(),Hx={message:({params:{discrError:e,tagName:t}})=>e===Xa.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Pr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},Jx={keyword:"discriminator",type:"object",schemaType:"object",error:Hx,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 d=t.let("valid",!1),u=t.const("tag",Pr._`${r}${(0,Pr.getProperty)(a)}`);t.if(Pr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Xa.DiscrError.Tag,tag:u,tagName:a})),e.ok(d);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(Pr._`${u} === ${m}`),t.assign(d,c(f[m]));t.else(),e.error(!1,{discrError:Xa.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function c(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,Pr.Name),m}function p(){var f;let m={},h=_(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,Wx.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=Rf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof Rf.SchemaEnv)I=I.schema;if(I===void 0)throw new zx.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||_(I)),b(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function _({required:w}){return Array.isArray(w)&&w.includes(a)}function b(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}}}};Za.default=Jx});var Cf=P(function(_D,Qx){Qx.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 Of=P(function(bD,Yx){Yx.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 jf=P(function(PD,Xx){Xx.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 Ff=P(function(vD,Zx){Zx.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 Tf=P(function(wD,eR){eR.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 kf=P(function($D,tR){tR.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 Af=P(function(ED,rR){rR.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 Df=P(function(ID,iR){iR.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 Nf=P(function(tl){Object.defineProperty(tl,"__esModule",{value:!0});var nR=Cf(),sR=Of(),oR=jf(),aR=Ff(),lR=Tf(),cR=kf(),dR=Af(),uR=Df(),pR=["/properties"];function fR(e){return[nR,sR,oR,aR,lR,t(this,cR),dR,t(this,uR)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,pR):i}}tl.default=fR});var nl=P(function(z,il){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 mR=Wo(),hR=If(),gR=el(),yR=Nf(),rl="https://json-schema.org/draft/2020-12/schema";class Ei extends mR.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),hR.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(gR.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;yR.default.call(this,e),this.refs["http://json-schema.org/schema"]=rl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rl)?rl:void 0)}}z.Ajv2020=Ei;il.exports=z=Ei;il.exports.Ajv2020=Ei;Object.defineProperty(z,"__esModule",{value:!0});z.default=Ei;var _R=hr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return _R.KeywordCxt}});var vr=j();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var bR=ai();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return bR.default}});var PR=gr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return PR.default}})});var Fg=P(function(nt){Object.defineProperty(nt,"__esModule",{value:!0});nt.formatNames=nt.fastFormats=nt.fullFormats=void 0;function it(e,t){return{validate:e,compare:t}}nt.fullFormats={date:it(Rg,rc),time:it(ec(!0),ic),"date-time":it(Ig(!0),Og),"iso-time":it(ec(),Cg),"iso-date-time":it(Ig(),jg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Zj,"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:oF,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:eF,int32:{type:"number",validate:iF},int64:{type:"number",validate:nF},float:{type:"number",validate:xg},double:{type:"number",validate:xg},password:!0,binary:!0};nt.fastFormats={...nt.fullFormats,date:it(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,rc),time:it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ic),"date-time":it(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Og),"iso-time":it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Cg),"iso-date-time":it(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,jg),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};nt.formatNames=Object.keys(nt.fullFormats);function Hj(e){return e%4===0&&(e%100!==0||e%400===0)}var Jj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Qj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Rg(e){let t=Jj.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&&Hj(r)?29:Qj[i])}function rc(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Zl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ec(e){return function(r){let i=Zl.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],d=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 c=s-l*d,p=n-u*d-(c<0?1:0);return(p===23||p===-1)&&(c===59||c===-1)&&o<61}}function ic(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 Cg(e,t){if(!(e&&t))return;let r=Zl.exec(e),i=Zl.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 tc=/t|\s/i;function Ig(e){let t=ec(e);return function(i){let n=i.split(tc);return n.length===2&&Rg(n[0])&&t(n[1])}}function Og(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 jg(e,t){if(!(e&&t))return;let[r,i]=e.split(tc),[n,s]=t.split(tc),o=rc(r,n);if(o===void 0)return;return o||ic(i,s)}var Yj=/\/|:/,Xj=/^(?:[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 Zj(e){return Yj.test(e)&&Xj.test(e)}var Sg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eF(e){return Sg.lastIndex=0,Sg.test(e)}var tF=-2147483648,rF=2147483647;function iF(e){return Number.isInteger(e)&&e<=rF&&e>=tF}function nF(e){return Number.isInteger(e)}function xg(){return!0}var sF=/[^\\]\\Z/;function oF(e){if(sF.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var kg=P(function(nc){Object.defineProperty(nc,"__esModule",{value:!0});var aF=Qo(),lF=pa(),cF=Ta(),dF=Ja(),Tg=Qa(),uF=[aF.default,lF.default,(0,cF.default)(),dF.default,Tg.metadataVocabulary,Tg.contentVocabulary];nc.default=uF});var Ag=P(function(zM,pF){pF.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=P(function(W,sc){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 fF=Wo(),mF=kg(),hF=el(),Dg=Ag(),gF=["/properties"],Rs="http://json-schema.org/draft-07/schema";class Ki extends fF.default{_addVocabularies(){if(super._addVocabularies(),mF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(hF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Dg,gF):Dg;this.addMetaSchema(e,Rs,!1),this.refs["http://json-schema.org/schema"]=Rs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rs)?Rs:void 0)}}W.Ajv=Ki;sc.exports=W=Ki;sc.exports.Ajv=Ki;Object.defineProperty(W,"__esModule",{value:!0});W.default=Ki;var yF=hr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return yF.KeywordCxt}});var Lr=j();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Lr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Lr.CodeGen}});var _F=ai();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return _F.default}});var bF=gr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return bF.default}})});var Lg=P(function(qr){Object.defineProperty(qr,"__esModule",{value:!0});qr.formatLimitDefinition=void 0;var PF=Ng(),ze=j(),Tt=ze.operators,Cs={formatMaximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},formatMinimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},formatExclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},formatExclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},vF={message:({keyword:e,schemaCode:t})=>ze.str`should be ${Cs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>ze._`{comparison: ${Cs[e].okStr}, limit: ${t}}`};qr.formatLimitDefinition={keyword:Object.keys(Cs),type:"string",schemaType:"string",$data:!0,error:vF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let d=new PF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(d.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",ze._`${p}[${d.schemaCode}]`);e.fail$data((0,ze.or)(ze._`typeof ${f} != "object"`,ze._`${f} instanceof RegExp`,ze._`typeof ${f}.compare != "function"`,c(f)))}function l(){let p=d.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?ze._`${o.code.formats}${(0,ze.getProperty)(p)}`:void 0});e.fail$data(c(m))}function c(p){return ze._`${p}.compare(${r}, ${i}) ${Cs[n].fail} 0`}},dependencies:["format"]};var wF=(e)=>(e.addKeyword(qr.formatLimitDefinition),e);qr.default=wF});var Bg=P(function(zi,Ug){Object.defineProperty(zi,"__esModule",{value:!0});var Mr=Fg(),$F=Lg(),oc=j(),qg=new oc.Name("fullFormats"),EF=new oc.Name("fastFormats"),ac=(e,t={keywords:!0})=>{if(Array.isArray(t))return Mg(e,t,Mr.fullFormats,qg),e;let[r,i]=t.mode==="fast"?[Mr.fastFormats,EF]:[Mr.fullFormats,qg],n=t.formats||Mr.formatNames;if(Mg(e,n,r,i),t.keywords)(0,$F.default)(e);return e};ac.get=(e,t="full")=>{let i=(t==="fast"?Mr.fastFormats:Mr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function Mg(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=oc._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}Ug.exports=zi=ac;Object.defineProperty(zi,"__esModule",{value:!0});zi.default=ac});var jy=P(function(QU,Oy){Oy.exports=gT;function hT(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 gT(e){let t=hT(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 Qy=P(function(dB,Jy){var jT=require("stream");class Hy extends jT{#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)}}Jy.exports=Hy});class at 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 lt extends at{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class sn{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 lt(`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 on(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Xc=require("events"),ln=Ce(require("child_process")),He=Ce(require("path")),Yr=Ce(require("fs")),U=Ce(require("process")),Zc=require("util");var Hc=require("util");class an{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)=>on(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,c){return t.formatItem(l,r,c,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,c)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(c,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((c)=>n(t.styleOptionTerm(t.optionTerm(c)),t.styleOptionDescription(t.optionDescription(c))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,c)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(c,p,t))}),s.join(`
11
- `)}displayWidth(e){return Hc.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
- `+" ".repeat(t+a));return s+o+" ".repeat(a)+l.replace(/\n/g,`
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()],d=this.displayWidth(a[0]);o.forEach((u)=>{let l=this.displayWidth(u);if(d+l<=t){a.push(u),d+=l;return}n.push(a.join(""));let c=u.trimStart();a=[c],d=this.displayWidth(c)}),n.push(a.join(""))}),n.join(`
14
- `)}}class Qr{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=B_(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 lt(`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 Jc(this.name().replace(/^no-/,""));return Jc(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 Ks{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 Jc(e){return e.split("-").reduce((t,r)=>t+r[0].toUpperCase()+r.slice(1))}function B_(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}
10
+ deps: ${r}}`};var WS={keyword:"dependencies",type:"object",schemaType:"object",error:Ze.error,code(e){let[t,r]=HS(e);ef(e,t),tf(e,r)}};function HS({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function ef(e,t=e.schema){let{gen:r,data:n,it:i}=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 l=(0,wn.propertyInData)(r,n,o,i.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors)r.if(l,()=>{for(let d of a)(0,wn.checkReportMissingProp)(e,d)});else r.if(Ea._`${l} && (${(0,wn.checkMissingProp)(e,a,s)})`),(0,wn.reportMissingProp)(e,s),r.else()}}Ze.validatePropertyDeps=ef;function tf(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let a in t){if((0,KS.alwaysValidSchema)(s,t[a]))continue;r.if((0,wn.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=e.subschema({keyword:i,schemaProp:a},o);e.mergeValidEvaluated(l,o)},()=>r.var(o,!0)),e.ok(o)}}Ze.validateSchemaDeps=tf;Ze.default=WS});var nf=P(function(Sa){Object.defineProperty(Sa,"__esModule",{value:!0});var rf=O(),JS=D(),QS={message:"property name must be valid",params:({params:e})=>rf._`{propertyName: ${e.propertyName}}`},YS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:QS,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,JS.alwaysValidSchema)(i,r))return;let s=t.name("valid");t.forIn("key",n,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,rf.not)(s),()=>{if(e.error(!0),!i.allErrors)t.break()})}),e.ok(s)}};Sa.default=YS});var ja=P(function(xa){Object.defineProperty(xa,"__esModule",{value:!0});var Ui=Oe(),Be=O(),XS=Ce(),Bi=D(),ZS={message:"must NOT have additional properties",params:({params:e})=>Be._`{additionalProperty: ${e.additionalProperty}}`},ex={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ZS,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Bi.alwaysValidSchema)(o,r))return;let d=(0,Ui.allSchemaProperties)(n.properties),c=(0,Ui.allSchemaProperties)(n.patternProperties);p(),e.ok(Be._`${s} === ${XS.default.errors}`);function p(){t.forIn("key",i,(g)=>{if(!d.length&&!c.length)f(g);else t.if(h(g),()=>f(g))})}function h(g){let y;if(d.length>8){let b=(0,Bi.schemaRefOrVal)(o,n.properties,"properties");y=(0,Ui.isOwnProperty)(t,b,g)}else if(d.length)y=(0,Be.or)(...d.map((b)=>Be._`${g} === ${b}`));else y=Be.nil;if(c.length)y=(0,Be.or)(y,...c.map((b)=>Be._`${(0,Ui.usePattern)(e,b)}.test(${g})`));return(0,Be.not)(y)}function u(g){t.code(Be._`delete ${i}[${g}]`)}function f(g){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){u(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,Bi.alwaysValidSchema)(o,r)){let y=t.name("valid");if(l.removeAdditional==="failing")m(g,y,!1),t.if((0,Be.not)(y),()=>{e.reset(),u(g)});else if(m(g,y),!a)t.if((0,Be.not)(y),()=>t.break())}}function m(g,y,b){let v={keyword:"additionalProperties",dataProp:g,dataPropType:Bi.Type.Str};if(b===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,y)}}};xa.default=ex});var af=P(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var tx=gr(),sf=Oe(),Ra=D(),of=ja(),rx={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e;if(s.opts.removeAdditional==="all"&&n.additionalProperties===void 0)of.default.code(new tx.KeywordCxt(s,of.default,"additionalProperties"));let o=(0,sf.allSchemaProperties)(r);for(let p of o)s.definedProperties.add(p);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=Ra.mergeEvaluated.props(t,(0,Ra.toHash)(o),s.props);let a=o.filter((p)=>!(0,Ra.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let l=t.name("valid");for(let p of a){if(d(p))c(p);else{if(t.if((0,sf.propertyInData)(t,i,p,s.opts.ownProperties)),c(p),!s.allErrors)t.else().var(l,!0);t.endIf()}e.it.definedProperties.add(p),e.ok(l)}function d(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function c(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},l)}}};Ca.default=rx});var uf=P(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var lf=Oe(),Gi=O(),df=D(),cf=D(),nx={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:s}=e,{opts:o}=s,a=(0,lf.allSchemaProperties)(r),l=a.filter((m)=>(0,df.alwaysValidSchema)(s,r[m]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let d=o.strictSchema&&!o.allowMatchingProperties&&i.properties,c=t.name("valid");if(s.props!==!0&&!(s.props instanceof Gi.Name))s.props=(0,cf.evaluatedPropsToName)(t,s.props);let{props:p}=s;h();function h(){for(let m of a){if(d)u(m);if(s.allErrors)f(m);else t.var(c,!0),f(m),t.if(c)}}function u(m){for(let g in d)if(new RegExp(m).test(g))(0,df.checkStrictMode)(s,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function f(m){t.forIn("key",n,(g)=>{t.if(Gi._`${(0,lf.usePattern)(e,m)}.test(${g})`,()=>{let y=l.includes(m);if(!y)e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:cf.Type.Str},c);if(s.opts.unevaluated&&p!==!0)t.assign(Gi._`${p}[${g}]`,!0);else if(!y&&!s.allErrors)t.if((0,Gi.not)(c),()=>t.break())})})}}};Oa.default=nx});var pf=P(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var ix=D(),sx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,ix.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Fa.default=sx});var ff=P(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});var ox=Oe(),ax={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:ox.validateUnion,error:{message:"must match a schema in anyOf"}};Ta.default=ax});var mf=P(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});var Vi=O(),lx=D(),dx={message:"must match exactly one schema in oneOf",params:({params:e})=>Vi._`{passingSchemas: ${e.passing}}`},cx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:dx,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),l=t.name("_valid");e.setParams({passing:a}),t.block(d),e.result(o,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((c,p)=>{let h;if((0,lx.alwaysValidSchema)(i,c))t.var(l,!0);else h=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},l);if(p>0)t.if(Vi._`${l} && ${o}`).assign(o,!1).assign(a,Vi._`[${a}, ${p}]`).else();t.if(l,()=>{if(t.assign(o,!0),t.assign(a,p),h)e.mergeEvaluated(h,Vi.Name)})})}}};Aa.default=cx});var hf=P(function(ka){Object.defineProperty(ka,"__esModule",{value:!0});var ux=D(),px={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let i=t.name("valid");r.forEach((s,o)=>{if((0,ux.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(a)})}};ka.default=px});var _f=P(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});var zi=O(),yf=D(),fx={message:({params:e})=>zi.str`must match "${e.ifClause}" schema`,params:({params:e})=>zi._`{failingKeyword: ${e.ifClause}}`},mx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:fx,code(e){let{gen:t,parentSchema:r,it:n}=e;if(r.then===void 0&&r.else===void 0)(0,yf.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=gf(n,"then"),s=gf(n,"else");if(!i&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(l(),e.reset(),i&&s){let c=t.let("ifClause");e.setParams({ifClause:c}),t.if(a,d("then",c),d("else",c))}else if(i)t.if(a,d("then"));else t.if((0,zi.not)(a),d("else"));e.pass(o,()=>e.error(!0));function l(){let c=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(c)}function d(c,p){return()=>{let h=e.subschema({keyword:c},a);if(t.assign(o,a),e.mergeValidEvaluated(h,o),p)t.assign(p,zi._`${c}`);else e.setParams({ifClause:c})}}}};function gf(e,t){let r=e.schema[t];return r!==void 0&&!(0,yf.alwaysValidSchema)(e,r)}Da.default=mx});var bf=P(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var hx=D(),gx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,hx.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Na.default=gx});var La=P(function(Ma){Object.defineProperty(Ma,"__esModule",{value:!0});var yx=Pa(),_x=Qp(),bx=va(),Px=Xp(),vx=Zp(),wx=qi(),$x=nf(),Ix=ja(),Ex=af(),Sx=uf(),xx=pf(),jx=ff(),Rx=mf(),Cx=hf(),Ox=_f(),Fx=bf();function Tx(e=!1){let t=[xx.default,jx.default,Rx.default,Cx.default,Ox.default,Fx.default,$x.default,Ix.default,wx.default,Ex.default,Sx.default];if(e)t.push(_x.default,Px.default);else t.push(yx.default,bx.default);return t.push(vx.default),t}Ma.default=Tx});var Ua=P(function($n){Object.defineProperty($n,"__esModule",{value:!0});$n.dynamicAnchor=void 0;var qa=O(),Ax=Ce(),Pf=cn(),kx=Ti(),Dx={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>vf(e,e.schema)};function vf(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let i=qa._`${Ax.default.dynamicAnchors}${(0,qa.getProperty)(t)}`,s=n.errSchemaPath==="#"?n.validateName:Nx(e);r.if(qa._`!${i}`,()=>r.assign(i,s))}$n.dynamicAnchor=vf;function Nx(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:i,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:l}=n.opts,d=new Pf.SchemaEnv({schema:r,schemaId:l,root:i,baseId:s,localRefs:o,meta:a});return Pf.compileSchema.call(n,d),(0,kx.getValidate)(e,d)}$n.default=Dx});var Ba=P(function(In){Object.defineProperty(In,"__esModule",{value:!0});In.dynamicRef=void 0;var wf=O(),Mx=Ce(),$f=Ti(),Lx={keyword:"$dynamicRef",schemaType:"string",code:(e)=>If(e,e.schema)};function If(e,t){let{gen:r,keyword:n,it:i}=e;if(t[0]!=="#")throw Error(`"${n}" only supports hash fragment reference`);let s=t.slice(1);if(i.allErrors)o();else{let l=r.let("valid",!1);o(l),e.ok(l)}function o(l){if(i.schemaEnv.root.dynamicAnchors[s]){let d=r.let("_v",wf._`${Mx.default.dynamicAnchors}${(0,wf.getProperty)(s)}`);r.if(d,a(d,l),a(i.validateName,l))}else a(i.validateName,l)()}function a(l,d){return d?()=>r.block(()=>{(0,$f.callRef)(e,l),r.let(d,!0)}):()=>(0,$f.callRef)(e,l)}}In.dynamicRef=If;In.default=Lx});var Ef=P(function(Ga){Object.defineProperty(Ga,"__esModule",{value:!0});var qx=Ua(),Ux=D(),Bx={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,qx.dynamicAnchor)(e,"");else(0,Ux.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ga.default=Bx});var Sf=P(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var Gx=Ba(),Vx={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,Gx.dynamicRef)(e,e.schema)};Va.default=Vx});var xf=P(function(za){Object.defineProperty(za,"__esModule",{value:!0});var zx=Ua(),Kx=Ba(),Wx=Ef(),Hx=Sf(),Jx=[zx.default,Kx.default,Wx.default,Hx.default];za.default=Jx});var Rf=P(function(Ka){Object.defineProperty(Ka,"__esModule",{value:!0});var jf=qi(),Qx={keyword:"dependentRequired",type:"object",schemaType:"object",error:jf.error,code:(e)=>(0,jf.validatePropertyDeps)(e)};Ka.default=Qx});var Cf=P(function(Wa){Object.defineProperty(Wa,"__esModule",{value:!0});var Yx=qi(),Xx={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,Yx.validateSchemaDeps)(e)};Wa.default=Xx});var Of=P(function(Ha){Object.defineProperty(Ha,"__esModule",{value:!0});var Zx=D(),ej={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,Zx.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ha.default=ej});var Ff=P(function(Ja){Object.defineProperty(Ja,"__esModule",{value:!0});var tj=Rf(),rj=Cf(),nj=Of(),ij=[tj.default,rj.default,nj.default];Ja.default=ij});var Af=P(function(Qa){Object.defineProperty(Qa,"__esModule",{value:!0});var Rt=O(),Tf=D(),sj=Ce(),oj={message:"must NOT have unevaluated properties",params:({params:e})=>Rt._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},aj={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:oj,code(e){let{gen:t,schema:r,data:n,errsCount:i,it:s}=e;if(!i)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof Rt.Name)t.if(Rt._`${a} !== true`,()=>t.forIn("key",n,(p)=>t.if(d(a,p),()=>l(p))));else if(a!==!0)t.forIn("key",n,(p)=>a===void 0?l(p):t.if(c(a,p),()=>l(p)));s.props=!0,e.ok(Rt._`${i} === ${sj.default.errors}`);function l(p){if(r===!1){if(e.setParams({unevaluatedProperty:p}),e.error(),!o)t.break();return}if(!(0,Tf.alwaysValidSchema)(s,r)){let h=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:Tf.Type.Str},h),!o)t.if((0,Rt.not)(h),()=>t.break())}}function d(p,h){return Rt._`!${p} || !${p}[${h}]`}function c(p,h){let u=[];for(let f in p)if(p[f]===!0)u.push(Rt._`${h} !== ${f}`);return(0,Rt.and)(...u)}}};Qa.default=aj});var Df=P(function(Ya){Object.defineProperty(Ya,"__esModule",{value:!0});var Bt=O(),kf=D(),lj={message:({params:{len:e}})=>Bt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Bt._`{limit: ${e}}`},dj={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:lj,code(e){let{gen:t,schema:r,data:n,it:i}=e,s=i.items||0;if(s===!0)return;let o=t.const("len",Bt._`${n}.length`);if(r===!1)e.setParams({len:s}),e.fail(Bt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,kf.alwaysValidSchema)(i,r)){let l=t.var("valid",Bt._`${o} <= ${s}`);t.if((0,Bt.not)(l),()=>a(l,s)),e.ok(l)}i.items=!0;function a(l,d){t.forRange("i",d,o,(c)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:c,dataPropType:kf.Type.Num},l),!i.allErrors)t.if((0,Bt.not)(l),()=>t.break())})}}};Ya.default=dj});var Nf=P(function(Xa){Object.defineProperty(Xa,"__esModule",{value:!0});var cj=Af(),uj=Df(),pj=[cj.default,uj.default];Xa.default=pj});var Mf=P(function(Za){Object.defineProperty(Za,"__esModule",{value:!0});var Y=O(),fj={message:({schemaCode:e})=>Y.str`must match format "${e}"`,params:({schemaCode:e})=>Y._`{format: ${e}}`},mj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:fj,code(e,t){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=e,{opts:l,errSchemaPath:d,schemaEnv:c,self:p}=a;if(!l.validateFormats)return;if(i)h();else u();function h(){let f=r.scopeValue("formats",{ref:p.formats,code:l.code.formats}),m=r.const("fDef",Y._`${f}[${o}]`),g=r.let("fType"),y=r.let("format");r.if(Y._`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,Y._`${m}.type || "string"`).assign(y,Y._`${m}.validate`),()=>r.assign(g,Y._`"string"`).assign(y,m)),e.fail$data((0,Y.or)(b(),v()));function b(){if(l.strictSchema===!1)return Y.nil;return Y._`${o} && !${y}`}function v(){let I=c.$async?Y._`(${m}.async ? await ${y}(${n}) : ${y}(${n}))`:Y._`${y}(${n})`,E=Y._`(typeof ${y} == "function" ? ${I} : ${y}.test(${n}))`;return Y._`${y} && ${y} !== true && ${g} === ${t} && !${E}`}}function u(){let f=p.formats[s];if(!f){b();return}if(f===!0)return;let[m,g,y]=v(f);if(m===t)e.pass(I());function b(){if(l.strictSchema===!1){p.logger.warn(E());return}throw Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${d}"`}}function v(E){let w=E instanceof RegExp?(0,Y.regexpCode)(E):l.code.formats?Y._`${l.code.formats}${(0,Y.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:E,code:w});if(typeof E=="object"&&!(E instanceof RegExp))return[E.type||"string",E.validate,Y._`${x}.validate`];return["string",E,x]}function I(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!c.$async)throw Error("async format in sync schema");return Y._`await ${y}(${n})`}return typeof g=="function"?Y._`${y}(${n})`:Y._`${y}.test(${n})`}}}};Za.default=mj});var tl=P(function(el){Object.defineProperty(el,"__esModule",{value:!0});var hj=Mf(),gj=[hj.default];el.default=gj});var rl=P(function(Pr){Object.defineProperty(Pr,"__esModule",{value:!0});Pr.contentVocabulary=Pr.metadataVocabulary=void 0;Pr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Pr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var qf=P(function(nl){Object.defineProperty(nl,"__esModule",{value:!0});var yj=ra(),_j=_a(),bj=La(),Pj=xf(),vj=Ff(),wj=Nf(),$j=tl(),Lf=rl(),Ij=[Pj.default,yj.default,_j.default,(0,bj.default)(!0),$j.default,Lf.metadataVocabulary,Lf.contentVocabulary,vj.default,wj.default];nl.default=Ij});var Bf=P(function(Ki){Object.defineProperty(Ki,"__esModule",{value:!0});Ki.DiscrError=void 0;var Uf;(function(e){e.Tag="tag",e.Mapping="mapping"})(Uf||(Ki.DiscrError=Uf={}))});var ol=P(function(sl){Object.defineProperty(sl,"__esModule",{value:!0});var vr=O(),il=Bf(),Gf=cn(),Ej=yr(),Sj=D(),xj={message:({params:{discrError:e,tagName:t}})=>e===il.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>vr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},jj={keyword:"discriminator",type:"object",schemaType:"object",error:xj,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let l=t.let("valid",!1),d=t.const("tag",vr._`${r}${(0,vr.getProperty)(a)}`);t.if(vr._`typeof ${d} == "string"`,()=>c(),()=>e.error(!1,{discrError:il.DiscrError.Tag,tag:d,tagName:a})),e.ok(l);function c(){let u=h();t.if(!1);for(let f in u)t.elseIf(vr._`${d} === ${f}`),t.assign(l,p(u[f]));t.else(),e.error(!1,{discrError:il.DiscrError.Mapping,tag:d,tagName:a}),t.endIf()}function p(u){let f=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:u},f);return e.mergeEvaluated(m,vr.Name),f}function h(){var u;let f={},m=y(i),g=!0;for(let I=0;I<o.length;I++){let E=o[I];if((E===null||E===void 0?void 0:E.$ref)&&!(0,Sj.schemaHasRulesButRef)(E,s.self.RULES)){let x=E.$ref;if(E=Gf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),E instanceof Gf.SchemaEnv)E=E.schema;if(E===void 0)throw new Ej.default(s.opts.uriResolver,s.baseId,x)}let w=(u=E===null||E===void 0?void 0:E.properties)===null||u===void 0?void 0:u[a];if(typeof w!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||y(E)),b(w,I)}if(!g)throw Error(`discriminator: "${a}" must be required`);return f;function y({required:I}){return Array.isArray(I)&&I.includes(a)}function b(I,E){if(I.const)v(I.const,E);else if(I.enum)for(let w of I.enum)v(w,E);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(I,E){if(typeof I!="string"||I in f)throw Error(`discriminator: "${a}" values must be unique strings`);f[I]=E}}}};sl.default=jj});var Vf=P(function(rN,Rj){Rj.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 zf=P(function(nN,Cj){Cj.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 Kf=P(function(iN,Oj){Oj.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 Wf=P(function(sN,Fj){Fj.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 Hf=P(function(oN,Tj){Tj.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 Jf=P(function(aN,Aj){Aj.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 Qf=P(function(lN,kj){kj.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 Yf=P(function(dN,Dj){Dj.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 Xf=P(function(al){Object.defineProperty(al,"__esModule",{value:!0});var Nj=Vf(),Mj=zf(),Lj=Kf(),qj=Wf(),Uj=Hf(),Bj=Jf(),Gj=Qf(),Vj=Yf(),zj=["/properties"];function Kj(e){return[Nj,Mj,Lj,qj,Uj,t(this,Bj),Gj,t(this,Vj)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,zj):n}}al.default=Kj});var cl=P(function(W,dl){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv2020=void 0;var Wj=Zo(),Hj=qf(),Jj=ol(),Qj=Xf(),ll="https://json-schema.org/draft/2020-12/schema";class En extends Wj.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),Hj.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(Jj.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;Qj.default.call(this,e),this.refs["http://json-schema.org/schema"]=ll}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ll)?ll:void 0)}}W.Ajv2020=En;dl.exports=W=En;dl.exports.Ajv2020=En;Object.defineProperty(W,"__esModule",{value:!0});W.default=En;var Yj=gr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return Yj.KeywordCxt}});var wr=O();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return wr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return wr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return wr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return wr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return wr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return wr.CodeGen}});var Xj=ln();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return Xj.default}});var Zj=yr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return Zj.default}})});var Wg=P(function(st){Object.defineProperty(st,"__esModule",{value:!0});st.formatNames=st.fastFormats=st.fullFormats=void 0;function it(e,t){return{validate:e,compare:t}}st.fullFormats={date:it(Gg,ld),time:it(od(!0),dd),"date-time":it(qg(!0),zg),"iso-time":it(od(),Vg),"iso-date-time":it(qg(),Kg),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:LF,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:TF,int32:{type:"number",validate:DF},int64:{type:"number",validate:NF},float:{type:"number",validate:Bg},double:{type:"number",validate:Bg},password:!0,binary:!0};st.fastFormats={...st.fullFormats,date:it(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ld),time:it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,dd),"date-time":it(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zg),"iso-time":it(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Vg),"iso-date-time":it(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Kg),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};st.formatNames=Object.keys(st.fullFormats);function xF(e){return e%4===0&&(e%100!==0||e%400===0)}var jF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,RF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gg(e){let t=jF.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],i=+t[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&xF(r)?29:RF[n])}function ld(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var sd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function od(e){return function(r){let n=sd.exec(r);if(!n)return!1;let i=+n[1],s=+n[2],o=+n[3],a=n[4],l=n[5]==="-"?-1:1,d=+(n[6]||0),c=+(n[7]||0);if(d>23||c>59||e&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let p=s-c*l,h=i-d*l-(p<0?1:0);return(h===23||h===-1)&&(p===59||p===-1)&&o<61}}function dd(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(!(r&&n))return;return r-n}function Vg(e,t){if(!(e&&t))return;let r=sd.exec(e),n=sd.exec(t);if(!(r&&n))return;if(e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t)return 1;if(e<t)return-1;return 0}var ad=/t|\s/i;function qg(e){let t=od(e);return function(n){let i=n.split(ad);return i.length===2&&Gg(i[0])&&t(i[1])}}function zg(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(!(r&&n))return;return r-n}function Kg(e,t){if(!(e&&t))return;let[r,n]=e.split(ad),[i,s]=t.split(ad),o=ld(r,i);if(o===void 0)return;return o||dd(n,s)}var CF=/\/|:/,OF=/^(?:[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 CF.test(e)&&OF.test(e)}var Ug=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function TF(e){return Ug.lastIndex=0,Ug.test(e)}var AF=-2147483648,kF=2147483647;function DF(e){return Number.isInteger(e)&&e<=kF&&e>=AF}function NF(e){return Number.isInteger(e)}function Bg(){return!0}var MF=/[^\\]\\Z/;function LF(e){if(MF.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var Jg=P(function(cd){Object.defineProperty(cd,"__esModule",{value:!0});var qF=ra(),UF=_a(),BF=La(),GF=tl(),Hg=rl(),VF=[qF.default,UF.default,(0,BF.default)(),GF.default,Hg.metadataVocabulary,Hg.contentVocabulary];cd.default=VF});var Qg=P(function(CU,zF){zF.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 Xg=P(function(H,ud){Object.defineProperty(H,"__esModule",{value:!0});H.MissingRefError=H.ValidationError=H.CodeGen=H.Name=H.nil=H.stringify=H.str=H._=H.KeywordCxt=H.Ajv=void 0;var KF=Zo(),WF=Jg(),HF=ol(),Yg=Qg(),JF=["/properties"],Cs="http://json-schema.org/draft-07/schema";class Kn extends KF.default{_addVocabularies(){if(super._addVocabularies(),WF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(HF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Yg,JF):Yg;this.addMetaSchema(e,Cs,!1),this.refs["http://json-schema.org/schema"]=Cs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Cs)?Cs:void 0)}}H.Ajv=Kn;ud.exports=H=Kn;ud.exports.Ajv=Kn;Object.defineProperty(H,"__esModule",{value:!0});H.default=Kn;var QF=gr();Object.defineProperty(H,"KeywordCxt",{enumerable:!0,get:function(){return QF.KeywordCxt}});var Lr=O();Object.defineProperty(H,"_",{enumerable:!0,get:function(){return Lr._}});Object.defineProperty(H,"str",{enumerable:!0,get:function(){return Lr.str}});Object.defineProperty(H,"stringify",{enumerable:!0,get:function(){return Lr.stringify}});Object.defineProperty(H,"nil",{enumerable:!0,get:function(){return Lr.nil}});Object.defineProperty(H,"Name",{enumerable:!0,get:function(){return Lr.Name}});Object.defineProperty(H,"CodeGen",{enumerable:!0,get:function(){return Lr.CodeGen}});var YF=ln();Object.defineProperty(H,"ValidationError",{enumerable:!0,get:function(){return YF.default}});var XF=yr();Object.defineProperty(H,"MissingRefError",{enumerable:!0,get:function(){return XF.default}})});var Zg=P(function(qr){Object.defineProperty(qr,"__esModule",{value:!0});qr.formatLimitDefinition=void 0;var ZF=Xg(),Ke=O(),Tt=Ke.operators,Os={formatMaximum:{okStr:"<=",ok:Tt.LTE,fail:Tt.GT},formatMinimum:{okStr:">=",ok:Tt.GTE,fail:Tt.LT},formatExclusiveMaximum:{okStr:"<",ok:Tt.LT,fail:Tt.GTE},formatExclusiveMinimum:{okStr:">",ok:Tt.GT,fail:Tt.LTE}},eT={message:({keyword:e,schemaCode:t})=>Ke.str`should be ${Os[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Ke._`{comparison: ${Os[e].okStr}, limit: ${t}}`};qr.formatLimitDefinition={keyword:Object.keys(Os),type:"string",schemaType:"string",$data:!0,error:eT,code(e){let{gen:t,data:r,schemaCode:n,keyword:i,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let l=new ZF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(l.$data)d();else c();function d(){let h=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),u=t.const("fmt",Ke._`${h}[${l.schemaCode}]`);e.fail$data((0,Ke.or)(Ke._`typeof ${u} != "object"`,Ke._`${u} instanceof RegExp`,Ke._`typeof ${u}.compare != "function"`,p(u)))}function c(){let h=l.schema,u=a.formats[h];if(!u||u===!0)return;if(typeof u!="object"||u instanceof RegExp||typeof u.compare!="function")throw Error(`"${i}": format "${h}" does not define "compare" function`);let f=t.scopeValue("formats",{key:h,ref:u,code:o.code.formats?Ke._`${o.code.formats}${(0,Ke.getProperty)(h)}`:void 0});e.fail$data(p(f))}function p(h){return Ke._`${h}.compare(${r}, ${n}) ${Os[i].fail} 0`}},dependencies:["format"]};var tT=(e)=>(e.addKeyword(qr.formatLimitDefinition),e);qr.default=tT});var ny=P(function(Wn,ry){Object.defineProperty(Wn,"__esModule",{value:!0});var Ur=Wg(),rT=Zg(),pd=O(),ey=new pd.Name("fullFormats"),nT=new pd.Name("fastFormats"),fd=(e,t={keywords:!0})=>{if(Array.isArray(t))return ty(e,t,Ur.fullFormats,ey),e;let[r,n]=t.mode==="fast"?[Ur.fastFormats,nT]:[Ur.fullFormats,ey],i=t.formats||Ur.formatNames;if(ty(e,i,r,n),t.keywords)(0,rT.default)(e);return e};fd.get=(e,t="full")=>{let n=(t==="fast"?Ur.fastFormats:Ur.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function ty(e,t,r,n){var i,s;(i=(s=e.opts.code).formats)!==null&&i!==void 0||(s.formats=pd._`require("ajv-formats/dist/formats").${n}`);for(let o of t)e.addFormat(o,r[o])}ry.exports=Wn=fd;Object.defineProperty(Wn,"__esModule",{value:!0});Wn.default=fd});var t_=P(function(DB,e_){e_.exports=eA;function ZT(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 eA(e){let t=ZT(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 P_=P(function(QB,b_){var hA=require("stream");class __ extends hA{#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)}}b_.exports=__});class lt 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 dt extends lt{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class ai{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 dt(`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 li(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var oc=require("events"),ci=Re(require("child_process")),He=Re(require("path")),Yr=Re(require("fs")),U=Re(require("process")),ac=require("util");var rc=require("util");class di{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((n)=>!n._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((n,i)=>n.name().localeCompare(i.name()));return t}compareOptions(e,t){let r=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((n)=>!n.hidden),r=e._getHelpOption();if(r&&!r.hidden){let n=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);if(!n&&!i)t.push(r);else if(r.long&&!i)t.push(e.createOption(r.long,r.description));else if(r.short&&!n)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 n=r.options.filter((i)=>!i.hidden);t.push(...n)}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)=>li(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,n)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,n)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,n)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,n)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let n=e.parent;n;n=n.parent)r=n.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 n=new Map;return e.forEach((i)=>{let s=r(i);if(!n.has(s))n.set(s,[])}),t.forEach((i)=>{let s=r(i);if(!n.has(s))n.set(s,[]);n.get(s).push(i)}),n}formatHelp(e,t){let r=t.padWidth(e,t),n=t.helpWidth??80;function i(c,p){return t.formatItem(c,r,p,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),n),""]);let a=t.visibleArguments(e).map((c)=>i(t.styleArgumentTerm(t.argumentTerm(c)),t.styleArgumentDescription(t.argumentDescription(c))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(c)=>c.helpGroupHeading??"Options:").forEach((c,p)=>{let h=c.map((u)=>i(t.styleOptionTerm(t.optionTerm(u)),t.styleOptionDescription(t.optionDescription(u))));s=s.concat(this.formatItemList(p,h,t))}),t.showGlobalOptions){let c=t.visibleGlobalOptions(e).map((p)=>i(t.styleOptionTerm(t.optionTerm(p)),t.styleOptionDescription(t.optionDescription(p))));s=s.concat(this.formatItemList("Global Options:",c,t))}return this.groupItems(e.commands,t.visibleCommands(e),(c)=>c.helpGroup()||"Commands:").forEach((c,p)=>{let h=c.map((u)=>i(t.styleSubcommandTerm(t.subcommandTerm(u)),t.styleSubcommandDescription(t.subcommandDescription(u))));s=s.concat(this.formatItemList(p,h,t))}),s.join(`
11
+ `)}displayWidth(e){return rc.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,n){let s=" ".repeat(2);if(!r)return s+e;let o=e.padEnd(t+e.length-n.displayWidth(e)),a=2,d=(this.helpWidth??80)-t-a-2,c;if(d<this.minWidthToWrap||n.preformatted(r))c=r;else c=n.boxWrap(r,d).replace(/\n/g,`
12
+ `+" ".repeat(t+a));return s+o+" ".repeat(a)+c.replace(/\n/g,`
13
+ ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,i=[];return r.forEach((s)=>{let o=s.match(n);if(o===null){i.push("");return}let a=[o.shift()],l=this.displayWidth(a[0]);o.forEach((d)=>{let c=this.displayWidth(d);if(l+c<=t){a.push(d),l+=c;return}i.push(a.join(""));let p=d.trimStart();a=[p],l=this.displayWidth(p)}),i.push(a.join(""))}),i.join(`
14
+ `)}}class Qr{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=pb(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 dt(`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 nc(this.name().replace(/^no-/,""));return nc(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 Js{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 n=this.negativeOptions.get(r).presetArg,i=n!==void 0?n:!1;return t.negate===(i===e)}}function nc(e){return e.split("-").reduce((t,r)=>t+r[0].toUpperCase()+r.slice(1))}function pb(e){let t,r,n=/^-[^-]$/,i=/^--[^-]/,s=e.split(/[ |,]+/).concat("guard");if(n.test(s[0]))t=s.shift();if(i.test(s[0]))r=s.shift();if(!t&&n.test(s[0]))t=s.shift();if(!t&&i.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
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(i.test(o))throw Error(`${a}
18
- - too many short flags`);if(n.test(o))throw Error(`${a}
17
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${a}
18
+ - too many short flags`);if(i.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 G_(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 zs(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=G_(e,o),d=Math.max(e.length,o.length);if((d-a)/d>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
- (Did you mean one of ${i.join(", ")}?)`;if(i.length===1)return`
22
- (Did you mean ${i[0]}?)`;return""}class sr extends Xc.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:()=>Yc()??(U.default.stdout.isTTY&&U.default.stdout.hasColors?.()),getErrHasColors:()=>Yc()??(U.default.stderr.isTTY&&U.default.stderr.hasColors?.()),stripColor:(t)=>Zc.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 sr(e)}createHelp(){return Object.assign(new an,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
- - 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 sn(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 at(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 Qr(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
- - 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 Qr)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,d)=>{let u=o.exec(a);return u?u[0]:d},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
- - 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(Yr.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
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 fb(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let r=[];for(let n=0;n<=e.length;n++)r[n]=[n];for(let n=0;n<=t.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let i=1;i<=e.length;i++){let s;if(e[i-1]===t[n-1])s=0;else s=1;if(r[i][n]=Math.min(r[i-1][n]+1,r[i][n-1]+1,r[i-1][n-1]+s),i>1&&n>1&&e[i-1]===t[n-2]&&e[i-2]===t[n-1])r[i][n]=Math.min(r[i][n],r[i-2][n-2]+1)}return r[e.length][t.length]}function Qs(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 n=[],i=3,s=0.4;if(t.forEach((o)=>{if(o.length<=1)return;let a=fb(e,o),l=Math.max(e.length,o.length);if((l-a)/l>s){if(a<i)i=a,n=[o];else if(a===i)n.push(o)}}),n.sort((o,a)=>o.localeCompare(a)),r)n=n.map((o)=>`--${o}`);if(n.length>1)return`
21
+ (Did you mean one of ${n.join(", ")}?)`;if(n.length===1)return`
22
+ (Did you mean ${n[0]}?)`;return""}class or extends oc.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:()=>sc()??(U.default.stdout.isTTY&&U.default.stdout.hasColors?.()),getErrHasColors:()=>sc()??(U.default.stderr.isTTY&&U.default.stderr.hasColors?.()),stripColor:(t)=>ac.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 n=t,i=r;if(typeof n==="object"&&n!==null)i=n,n=null;i=i||{};let[,s,o]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(n)a.description(n),a._executableHandler=!0;if(i.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,o)a.arguments(o);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),n)return this;return a}createCommand(e){return new or(e)}createHelp(){return Object.assign(new di,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
+ - 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 ai(e,t)}argument(e,t,r,n){let i=this.createArgument(e,t);if(typeof r==="function")i.default(n).argParser(r);else i.default(r);return this.addArgument(i),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]",[,n,i]=r.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(n);if(o.helpOption(!1),i)o.arguments(i);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 lt(e,t,r));U.default.exit(e)}action(e){let t=(r)=>{let n=this.registeredArguments.length,i=r.slice(0,n);if(this._storeOptionsAsProperties)i[n]=this;else i[n]=this.opts();return i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Qr(e,t)}_callParseArg(e,t,r,n){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let s=`${n} ${i.message}`;this.error(s,{exitCode:i.exitCode,code:i.code})}throw i}}_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
+ - already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(n)=>[n.name()].concat(n.aliases()),r=t(e).find((n)=>this._findCommand(n));if(r){let n=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw Error(`cannot add command '${i}' as already have command '${n}'`)}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 n=(i,s,o)=>{if(i==null&&e.presetArg!==void 0)i=e.presetArg;let a=this.getOptionValue(r);if(i!==null&&e.parseArg)i=this._callParseArg(e,i,a,s);else if(i!==null&&e.variadic)i=e._collectValue(i,a);if(i==null)if(e.negate)i=!1;else if(e.isBoolean()||e.optional)i=!0;else i="";this.setOptionValueWithSource(r,i,o)};if(this.on("option:"+t,(i)=>{let s=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(i)=>{let s=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,s,"env")});return this}_optionEx(e,t,r,n,i){if(typeof t==="object"&&t instanceof Qr)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 n==="function")s.default(i).argParser(n);else if(n instanceof RegExp){let o=n;n=(a,l)=>{let d=o.exec(a);return d?d[0]:l},s.default(i).argParser(n)}else s.default(n);return this.addOption(s)}option(e,t,r,n){return this._optionEx({},e,t,r,n)}requiredOption(e,t,r,n){return this._optionEx({mandatory:!0},e,t,r,n)}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 n=U.default.execArgv??[];if(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.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
+ - 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(Yr.default.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",i=`'${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 c=He.default.resolve(u,l);if(Yr.default.existsSync(c))return c;if(r.includes(He.default.extname(l)))return;let p=r.find((f)=>Yr.default.existsSync(`${c}${f}`));if(p)return`${c}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let u;try{u=Yr.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}s=He.default.resolve(He.default.dirname(u),s)}if(s){let u=i(s,n);if(!u&&!e._executableFile&&this._scriptPath){let l=He.default.basename(this._scriptPath,He.default.extname(this._scriptPath));if(l!==this._name)u=i(s,`${l}-${e._name}`)}n=u||n}let o=r.includes(He.default.extname(n)),a;if(U.default.platform!=="win32")if(o)t.unshift(n),t=Qc(U.default.execArgv).concat(t),a=ln.default.spawn(U.default.argv[0],t,{stdio:"inherit"});else a=ln.default.spawn(n,t,{stdio:"inherit"});else this._checkForMissingExecutable(n,s,e._name),t.unshift(n),t=Qc(U.default.execArgv).concat(t),a=ln.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 d=this._exitCallback;a.on("close",(u)=>{if(u=u??1,!d)U.default.exit(u);else d(new at(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(!d)U.default.exit(1);else{let l=new at(1,"commander.executeSubCommandAsync","(error)");l.nestedError=u,d(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((c)=>c.short).some((c)=>/^-\d$/.test(c)))},o=null,a=null,d=0;while(d<e.length||a){let u=a??e[d++];if(a=null,u==="--"){if(i===r)i.push(u);i.push(...e.slice(d));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 c=e[d++];if(c===void 0)this.optionMissingArgument(l);this.emit(`option:${l.name()}`,c)}else if(l.optional){let c=null;if(d<e.length&&(!n(e[d])||s(e[d])))c=e[d++];this.emit(`option:${l.name()}`,c)}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("="),c=this._findOption(u.slice(0,l));if(c&&(c.required||c.optional)){this.emit(`option:${c.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(d));break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u,...e.slice(d));break}else if(this._defaultCommandName){r.push(u,...e.slice(d));break}}if(this._passThroughOptions){i.push(u,...e.slice(d));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
+ - ${n}`;throw Error(i)}_executeSubCommand(e,t){t=t.slice();let r=[".js",".ts",".tsx",".mjs",".cjs"];function n(d,c){let p=He.default.resolve(d,c);if(Yr.default.existsSync(p))return p;if(r.includes(He.default.extname(c)))return;let h=r.find((u)=>Yr.default.existsSync(`${p}${u}`));if(h)return`${p}${h}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,s=this._executableDir||"";if(this._scriptPath){let d;try{d=Yr.default.realpathSync(this._scriptPath)}catch{d=this._scriptPath}s=He.default.resolve(He.default.dirname(d),s)}if(s){let d=n(s,i);if(!d&&!e._executableFile&&this._scriptPath){let c=He.default.basename(this._scriptPath,He.default.extname(this._scriptPath));if(c!==this._name)d=n(s,`${c}-${e._name}`)}i=d||i}let o=r.includes(He.default.extname(i)),a;if(U.default.platform!=="win32")if(o)t.unshift(i),t=ic(U.default.execArgv).concat(t),a=ci.default.spawn(U.default.argv[0],t,{stdio:"inherit"});else a=ci.default.spawn(i,t,{stdio:"inherit"});else this._checkForMissingExecutable(i,s,e._name),t.unshift(i),t=ic(U.default.execArgv).concat(t),a=ci.default.spawn(U.default.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((c)=>{U.default.on(c,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(c)})});let l=this._exitCallback;a.on("close",(d)=>{if(d=d??1,!l)U.default.exit(d);else l(new lt(d,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(d)=>{if(d.code==="ENOENT")this._checkForMissingExecutable(i,s,e._name);else if(d.code==="EACCES")throw Error(`'${i}' not executable`);if(!l)U.default.exit(1);else{let c=new lt(1,"commander.executeSubCommandAsync","(error)");c.nestedError=d,l(c)}}),this.runningCommand=a}_dispatchSubcommand(e,t,r){let n=this._findCommand(e);if(!n)this.help({error:!0});n._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(r));else return n._parseCommand(t,r)}),i}_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,n,i)=>{let s=n;if(n!==null&&r.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${r.name()}'.`;s=this._callParseArg(r,n,i,o)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,n)=>{let i=r.defaultValue;if(r.variadic){if(n<this.args.length){if(i=this.args.slice(n),r.parseArg)i=i.reduce((s,o)=>e(r,o,s),r.defaultValue)}else if(i===void 0)i=[]}else if(n<this.args.length){if(i=this.args[n],r.parseArg)i=e(r,i,r.defaultValue)}t[n]=i}),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,n=[];if(this._getCommandAndAncestors().reverse().filter((i)=>i._lifeCycleHooks[t]!==void 0).forEach((i)=>{i._lifeCycleHooks[t].forEach((s)=>{n.push({hookedCommand:i,callback:s})})}),t==="postAction")n.reverse();return n.forEach((i)=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let n=e;if(this._lifeCycleHooks[r]!==void 0)this._lifeCycleHooks[r].forEach((i)=>{n=this._chainOrCall(n,()=>i(this,t))});return n}_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 n=()=>{if(r.unknown.length>0)this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),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(i,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent?.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,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 n(),this._processArguments()}else if(this.commands.length)n(),this.help({error:!0});else n(),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 n=r.attributeName();if(this.getOptionValue(n)===void 0)return!1;return this.getOptionValueSource(n)!=="default"});e.filter((r)=>r.conflictsWith.length>0).forEach((r)=>{let n=e.find((i)=>r.conflictsWith.includes(i.attributeName()));if(n)this._conflictingOption(r,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],n=t;function i(d){return d.length>1&&d[0]==="-"}let s=(d)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(d))return!1;return!this._getCommandAndAncestors().some((c)=>c.options.map((p)=>p.short).some((p)=>/^-\d$/.test(p)))},o=null,a=null,l=0;while(l<e.length||a){let d=a??e[l++];if(a=null,d==="--"){if(n===r)n.push(d);n.push(...e.slice(l));break}if(o&&(!i(d)||s(d))){this.emit(`option:${o.name()}`,d);continue}if(o=null,i(d)){let c=this._findOption(d);if(c){if(c.required){let p=e[l++];if(p===void 0)this.optionMissingArgument(c);this.emit(`option:${c.name()}`,p)}else if(c.optional){let p=null;if(l<e.length&&(!i(e[l])||s(e[l])))p=e[l++];this.emit(`option:${c.name()}`,p)}else this.emit(`option:${c.name()}`);o=c.variadic?c:null;continue}}if(d.length>2&&d[0]==="-"&&d[1]!=="-"){let c=this._findOption(`-${d[1]}`);if(c){if(c.required||c.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${c.name()}`,d.slice(2));else this.emit(`option:${c.name()}`),a=`-${d.slice(2)}`;continue}}if(/^--[^=]+=/.test(d)){let c=d.indexOf("="),p=this._findOption(d.slice(0,c));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,d.slice(c+1));continue}}if(n===t&&i(d)&&!(this.commands.length===0&&s(d)))n=r;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(d)){t.push(d),r.push(...e.slice(l));break}else if(this._getHelpCommand()&&d===this._getHelpCommand().name()){t.push(d,...e.slice(l));break}else if(this._defaultCommandName){r.push(d,...e.slice(l));break}}if(this._passThroughOptions){n.push(d,...e.slice(l));break}n.push(d)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let n=this.options[r].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}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
- `),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 Ks(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),d=this.options.find((l)=>l.negate&&o===l.attributeName()),u=this.options.find((l)=>!l.negate&&o===l.attributeName());if(d&&(d.presetArg===void 0&&a===!1||d.presetArg!==void 0&&a===d.presetArg))return d;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=zs(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=zs(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
- `),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)=>on(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=He.default.basename(e,He.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
- 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 Qc(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 Yc(){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 Ck=new sr;function y(e,t){if(e)return;if(typeof t==="string")throw Error(t);throw t}var nn=require("path"),C_=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 or 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
- `);return new or(`Pipeline graph validation failed
37
- ${t}`,e)}}var Hs="x-potato-sdk-base-url",ed=(e,t,r)=>(y(e.length>0,"The SDK base URL cannot be empty"),y(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[Hs]: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(Hs);y(s,"The SDK base URL is missing"),n.delete(Hs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let d=a;if(a.length===0)d=void 0;else if(o.headers.get("content-type")?.includes("application/json"))d=JSON.parse(a);throw re.fromResponse(o.status,d)}return a.length===0?void 0:JSON.parse(a)}var nv=()=>"/api/v2-beta/me",td=async(e)=>C(nv(),{...e,method:"GET"}),sv=(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"},Js=async(e,t)=>C(sv(e),{...t,method:"GET"}),ov=()=>"/api/v2-beta/projects",rd=async(e,t)=>C(ov(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),av=(e)=>`/api/v2-beta/projects/${e}`,id=async(e,t)=>C(av(e),{...t,method:"GET"}),lv=(e)=>`/api/v2-beta/projects/${e}`,nd=async(e,t,r)=>C(lv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),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/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Qs=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e)=>`/api/v2-beta/pipelines/${e}`,sd=async(e,t)=>C(dv(e),{...t,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}`,od=async(e,t,r)=>C(uv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),pv=(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`},Ys=async(e,t,r)=>C(pv(e,t),{...r,method:"GET"}),fv=(e)=>`/api/v2-beta/projects/${e}/datasets`,ad=async(e,t,r)=>C(fv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),mv=(e)=>`/api/v2-beta/datasets/${e}`,ld=async(e,t)=>C(mv(e),{...t,method:"GET"}),hv=(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`},Xs=async(e,t,r)=>C(hv(e,t),{...r,method:"GET"}),gv=(e)=>`/api/v2-beta/datasets/${e}/fields`,Zs=async(e,t,r)=>C(gv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),yv=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,cd=async(e,t)=>C(yv(e),{...t,method:"GET"}),_v=(e)=>`/api/v2-beta/datasets/${e}/items`,dd=async(e,t,r)=>C(_v(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),bv=(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`},eo=async(e,t,r)=>C(bv(e,t),{...r,method:"GET"}),Pv=(e)=>`/api/v2-beta/datasets/${e}/uploads`,ud=async(e,t,r)=>C(Pv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),vv=(e)=>`/api/v2-beta/uploads/${e}/finalize`,pd=async(e,t)=>C(vv(e),{...t,method:"POST"}),wv=(e)=>`/api/v2-beta/uploads/${e}`,to=async(e,t)=>C(wv(e),{...t,method:"GET"}),$v=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,fd=async(e,t,r)=>C($v(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Ev=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,md=async(e,t,r)=>C(Ev(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Iv=(e)=>`/api/v2-beta/pipelines/${e}/export`,hd=async(e,t)=>C(Iv(e),{...t,method:"GET"}),Sv=(e)=>`/api/v2-beta/pipelines/${e}/copy`,gd=async(e,t,r)=>C(Sv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),xv=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,yd=async(e,t,r)=>C(xv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Rv=(e)=>`/api/v2-beta/pipelines/${e}/runs`,_d=async(e,t)=>C(Rv(e),{...t,method:"POST"}),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/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},ro=async(e,t,r)=>C(Cv(e,t),{...r,method:"GET"}),Ov=(e)=>`/api/v2-beta/runs/${e}`,io=async(e,t)=>C(Ov(e),{...t,method:"GET"});var jv=(e)=>`/api/v2-beta/runs/${e}/cancel`,bd=async(e,t)=>C(jv(e),{...t,method:"POST"}),Fv=(e)=>`/api/v2-beta/datasets/${e}/exports`,Pd=async(e,t,r)=>C(Fv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Tv=(e)=>`/api/v2-beta/exports/${e}`,no=async(e,t)=>C(Tv(e),{...t,method:"GET"}),kv=(e)=>`/api/v2-beta/pipelines/${e}/graph`,vd=async(e,t)=>C(kv(e),{...t,method:"GET"}),Av=(e)=>`/api/v2-beta/pipelines/${e}/graph`,wd=async(e,t,r)=>C(Av(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Dv=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,$d=async(e,t,r)=>C(Dv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Nv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,Ed=async(e,t,r,i)=>C(Nv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),Lv=(e)=>`/api/v2-beta/projects/${e}/secrets`,Id=async(e,t)=>C(Lv(e),{...t,method:"GET"}),qv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,Sd=async(e,t,r,i)=>C(qv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),Mv=(e)=>`/api/v2-beta/projects/${e}/files`,xd=async(e,t)=>C(Mv(e),{...t,method:"GET"}),Uv=(e)=>`/api/v2-beta/projects/${e}/files`,Rd=async(e,t,r)=>C(Uv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Bv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,Cd=async(e,t,r)=>C(Bv(e,t),{...r,method:"POST"}),Gv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,Od=async(e,t,r)=>C(Gv(e,t),{...r,method:"DELETE"}),Vv=(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`},so=async(e,t,r)=>C(Vv(e,t),{...r,method:"GET"}),Kv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,jd=async(e,t,r)=>C(Kv(e,t),{...r,method:"GET"}),zv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Fd=async(e,t)=>C(zv(e),{...t,method:"GET"}),Wv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Td=async(e,t,r)=>C(Wv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Hv=(e)=>`/api/v2-beta/checks/${e}`,oo=async(e,t)=>C(Hv(e),{...t,method:"GET"});async function*bt(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 Xr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;y(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),y(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 d=await e(o.signal);if(t(d))return d;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:c}=Promise.withResolvers();setTimeout(c,Math.min(n,u)),await l}}catch(d){if(o.signal.aborted)throw re.waitTimeout(i);throw d}finally{clearTimeout(a)}};var Qv=(e)=>{let t=ed(e.baseUrl,e.apiKey,e.fetch);async function r(l,c){switch(l.type){case"datasetUpload":return Xr((p)=>to(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c);case"datasetExport":return Xr((p)=>no(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",c);case"pipelineCheck":return Xr((p)=>oo(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c);case"pipelineRun":return Xr((p)=>io(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",c)}}return{me:()=>td(t),projects:{create:(l)=>rd(l,t),get:({projectId:l})=>id(l,t),update:({projectId:l,...c})=>nd(l,c,t),listPage:(l={})=>Js(l,t),listAll:(l={})=>bt(async(c)=>{let p=await Js({...l,...c},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...c})=>fd(l,c,t),get:({pipelineId:l})=>sd(l,t),update:({pipelineId:l,...c})=>od(l,c,t),listPage:({projectId:l,...c})=>Qs(l,c,t),listAll:({projectId:l,...c})=>bt(async(p)=>{let f=await Qs(l,{...c,...p},t);return{items:f.pipelines,pagination:f.pagination}},c),getGraph:({pipelineId:l})=>vd(l,t),replaceGraph:({pipelineId:l,...c})=>wd(l,"version"in c?{graph:c.graph,expectedVersion:c.version}:c,t),validateGraph:({pipelineId:l,...c})=>$d(l,c,t),estimateCost:({pipelineId:l,...c})=>yd(l,c,t),patchNode:({pipelineId:l,nodeId:c,...p})=>Ed(l,c,p,t),attachDataset:({pipelineId:l,...c})=>md(l,c,t),export:({pipelineId:l})=>hd(l,t),copy:({pipelineId:l,...c})=>gd(l,c,t)},datasets:{create:({projectId:l,...c})=>ad(l,c,t),get:({datasetId:l})=>ld(l,t),listPage:({projectId:l,...c})=>Ys(l,c,t),listAll:({projectId:l,...c})=>bt(async(p)=>{let f=await Ys(l,{...c,...p},t);return{items:f.datasets,pagination:f.pagination}},c),createField:async({datasetId:l,...c})=>{let p=await Zs(l,c,t);return y(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:c})=>{let p=await Zs(l,{fields:c},t);return y("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...c})=>Xs(l,c,t),getInferredFields:({datasetId:l})=>cd(l,t),listAllFields:({datasetId:l,...c})=>bt(async(p)=>{let f=await Xs(l,{...c,...p},t);return{items:f.fields,pagination:f.pagination}},c),appendItems:({datasetId:l,...c})=>dd(l,c,t),listItemsPage:({datasetId:l,...c})=>eo(l,c,t),listAllItems:({datasetId:l,...c})=>bt(async(p)=>{let f=await eo(l,{...c,...p},t);return{items:f.items,pagination:f.pagination}},c),startUpload:({datasetId:l,...c})=>ud(l,c,t),finalizeUpload:({uploadId:l})=>pd(l,t),getUpload:({uploadId:l})=>to(l,t),startExport:({datasetId:l,...c})=>Pd(l,c,t),getExport:({exportId:l})=>no(l,t)},runs:{start:({pipelineId:l})=>{let c=new Headers(t.headers);return c.set("Content-Type","application/json"),_d(l,{...t,headers:c,body:"{}"})},get:({runId:l})=>io(l,t),cancel:({runId:l})=>bd(l,t),listPage:({pipelineId:l,...c})=>ro(l,c,t),listAll:({pipelineId:l,...c})=>bt(async(p)=>{let f=await ro(l,{...c,...p},t);return{items:f.runs,pagination:f.pagination}},c),listItemsPage:({runId:l,...c})=>so(l,c,t),listAllItems:({runId:l,...c})=>bt(async(p)=>{let f=await so(l,{...c,...p},t);return{items:f.items,pagination:f.pagination}},c),getItem:({runId:l,itemId:c})=>jd(l,c,t)},secrets:{list:async({projectId:l})=>(await Id(l,t)).secrets,set:({projectId:l,name:c,...p})=>Sd(l,c,p,t)},files:{list:async({projectId:l})=>(await xd(l,t)).files,startUpload:({projectId:l,...c})=>Rd(l,c,t),finalizeUpload:({projectId:l,fileId:c})=>Cd(l,c,t),delete:({projectId:l,fileId:c})=>Od(l,c,t)},checks:{list:async({pipelineId:l})=>(await Fd(l,t)).checks,start:({pipelineId:l,...c})=>Td(l,c,t),get:({checkRunId:l})=>oo(l,t)},waitFor:r}};function ct(e){return Qv(e)}var wr=require("fs/promises"),sl=require("path"),qf=Ce(nl(),1);var Kn="toloka.json";class ol extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var vR="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",wR={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:vR},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},$R=new qf.default({allErrors:!0,strict:!1}),Lf=$R.compile(wR);function ER(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 Mf(e){if(Lf(e))return e;let t=Lf.errors;throw y(t,"toloka.json validation failed without errors"),new ol(`Invalid toloka.json: ${t.map(ER).join("; ")}`)}async function Ie(e){let t;try{t=await wr.readFile(sl.join(e,Kn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Mf(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new ol(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Gt(e,t){let r=Mf(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 wr.mkdir(e,{recursive:!0}),await wr.writeFile(sl.join(e,Kn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
38
- `,"utf8")}var ge=require("fs/promises"),Gf=require("os"),$r=require("path");class Ii extends Error{constructor(e,t){super(e,t);this.name="CredentialsError"}}var Vf=(e)=>e.HOME??Gf.homedir(),IR=(e)=>e.XDG_CONFIG_HOME??$r.join(Vf(e),".config"),Ge=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??$r.join(IR(e),"toloka","credentials.json"),Kf=(e=process.env)=>$r.join(Vf(e),".toloka","credentials.json"),Uf=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},ft=(e)=>{let t=Uf(e.trim());try{let r=new URL(t);return r.hash="",r.search="",Uf(r.toString())}catch{return t}},zn=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,SR=(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}},xR=(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=SR(i);if(n===void 0)return;Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}return t},RR=(e,t)=>{let r=xR(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}},CR=(e)=>{let t=zn(e,"baseUrl"),r=zn(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(typeof r!=="string"||r.length===0)return;let i=zn(e,"current"),n=zn(e,"projects");if(i===void 0&&n===void 0)return{baseUrl:t,apiKey:r};let s=RR(n,i);if(s===void 0)return;return{baseUrl:t,apiKey:r,...s}};async function Wn(e){let t;try{t=await ge.readFile(e,"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"missing";return"invalid"}try{let r=CR(JSON.parse(t));return r===void 0?"invalid":{credentials:r}}catch{return"invalid"}}async function al(e=process.env){let t=Ge(e),r=await Wn(t);if(r!=="missing"){if(r==="invalid")throw new Ii(`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=Kf(e),n=await Wn(i);if(n==="missing")return;if(n==="invalid")throw new Ii(`Invalid credentials file at ${i}. Run toloka logout, then toloka login.`);return{credentials:n.credentials,path:i,legacy:!0}}async function Si(e,t){try{return{found:await al(e)}}catch(r){if(!(r instanceof Ii)||t===void 0)throw r;return{found:void 0,warning:r.message}}}async function zf(e=process.env){return(await al(e))?.credentials}async function Ot(e=process.env){let t=await al(e);if(t!==void 0)return t;throw new Ii(`No stored credentials found at ${Ge(e)}. Run toloka login.`)}var OR=(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}:{}}},Bf=async(e)=>{try{let t=await ge.lstat(e);y(!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 ll(e){let t=$r.dirname(e);await Bf(t),await Bf(e),await ge.mkdir(t,{recursive:!0,mode:448}),await ge.chmod(t,448)}async function Hn(e,t=process.env){let r=Ge(t);return await ll(r),await ge.writeFile(r,`${JSON.stringify(OR(e),null,2)}
39
- `,{mode:384}),await ge.chmod(r,384),r}var jR=async(e)=>{try{return await ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}};async function Wf(e=process.env){let t=[],r=[Ge(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Kf(e)]:[]];for(let i of r){if(!await jR(i))continue;await ge.rm(i,{force:!0}),t.push(i)}return t}var FR=16,Hf=(e)=>e.length>FR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var de="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, set projectId in toloka.json, or run toloka project add.",TR="No project selected. Run toloka project add, or cd into a checkout.",Jf="project add writes the machine registry; unset --api-key / --base-url / POTATO_API_KEY / POTATO_BASE_URL, or run login against that platform first.",kR=/^[^/\s]+$/u,Jn=(e)=>{let t=e.trim();return y(t.length>0&&kR.test(t),"Project alias must be non-empty and contain no / or whitespace."),t},ye=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},AR=(e,t,r)=>ye(e?.baseUrl)??ye(t?.POTATO_BASE_URL)??mt(t??{})??ye(r?.baseUrl),xi=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,DR=(e,t,r)=>{if(!r||t?.projects===void 0)return{};if(t.current!==void 0){let i=xi(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=xi(t.projects,i);if(n?.id!==e)continue;return n.name===void 0?{alias:i}:{alias:i,name:n.name}}return{}};function Ri(e={}){let t=e.flags??{},r=e.environment??{},i=e.stored,n=e.effectiveBaseUrl??AR(t,r,i),s=i!==void 0&&n!==void 0&&ft(n)===ft(i.baseUrl),a=[{id:ye(t.projectId),source:"flag"},{id:ye(r.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:ye(r.POTATO_PROJECT_ID),source:"potato-project-id"},{id:ye(e.state?.projectId),source:"toloka.json"},{id:s&&i.current!==void 0?ye(i.projects?.[i.current]?.id):void 0,source:"registry"}].find((d)=>d.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...DR(a.id,i,s)}}var dl=(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})`},Qn=(e,t,r)=>{let i=ye(e.apiKey)??ye(t.POTATO_API_KEY),n=ye(e.baseUrl)??ye(t.POTATO_BASE_URL)??mt(t);y(i===void 0||i===r.apiKey,Jf),y(n===void 0||ft(n)===ft(r.baseUrl),Jf)},Yn=async(e,t)=>{await Hn(e,t)},Qf=(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}},cl=async(e,t,r)=>{y(e?.prompt,r);let i=(await e.prompt(t)).trim();return y(i.length>0,r),i};async function Yf(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 Xf(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias??await cl(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),i=ye(e.projectId)??await cl(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),n=xi(t.credentials.projects,r);y(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 Yn(Qf(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 Zf(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias),i=xi(t.credentials.projects,r);y(i,`Unknown project alias ${r}.`),await Yn({...t.credentials,current:r},e.environment);let n=`Using project ${i.id} as ${r}.`;return e.io?.stdout(n),{output:n}}async function em(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias),i=Object.assign(Object.create(null),t.credentials.projects??{});y(xi(i,r),`Unknown project alias ${r}.`),delete i[r];let n=t.credentials.current===r?void 0:t.credentials.current;await Yn({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 tm(e){let t=Ri(e),r=t===void 0?TR:dl(t,e.stored);return e.io?.stdout(r),t===void 0?{output:r}:{output:r,project:t}}var NR=(e)=>{let t=[...new Set(e.map((r)=>r.teamId))];return t.length===1?t[0]:void 0},LR=async(e,t)=>{let r=ye(t);if(r!==void 0)return r;let i=[];for await(let s of e.projects.listAll())i.push(s);let n=NR(i);return y(n,"Missing team id. Pass --team-id. Visible projects do not share a single team, or none are visible."),n},qR=async(e,t,r,i)=>{if(t===void 0){try{await Gt(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 rm(e){let t=await Ot(e.environment);Qn(e.flags??{},e.environment,t.credentials);let r=Jn(e.alias??await cl(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal."));y(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 Ie(e.sourceRoot);await e.afterPreflight?.();let n=await LR(e.client,e.teamId),s=await e.client.projects.create({teamId:n,name:ye(e.name)??r});try{await Yn(Qf(t.credentials,r,{id:s.id,name:s.name}),e.environment)}catch(d){let u=d instanceof Error?d.message:String(d);throw Error([`Created ${s.id} but failed to update the local registry: ${u}`,`Run: toloka project add ${r} ${s.id}`].join(`
42
- `),{cause:d})}let o=[`Created project ${s.id} as ${r}.`];if(e.sourceRoot!==void 0){let d=await qR(e.sourceRoot,i,s,r);if(d!==void 0)o.push(d)}let a=o.join(`
43
- `);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var Vt="https://platform.toloka.ai",MR=/^(?:prestable|pr-\d+)$/u,mt=(e)=>{let t=e.ENV?.trim();if(t===void 0||!MR.test(t))return;return`https://${t}.platform.toloka-test.ai`},UR="https://console.toloka.ai",BR="https://prestable.console.toloka-test.ai",im=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return UR;if(t.endsWith(".platform.toloka-test.ai"))return BR;return},GR=["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 ul(e,t,r,i){let n=e.apiKey??r.POTATO_API_KEY??i?.apiKey,s=e.baseUrl??r.POTATO_BASE_URL??mt(r)??i?.baseUrl??Vt,o=Ri({flags:e,state:t,environment:r,stored:i,effectiveBaseUrl:s});return y(n,GR),{apiKey:n,baseUrl:s,...o===void 0?{}:{projectId:o.id}}}var VR=(e)=>{let t=im(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 nm(e={}){let t=e.environment??process.env,r=e.write??(()=>{return}),i=ft(e.baseUrl??t.POTATO_BASE_URL??mt(t)??Vt),n=e.apiKey;if(n===void 0)y(e.prompt,"Missing API key. Pass --api-key, or set POTATO_API_KEY, when stdin is not a terminal."),r(`
46
- ${VR(i)}
47
- `),n=(await e.prompt("API key: ",{mask:!0})).trim();y(n.length>0,"No API key entered.");let s={baseUrl:i,apiKey:n},o=e.probe?.(s)??ct(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 d=Ge(t),u=await Wn(d),l=typeof u==="object"&&ft(u.credentials.baseUrl)===ft(i)?{baseUrl:i,apiKey:n,...u.credentials.current===void 0?{}:{current:u.credentials.current},...u.credentials.projects===void 0?{}:{projects:u.credentials.projects}}:s,c=await Hn(l,t);return{credentialsFile:c,baseUrl:i,output:[a,`Saved credentials to ${c}.`,"","toloka reads them automatically. --api-key and POTATO_API_KEY still win when set."].join(`
49
- `)}}async function sm(e=process.env){let t=await Wf(e);return{removed:t,output:t.length===0?`No stored credentials found at ${Ge(e)}.`:`Removed ${t.join(", ")}.
32
+ `),this.outputHelp({error:!0});let r=t||{},n=r.exitCode||1,i=r.code||"commander.error";this._exit(n,i,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 Js(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((n)=>!t(n)).forEach((n)=>{this.setOptionValueWithSource(n,r.implied[n],"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),l=this.options.find((c)=>c.negate&&o===c.attributeName()),d=this.options.find((c)=>!c.negate&&o===c.attributeName());if(l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg))return l;return d||s},n=(s)=>{let o=r(s),a=o.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},i=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let s=i.createHelp().visibleOptions(i).filter((o)=>o.long).map((o)=>o.long);n=n.concat(s),i=i.parent}while(i&&!i._enablePositionalOptions);t=Qs(e,n)}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",n=e.length,i=this.parent?` for '${this.name()}'`:"",s=e.join(", "),o=`error: too many arguments${i}. Expected ${t} argument${r} but got ${n}: ${s}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((i)=>{if(n.push(i.name()),i.alias())n.push(i.alias())}),t=Qs(e,n)}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 n=this.createOption(t,r);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
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 n=[r.name()].concat(r.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}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)=>li(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=He.default.basename(e,He.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 n=t.formatHelp(this,t);if(r.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,r,n,i;if(t)r=(o)=>this._outputConfiguration.writeErr(o),n=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth();else r=(o)=>this._outputConfiguration.writeOut(o),n=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(o)=>{if(!n)o=this._outputConfiguration.stripColor(o);return r(o)},hasColors:n,helpWidth:i}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let r=this._getOutputContext(e),n={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let i=this.helpInformation({error:r.error});if(t){if(i=t(i),typeof i!=="string"&&!Buffer.isBuffer(i))throw Error("outputHelp callback must return a string or a Buffer")}if(r.write(i),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",n))}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
+ Expecting one of '${r.join("', '")}'`);let n=`${e}Help`;return this.on(n,(i)=>{let s;if(typeof t==="function")s=t({error:i.error,command:i.command});else s=t;if(s)i.write(`${s}
35
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((n)=>t.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function ic(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let r,n="127.0.0.1",i="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]))i=s[3];else n=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)r=s[1],n=s[3],i=s[4];if(r&&i!=="0")return`${r}=${n}:${parseInt(i)+1}`;return t})}function sc(){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 fk=new or;function _(e,t){if(e)return;if(typeof t==="string")throw Error(t);throw t}var oi=require("path"),Z_=require("readline/promises");class te extends Error{code;status;body;requestId;constructor(e,t,r,n,i){super(e);this.name="PotatoApiError",this.code=t,this.status=r,this.body=n,this.requestId=i}static fromResponse(e,t,r){let n=r===void 0?"":` (request id: ${r})`;return new te(`Potato API request failed with status ${e}${n}`,"http",e,t,r)}static waitTimeout(e){return new te(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class ar 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:n})=>`- ${r}: ${n}`).join(`
36
+ `);return new ar(`Pipeline graph validation failed
37
+ ${t}`,e)}}var Xs="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}`,[Xs]:new URL(e).toString()},fetch:r});async function j(e,t){let{fetch:r=globalThis.fetch,...n}=t,i=new Headers(n.headers),s=i.get(Xs);_(s,"The SDK base URL is missing"),i.delete(Xs);let o=await r(new URL(e,s),{...n,headers:i}),a=await o.text();if(!o.ok){let l=a;if(a.length===0)l=void 0;else if(o.headers.get("content-type")?.includes("application/json"))l=JSON.parse(a);throw te.fromResponse(o.status,l,o.headers.get("x-request-id")??void 0)}return a.length===0?void 0:JSON.parse(a)}var jv=()=>"/api/v2-beta/base-models",dc=async(e)=>j(jv(),{...e,method:"GET"}),Rv=(e)=>`/api/v2-beta/base-models/${e}`,cc=async(e,t)=>j(Rv(e),{...t,method:"GET"}),Cv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/projects/${e}/models?${n}`:`/api/v2-beta/projects/${e}/models`},Zs=async(e,t,r)=>j(Cv(e,t),{...r,method:"GET"}),Ov=(e)=>`/api/v2-beta/projects/${e}/models`,uc=async(e,t,r)=>j(Ov(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Fv=(e,t,r)=>{let n=new URLSearchParams;Object.entries(r||{}).forEach(([s,o])=>{if(o!==void 0)n.append(s,o===null?"null":o.toString())});let i=n.toString();return i.length>0?`/api/v2-beta/projects/${e}/models/${t}/versions?${i}`:`/api/v2-beta/projects/${e}/models/${t}/versions`},eo=async(e,t,r,n)=>j(Fv(e,t,r),{...n,method:"GET"}),Tv=(e)=>`/api/v2-beta/model-versions/${e}`,pc=async(e,t)=>j(Tv(e),{...t,method:"GET"}),Av=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}/archive`,fc=async(e,t,r)=>j(Av(e,t),{...r,method:"POST"}),kv=(e,t)=>`/api/v2-beta/projects/${e}/models/${t}`,mc=async(e,t,r)=>j(kv(e,t),{...r,method:"GET"}),Dv=()=>"/api/v2-beta/me",hc=async(e)=>j(Dv(),{...e,method:"GET"}),Nv=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([n,i])=>{if(i!==void 0)t.append(n,i===null?"null":i.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},to=async(e,t)=>j(Nv(e),{...t,method:"GET"}),Mv=()=>"/api/v2-beta/projects",gc=async(e,t)=>j(Mv(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),Lv=(e)=>`/api/v2-beta/projects/${e}`,yc=async(e,t)=>j(Lv(e),{...t,method:"GET"}),qv=(e)=>`/api/v2-beta/projects/${e}`,_c=async(e,t,r)=>j(qv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Uv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/projects/${e}/pipelines?${n}`:`/api/v2-beta/projects/${e}/pipelines`},ro=async(e,t,r)=>j(Uv(e,t),{...r,method:"GET"}),Bv=(e)=>`/api/v2-beta/pipelines/${e}`,bc=async(e,t)=>j(Bv(e),{...t,method:"GET"}),Gv=(e)=>`/api/v2-beta/pipelines/${e}`,Pc=async(e,t,r)=>j(Gv(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Vv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/projects/${e}/datasets?${n}`:`/api/v2-beta/projects/${e}/datasets`},no=async(e,t,r)=>j(Vv(e,t),{...r,method:"GET"}),zv=(e)=>`/api/v2-beta/projects/${e}/datasets`,vc=async(e,t,r)=>j(zv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Kv=(e)=>`/api/v2-beta/datasets/${e}`,wc=async(e,t)=>j(Kv(e),{...t,method:"GET"}),Wv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/datasets/${e}/fields?${n}`:`/api/v2-beta/datasets/${e}/fields`},io=async(e,t,r)=>j(Wv(e,t),{...r,method:"GET"}),Hv=(e)=>`/api/v2-beta/datasets/${e}/fields`,so=async(e,t,r)=>j(Hv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Jv=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,$c=async(e,t)=>j(Jv(e),{...t,method:"GET"}),Qv=(e)=>`/api/v2-beta/datasets/${e}/items`,Ic=async(e,t,r)=>j(Qv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Yv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/datasets/${e}/items?${n}`:`/api/v2-beta/datasets/${e}/items`},oo=async(e,t,r)=>j(Yv(e,t),{...r,method:"GET"}),Xv=(e)=>`/api/v2-beta/datasets/${e}/uploads`,Ec=async(e,t,r)=>j(Xv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),Zv=(e)=>`/api/v2-beta/uploads/${e}/finalize`,Sc=async(e,t)=>j(Zv(e),{...t,method:"POST"}),ew=(e)=>`/api/v2-beta/uploads/${e}`,ao=async(e,t)=>j(ew(e),{...t,method:"GET"}),tw=(e)=>`/api/v2-beta/uploads/${e}/cancel`,xc=async(e,t)=>j(tw(e),{...t,method:"POST"}),rw=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,jc=async(e,t,r)=>j(rw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),nw=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,Rc=async(e,t,r)=>j(nw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),iw=(e)=>`/api/v2-beta/pipelines/${e}/export`,Cc=async(e,t)=>j(iw(e),{...t,method:"GET"}),sw=(e)=>`/api/v2-beta/pipelines/${e}/copy`,Oc=async(e,t,r)=>j(sw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),ow=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,Fc=async(e,t,r)=>j(ow(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),aw=(e)=>`/api/v2-beta/pipelines/${e}/runs`,Tc=async(e,t)=>j(aw(e),{...t,method:"POST"}),lw=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/pipelines/${e}/runs?${n}`:`/api/v2-beta/pipelines/${e}/runs`},lo=async(e,t,r)=>j(lw(e,t),{...r,method:"GET"}),dw=(e)=>`/api/v2-beta/runs/${e}`,co=async(e,t)=>j(dw(e),{...t,method:"GET"});var cw=(e)=>`/api/v2-beta/runs/${e}/cancel`,Ac=async(e,t)=>j(cw(e),{...t,method:"POST"}),uw=(e)=>`/api/v2-beta/datasets/${e}/exports`,kc=async(e,t,r)=>j(uw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),pw=(e)=>`/api/v2-beta/exports/${e}`,uo=async(e,t)=>j(pw(e),{...t,method:"GET"}),fw=(e)=>`/api/v2-beta/pipelines/${e}/graph`,Dc=async(e,t)=>j(fw(e),{...t,method:"GET"}),mw=(e)=>`/api/v2-beta/pipelines/${e}/graph`,Nc=async(e,t,r)=>j(mw(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),hw=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,Mc=async(e,t,r)=>j(hw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),gw=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,Lc=async(e,t,r,n)=>j(gw(e,t),{...n,method:"PATCH",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(r)}),yw=(e)=>`/api/v2-beta/projects/${e}/secrets`,qc=async(e,t)=>j(yw(e),{...t,method:"GET"}),_w=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,Uc=async(e,t,r,n)=>j(_w(e,t),{...n,method:"PUT",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(r)}),bw=(e)=>`/api/v2-beta/projects/${e}/files`,Bc=async(e,t)=>j(bw(e),{...t,method:"GET"}),Pw=(e)=>`/api/v2-beta/projects/${e}/files`,Gc=async(e,t,r)=>j(Pw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),vw=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,Vc=async(e,t,r)=>j(vw(e,t),{...r,method:"POST"}),ww=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,zc=async(e,t,r)=>j(ww(e,t),{...r,method:"DELETE"}),$w=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([i,s])=>{if(s!==void 0)r.append(i,s===null?"null":s.toString())});let n=r.toString();return n.length>0?`/api/v2-beta/runs/${e}/items?${n}`:`/api/v2-beta/runs/${e}/items`},po=async(e,t,r)=>j($w(e,t),{...r,method:"GET"}),Iw=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,Kc=async(e,t,r)=>j(Iw(e,t),{...r,method:"GET"}),Ew=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Wc=async(e,t)=>j(Ew(e),{...t,method:"GET"}),Sw=(e)=>`/api/v2-beta/pipelines/${e}/checks`,Hc=async(e,t,r)=>j(Sw(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),xw=(e)=>`/api/v2-beta/checks/${e}`,fo=async(e,t)=>j(xw(e),{...t,method:"GET"});async function*Je(e,t={}){let r=t.offset;while(!0){let n=await e({limit:t.limit,offset:r});if(yield*n.items,!n.pagination.hasMore)return;r=n.pagination.offset+n.pagination.limit}}var Xr=async(e,t,r={})=>{let n=r.timeoutMs??60000,i=r.intervalMs??1000;_(Number.isFinite(n)&&n>=0,"The wait timeout must be a nonnegative finite number"),_(Number.isFinite(i)&&i>0,"The polling interval must be a positive finite number");let s=Date.now()+n,o=new AbortController,a=setTimeout(()=>o.abort(),n);try{while(!0){if(o.signal.aborted)throw te.waitTimeout(n);let l=await e(o.signal);if(t(l))return l;let d=s-Date.now();if(d<=0)throw te.waitTimeout(n);let{promise:c,resolve:p}=Promise.withResolvers();setTimeout(p,Math.min(i,d)),await c}}catch(l){if(o.signal.aborted)throw te.waitTimeout(n);throw l}finally{clearTimeout(a)}};var Rw=(e)=>{let t=lc(e.baseUrl,e.apiKey,e.fetch),r=()=>{let u=new Headers(t.headers);return u.set("Content-Type","application/json"),{...t,headers:u,body:"{}"}};async function n(u,f){switch(u.type){case"datasetUpload":return Xr((m)=>ao(u.uploadId,{...t,signal:m}),(m)=>m.status==="succeeded"||m.status==="failed",f);case"datasetExport":return Xr((m)=>uo(u.exportId,{...t,signal:m}),(m)=>m.status==="succeeded",f);case"pipelineCheck":return Xr((m)=>fo(u.checkRunId,{...t,signal:m}),(m)=>m.status==="succeeded"||m.status==="failed",f);case"pipelineRun":return Xr((m)=>co(u.runId,{...t,signal:m}),(m)=>m.status==="succeeded"||m.status==="failed",f)}}return{me:()=>hc(t),projects:{create:(u)=>gc(u,t),get:({projectId:u})=>yc(u,t),update:({projectId:u,...f})=>_c(u,f,t),listPage:(u={})=>to(u,t),listAll:(u={})=>Je(async(f)=>{let m=await to({...u,...f},t);return{items:m.projects,pagination:m.pagination}},u)},pipelines:{import:({projectId:u,...f})=>jc(u,f,t),get:({pipelineId:u})=>bc(u,t),update:({pipelineId:u,...f})=>Pc(u,f,t),listPage:({projectId:u,...f})=>ro(u,f,t),listAll:({projectId:u,...f})=>Je(async(m)=>{let g=await ro(u,{...f,...m},t);return{items:g.pipelines,pagination:g.pagination}},f),getGraph:({pipelineId:u})=>Dc(u,t),replaceGraph:({pipelineId:u,...f})=>Nc(u,"version"in f?{graph:f.graph,expectedVersion:f.version}:f,t),validateGraph:({pipelineId:u,...f})=>Mc(u,f,t),estimateCost:({pipelineId:u,...f})=>Fc(u,f,t),patchNode:({pipelineId:u,nodeId:f,...m})=>Lc(u,f,m,t),attachDataset:({pipelineId:u,...f})=>Rc(u,f,t),export:({pipelineId:u})=>Cc(u,t),copy:({pipelineId:u,...f})=>Oc(u,f,t)},datasets:{create:({projectId:u,...f})=>vc(u,f,t),get:({datasetId:u})=>wc(u,t),listPage:({projectId:u,...f})=>no(u,f,t),listAll:({projectId:u,...f})=>Je(async(m)=>{let g=await no(u,{...f,...m},t);return{items:g.datasets,pagination:g.pagination}},f),createField:async({datasetId:u,...f})=>{let m=await so(u,f,t);return _(!("fields"in m),"Creating one field must return that field"),m},createFields:async({datasetId:u,fields:f})=>{let m=await so(u,{fields:f},t);return _("fields"in m,"Creating several fields must return those fields"),m.fields},listFieldsPage:({datasetId:u,...f})=>io(u,f,t),getInferredFields:({datasetId:u})=>$c(u,t),listAllFields:({datasetId:u,...f})=>Je(async(m)=>{let g=await io(u,{...f,...m},t);return{items:g.fields,pagination:g.pagination}},f),appendItems:({datasetId:u,...f})=>Ic(u,f,t),listItemsPage:({datasetId:u,...f})=>oo(u,f,t),listAllItems:({datasetId:u,...f})=>Je(async(m)=>{let g=await oo(u,{...f,...m},t);return{items:g.items,pagination:g.pagination}},f),startUpload:({datasetId:u,...f})=>Ec(u,f,t),finalizeUpload:({uploadId:u})=>Sc(u,r()),cancelUpload:({uploadId:u})=>xc(u,r()),getUpload:({uploadId:u})=>ao(u,t),startExport:({datasetId:u,...f})=>kc(u,f,t),getExport:({exportId:u})=>uo(u,t)},baseModels:{list:async()=>(await dc(t)).baseModels,get:({id:u})=>cc(u,t)},models:{listPage:({projectId:u,...f})=>Zs(u,f,t),listAll:({projectId:u,...f})=>Je(async(m)=>{let g=await Zs(u,{...f,...m},t);return{items:g.models,pagination:g.pagination}},f),get:({projectId:u,modelId:f})=>mc(u,f,t),listVersionsPage:({projectId:u,modelId:f,...m})=>eo(u,f,m,t),listAllVersions:({projectId:u,modelId:f,...m})=>Je(async(g)=>{let y=await eo(u,f,{...m,...g},t);return{items:y.versions,pagination:y.pagination}},m),create:({projectId:u,...f})=>uc(u,f,t),getVersion:({modelVersionId:u})=>pc(u,t),archive:({projectId:u,modelId:f})=>{let m=new Headers(t.headers);return m.set("Content-Type","application/json"),fc(u,f,{...t,headers:m})}},runs:{start:({pipelineId:u})=>Tc(u,r()),get:({runId:u})=>co(u,t),cancel:({runId:u})=>Ac(u,t),listPage:({pipelineId:u,...f})=>lo(u,f,t),listAll:({pipelineId:u,...f})=>Je(async(m)=>{let g=await lo(u,{...f,...m},t);return{items:g.runs,pagination:g.pagination}},f),listItemsPage:({runId:u,...f})=>po(u,f,t),listAllItems:({runId:u,...f})=>Je(async(m)=>{let g=await po(u,{...f,...m},t);return{items:g.items,pagination:g.pagination}},f),getItem:({runId:u,itemId:f})=>Kc(u,f,t)},secrets:{list:async({projectId:u})=>(await qc(u,t)).secrets,set:({projectId:u,name:f,...m})=>Uc(u,f,m,t)},files:{list:async({projectId:u})=>(await Bc(u,t)).files,startUpload:({projectId:u,...f})=>Gc(u,f,t),finalizeUpload:({projectId:u,fileId:f})=>Vc(u,f,t),delete:({projectId:u,fileId:f})=>zc(u,f,t)},checks:{list:async({pipelineId:u})=>(await Wc(u,t)).checks,start:({pipelineId:u,...f})=>Hc(u,f,t),get:({checkRunId:u})=>fo(u,t)},waitFor:n}};function ct(e){return Rw(e)}var $r=require("fs/promises"),ul=require("path"),em=Re(cl(),1);var Wi="toloka.json";class pl extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var eR="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",tR={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:eR},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},rR=new em.default({allErrors:!0,strict:!1}),Zf=rR.compile(tR);function nR(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 tm(e){if(Zf(e))return e;let t=Zf.errors;throw _(t,"toloka.json validation failed without errors"),new pl(`Invalid toloka.json: ${t.map(nR).join("; ")}`)}async function Ee(e){let t;try{t=await $r.readFile(ul.join(e,Wi),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return tm(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new pl(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Gt(e,t){let r=tm(t),n=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),i=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await $r.mkdir(e,{recursive:!0}),await $r.writeFile(ul.join(e,Wi),`${JSON.stringify({projectId:r.projectId,pipelines:n,datasets:i},null,2)}
38
+ `,"utf8")}var ge=require("fs/promises"),im=require("os"),Ir=require("path");class Sn extends Error{constructor(e,t){super(e,t);this.name="CredentialsError"}}var sm=(e)=>e.HOME??im.homedir(),iR=(e)=>e.XDG_CONFIG_HOME??Ir.join(sm(e),".config"),Ge=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??Ir.join(iR(e),"toloka","credentials.json"),om=(e=process.env)=>Ir.join(sm(e),".toloka","credentials.json"),rm=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},mt=(e)=>{let t=rm(e.trim());try{let r=new URL(t);return r.hash="",r.search="",rm(r.toString())}catch{return t}},Hi=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,sR=(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}},oR=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[r,n]of Object.entries(e)){if(r.length===0)return;let i=sR(n);if(i===void 0)return;Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}return t},aR=(e,t)=>{let r=oR(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}},lR=(e)=>{let t=Hi(e,"baseUrl"),r=Hi(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(typeof r!=="string"||r.length===0)return;let n=Hi(e,"current"),i=Hi(e,"projects");if(n===void 0&&i===void 0)return{baseUrl:t,apiKey:r};let s=aR(i,n);if(s===void 0)return;return{baseUrl:t,apiKey:r,...s}};async function Ji(e){let t;try{t=await ge.readFile(e,"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return"missing";return"invalid"}try{let r=lR(JSON.parse(t));return r===void 0?"invalid":{credentials:r}}catch{return"invalid"}}async function fl(e=process.env){let t=Ge(e),r=await Ji(t);if(r!=="missing"){if(r==="invalid")throw new Sn(`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 n=om(e),i=await Ji(n);if(i==="missing")return;if(i==="invalid")throw new Sn(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`);return{credentials:i.credentials,path:n,legacy:!0}}async function xn(e,t){try{return{found:await fl(e)}}catch(r){if(!(r instanceof Sn)||t===void 0)throw r;return{found:void 0,warning:r.message}}}async function am(e=process.env){return(await fl(e))?.credentials}async function Ct(e=process.env){let t=await fl(e);if(t!==void 0)return t;throw new Sn(`No stored credentials found at ${Ge(e)}. Run toloka login.`)}var dR=(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}:{}}},nm=async(e)=>{try{let t=await ge.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 ml(e){let t=Ir.dirname(e);await nm(t),await nm(e),await ge.mkdir(t,{recursive:!0,mode:448}),await ge.chmod(t,448)}async function Qi(e,t=process.env){let r=Ge(t);return await ml(r),await ge.writeFile(r,`${JSON.stringify(dR(e),null,2)}
39
+ `,{mode:384}),await ge.chmod(r,384),r}var cR=async(e)=>{try{return await ge.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}};async function lm(e=process.env){let t=[],r=[Ge(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[om(e)]:[]];for(let n of r){if(!await cR(n))continue;await ge.rm(n,{force:!0}),t.push(n)}return t}var uR=16,dm=(e)=>e.length>uR?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var X="Missing project ID. Pass --project-id, set TOLOKA_PROJECT_ID, set projectId in toloka.json, or run toloka project add.",pR="No project selected. Run toloka project add, or cd into a checkout.",cm="project add writes the machine registry; unset --api-key / --base-url / POTATO_API_KEY / POTATO_BASE_URL, or run login against that platform first.",fR=/^[^/\s]+$/u,Yi=(e)=>{let t=e.trim();return _(t.length>0&&fR.test(t),"Project alias must be non-empty and contain no / or whitespace."),t},ye=(e)=>{if(e===void 0)return;let t=e.trim();return t.length===0?void 0:t},mR=(e,t,r)=>ye(e?.baseUrl)??ye(t?.POTATO_BASE_URL)??ht(t??{})??ye(r?.baseUrl),jn=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,hR=(e,t,r)=>{if(!r||t?.projects===void 0)return{};if(t.current!==void 0){let n=jn(t.projects,t.current);if(n?.id===e)return n.name===void 0?{alias:t.current}:{alias:t.current,name:n.name}}for(let n of Object.keys(t.projects).toSorted()){let i=jn(t.projects,n);if(i?.id!==e)continue;return i.name===void 0?{alias:n}:{alias:n,name:i.name}}return{}};function Rn(e={}){let t=e.flags??{},r=e.environment??{},n=e.stored,i=e.effectiveBaseUrl??mR(t,r,n),s=n!==void 0&&i!==void 0&&mt(i)===mt(n.baseUrl),a=[{id:ye(t.projectId),source:"flag"},{id:ye(r.TOLOKA_PROJECT_ID),source:"toloka-project-id"},{id:ye(r.POTATO_PROJECT_ID),source:"potato-project-id"},{id:ye(e.state?.projectId),source:"toloka.json"},{id:s&&n.current!==void 0?ye(n.projects?.[n.current]?.id):void 0,source:"registry"}].find((l)=>l.id!==void 0);if(a?.id===void 0)return;return{id:a.id,source:a.source,...hR(a.id,n,s)}}var gl=(e,t)=>{if(e===void 0)return"Project: (none). Run toloka project add.";let r=e.alias===void 0?"":`alias ${e.alias}, `,n=e.source!=="registry"&&t?.current!==void 0?`; registry current is ${t.current}`:"";return`Project: ${e.id} (${r}from ${e.source}${n})`},Xi=(e,t,r)=>{let n=ye(e.apiKey)??ye(t.POTATO_API_KEY),i=ye(e.baseUrl)??ye(t.POTATO_BASE_URL)??ht(t);_(n===void 0||n===r.apiKey,cm),_(i===void 0||mt(i)===mt(r.baseUrl),cm)},Zi=async(e,t)=>{await Qi(e,t)},um=(e,t,r)=>{let n=Object.assign(Object.create(null),e.projects??{},{[t]:r.name===void 0?{id:r.id}:r});return{...e,current:t,projects:n}},hl=async(e,t,r)=>{_(e?.prompt,r);let n=(await e.prompt(t)).trim();return _(n.length>0,r),n};async function pm(e){let t=[];for await(let n of e.client.projects.listAll()){let i=e.context?.id===n.id?"*":" ",s=e.context?.id===n.id&&e.context.alias!==void 0?` ${e.context.alias}`:"";t.push(`${i} ${n.id} ${n.name}${s}`)}let r=t.length===0?"No projects visible.":t.join(`
40
+ `);return e.io.stdout(r),{output:r}}async function fm(e){let t=await Ct(e.environment);Xi(e.flags??{},e.environment,t.credentials);let r=Yi(e.alias??await hl(e.io,"Alias: ","Missing project alias. Pass an alias or run this in a terminal.")),n=ye(e.projectId)??await hl(e.io,"Project id: ","Missing project ID. Pass a project id or run this in a terminal."),i=jn(t.credentials.projects,r);_(i===void 0||i.id===n,`Alias ${r} already points at ${i?.id}. Run toloka project remove ${r} first.`),await e.afterPreflight?.();let s=await e.client.projects.get({projectId:n});await Zi(um(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 mm(e){let t=await Ct(e.environment);Xi(e.flags??{},e.environment,t.credentials);let r=Yi(e.alias),n=jn(t.credentials.projects,r);_(n,`Unknown project alias ${r}.`),await Zi({...t.credentials,current:r},e.environment);let i=`Using project ${n.id} as ${r}.`;return e.io?.stdout(i),{output:i}}async function hm(e){let t=await Ct(e.environment);Xi(e.flags??{},e.environment,t.credentials);let r=Yi(e.alias),n=Object.assign(Object.create(null),t.credentials.projects??{});_(jn(n,r),`Unknown project alias ${r}.`),delete n[r];let i=t.credentials.current===r?void 0:t.credentials.current;await Zi({baseUrl:t.credentials.baseUrl,apiKey:t.credentials.apiKey,...i===void 0?{}:{current:i},...Object.keys(n).length===0?{}:{projects:n}},e.environment);let s=`Removed local alias ${r}.`;return e.io?.stdout(s),{output:s}}function gm(e){let t=Rn(e),r=t===void 0?pR:gl(t,e.stored);return e.io?.stdout(r),t===void 0?{output:r}:{output:r,project:t}}var gR=(e)=>{let t=[...new Set(e.map((r)=>r.teamId))];return t.length===1?t[0]:void 0},yR=async(e,t)=>{let r=ye(t);if(r!==void 0)return r;let n=[];for await(let s of e.projects.listAll())n.push(s);let i=gR(n);return _(i,"Missing team id. Pass --team-id. Visible projects do not share a single team, or none are visible."),i},_R=async(e,t,r,n)=>{if(t===void 0){try{await Gt(e,{projectId:r.id,pipelines:{},datasets:{}})}catch(i){let s=i instanceof Error?i.message:String(i);throw Error([`Created project ${r.id} as ${n}.`,`Failed to write toloka.json: ${s}`].join(`
41
+ `),{cause:i})}return}if(t.projectId===r.id)return;return`Checkout still uses ${t.projectId}; it overrides the new registry current.`};async function ym(e){let t=await Ct(e.environment);Xi(e.flags??{},e.environment,t.credentials);let r=Yi(e.alias??await hl(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 n=e.sourceRoot===void 0?void 0:await Ee(e.sourceRoot);await e.afterPreflight?.();let i=await yR(e.client,e.teamId),s=await e.client.projects.create({teamId:i,name:ye(e.name)??r});try{await Zi(um(t.credentials,r,{id:s.id,name:s.name}),e.environment)}catch(l){let d=l instanceof Error?l.message:String(l);throw Error([`Created ${s.id} but failed to update the local registry: ${d}`,`Run: toloka project add ${r} ${s.id}`].join(`
42
+ `),{cause:l})}let o=[`Created project ${s.id} as ${r}.`];if(e.sourceRoot!==void 0){let l=await _R(e.sourceRoot,n,s,r);if(l!==void 0)o.push(l)}let a=o.join(`
43
+ `);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var Vt="https://platform.toloka.ai",bR=/^(?:prestable|pr-\d+)$/u,ht=(e)=>{let t=e.ENV?.trim();if(t===void 0||!bR.test(t))return;return`https://${t}.platform.toloka-test.ai`},PR="https://console.toloka.ai",vR="https://prestable.console.toloka-test.ai",_m=(e)=>{let t;try{t=new URL(e).host}catch{return}if(t==="platform.toloka.ai")return PR;if(t.endsWith(".platform.toloka-test.ai"))return vR;return},wR=["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 yl(e,t,r,n){let i=e.apiKey??r.POTATO_API_KEY??n?.apiKey,s=e.baseUrl??r.POTATO_BASE_URL??ht(r)??n?.baseUrl??Vt,o=Rn({flags:e,state:t,environment:r,stored:n,effectiveBaseUrl:s});return _(i,wR),{apiKey:i,baseUrl:s,...o===void 0?{}:{projectId:o.id}}}var $R=(e)=>{let t=_m(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 bm(e={}){let t=e.environment??process.env,r=e.write??(()=>{return}),n=mt(e.baseUrl??t.POTATO_BASE_URL??ht(t)??Vt),i=e.apiKey;if(i===void 0)_(e.prompt,"Missing API key. Pass --api-key, or set POTATO_API_KEY, when stdin is not a terminal."),r(`
46
+ ${$R(n)}
47
+ `),i=(await e.prompt("API key: ",{mask:!0})).trim();_(i.length>0,"No API key entered.");let s={baseUrl:n,apiKey:i},o=e.probe?.(s)??ct(s),a;try{let h=await o.projects.listPage({limit:1});a=`Authenticated against ${n}: ${h.pagination.total} project(s) visible.`}catch(h){let u=h instanceof Error?h.message:String(h);throw Error([`Could not authenticate against ${n}: ${u}`,"","Nothing was saved. Check that the key was copied whole and has not been revoked."].join(`
48
+ `),{cause:h})}let l=Ge(t),d=await Ji(l),c=typeof d==="object"&&mt(d.credentials.baseUrl)===mt(n)?{baseUrl:n,apiKey:i,...d.credentials.current===void 0?{}:{current:d.credentials.current},...d.credentials.projects===void 0?{}:{projects:d.credentials.projects}}:s,p=await Qi(c,t);return{credentialsFile:p,baseUrl:n,output:[a,`Saved credentials to ${p}.`,"","toloka reads them automatically. --api-key and POTATO_API_KEY still win when set."].join(`
49
+ `)}}async function Pm(e=process.env){let t=await lm(e);return{removed:t,output:t.length===0?`No stored credentials found at ${Ge(e)}.`:`Removed ${t.join(", ")}.
50
50
 
51
- This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var om=(e)=>e.find((t)=>t!==void 0),KR=(e,t,r,i)=>om([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}`}]),zR=(e,t,r)=>{let i=mt(t);return om([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:Vt,source:"default"}};async function am(e={}){let t=e.environment??process.env,r=e.credentialLookup??await Si(t,e.flagApiKey??t.POTATO_API_KEY),{found:i,warning:n}=r,s=i?.path??Ge(t),o=KR(e,t,i,s),a=zR(e,t,i),d=dl(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.","",d),{authenticated:!1,output:u.join(`
52
- `)};let{value:l,source:c}=a;if(u.push(`Platform: ${l} (${c})`,`API key: ${e.showToken===!0?o.value:Hf(o.value)} (${o.source})`,d),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 ${Ge(t)}.`);let p=e.probe?.({baseUrl:l,apiKey:o.value})??ct({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
- `)}}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 pg=require("crypto"),Xt=require("fs/promises"),Ss=require("path");var Er=require("path");function cm(){let e=WR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function WR(e=process.argv[1]?Er.dirname(process.argv[1]):process.cwd(),t=Er.sep==="\\"){let r=t?lm(e):e;return(i)=>{if(!i)return;let n=t?lm(i):i,{dir:s,base:o,ext:a}=Er.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let d=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${d}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${d}`:d}return d}}function lm(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var pl=(e)=>{if("flags"in e){let t=dm(e.flags),r=um(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Xn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,HR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function HR(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 dm=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Ci(r)]).filter(([,t])=>t!==void 0)),um=(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?Xn(i):void 0]}))},Ci=(e)=>e===void 0?void 0:e.variant??e.enabled,Xn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var JR=["$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"],Oi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return JR.forEach(i),t.forEach(i),r};var Se=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 fl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var YR="NativeGzipValidationError",XR=31,ZR=139,eC=8,tC=(e)=>e.length>=2&&e[0]===XR&&e[1]===ZR;var ji,rC=()=>{if(ji)return ji;ji=[];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;ji[e]=t>>>0}return ji},iC=(e)=>{let t=rC(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Zn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=YR,t},nC=async(e,t)=>{if(e.size<18)Zn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!tC(r)||r[2]!==eC)Zn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==iC(t))Zn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Zn("invalid-size")};async function Kt(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(),[d]=await Promise.all([a,o]);return await nC(d,i),d}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var sC=["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"],pm=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return sC.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function Ir(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 aC=Array.isArray,fm=Object.prototype,r1=fm.hasOwnProperty,es=fm.toString,Ze=aC||function(e){return es.call(e)==="[object Array]"};var Fi=(e)=>e===Object(e)&&!Ze(e);var zt=(e)=>e===void 0,ht=(e)=>es.call(e)=="[object String]",mm=(e)=>ht(e)&&e.trim().length===0,hm=(e)=>e===null;var Ti=(e)=>es.call(e)=="[object Number]"&&e===e;var gm=(e)=>es.call(e)==="[object Boolean]";var ym=(e)=>e instanceof Error;function ts(e){return e===null||typeof e!="object"}function Wt(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function _m(e){return Wt(e,"ErrorEvent")}function Sr(e){return typeof Event<"u"&&lC(e,Event)}function bm(e){return Wt(e,"Object")}function lC(e,t){try{return e instanceof t}catch{return!1}}function ki(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ti(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),ki(n||r,t,r,i)}var cC=86400000,dC=1,uC=10;function Pm(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??dC,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??uC}}class ml{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ki(e.bucketSize,0,100,e._logger),this._refillRate=ki(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ki(e.refillInterval,0,cC,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 Ht{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Ht(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 Ht(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 Ht(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 Ht(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 wm{constructor(e){this.timestamp=0,this.counter=0,this.random=e??pC()}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 Ht.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,Ht.ofInner(e)}}var pC=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),vm,xe=()=>fC().toString(),fC=()=>(vm||(vm=new wm)).generate();class hl{add(e){let t=xe(),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 mC(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var $m=(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)=>$m(`${e} ${s}`,t,r)}},hC=(e)=>e();function Em(e,t=hC){return $m(e,t,mC())}var Rr="Mobile",is="iOS",xr="Android",Cm="Tablet",m1=xr+" "+Cm;var yC="Apple",h1=yC+" Watch",Om="Safari",ns="BlackBerry",jm="Samsung",_C=jm+"Browser",bC=jm+" Internet",ss="Chrome",PC=ss+" OS",vC=ss+" "+is,Fm="Internet Explorer",wC=Fm+" "+Rr,yl="Opera",g1=yl+" Mini",Tm="Edge",$C="Microsoft "+Tm,_l="Firefox",EC=_l+" "+is,bl="Nintendo",Pl="PlayStation",rs="Xbox",IC=xr+" "+Rr,SC=Rr+" "+Om,Ai="Windows",xC=Ai+" Phone";var km="Generic",y1=km+" "+Rr.toLowerCase(),_1=km+" "+Cm.toLowerCase(),RC="Konqueror",CC="Oculus Browser",Im="Vivaldi",OC="Yandex",Sm="Whale",jC="DuckDuckGo",FC="Pale Moon",xm="Waterfox",Rm="Brave",TC="Google Search App",H="(\\d+(\\.\\d+)?)",gl=new RegExp("Version/"+H);var b1=new RegExp(rs,"i"),P1=new RegExp(Pl+" \\w+","i"),v1=new RegExp(bl+" \\w+","i"),kC=new RegExp(ns+"|PlayBook|BB10","i"),AC={"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 w1={[wC]:[new RegExp("rv:"+H)],[$C]:[new RegExp(Tm+"?\\/"+H)],[ss]:[new RegExp("("+ss+"|CrMo)\\/"+H)],[vC]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[Om]:[gl],[SC]:[gl],[yl]:[new RegExp("("+yl+"|OPR)\\/"+H)],[_l]:[new RegExp(_l+"\\/"+H)],[EC]:[new RegExp("FxiOS\\/"+H)],[RC]:[new RegExp("Konqueror[:/]?"+H,"i")],[ns]:[new RegExp(ns+" "+H),gl],[IC]:[new RegExp("android\\s"+H,"i")],[bC]:[new RegExp(_C+"\\/"+H)],[CC]:[new RegExp("OculusBrowser\\/"+H)],[Im]:[new RegExp(Im+"\\/"+H)],[OC]:[new RegExp("YaBrowser\\/"+H)],[Sm]:[new RegExp(Sm+"\\/"+H)],[Rm]:[new RegExp(Rm+"\\/"+H)],[jC]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[FC]:[new RegExp("PaleMoon\\/"+H)],[xm]:[new RegExp(xm+"\\/"+H)],[TC]:[new RegExp("GSA\\/"+H)],[Fm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var $1=[[new RegExp(rs+"; "+rs+" (.*?)[);]","i"),(e)=>[rs,e&&e[1]||""]],[new RegExp(bl,"i"),[bl,""]],[new RegExp(Pl,"i"),[Pl,""]],[kC,[ns,""]],[new RegExp(Ai,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[xC,""];if(new RegExp(Rr).test(t)&&!/IEMobile\b/.test(t))return[Ai+" "+Rr,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=AC[i]||"";if(/arm/i.test(t))n="RT";return[Ai,n]}return[Ai,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[is,t.join(".")]}return[is,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=zt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+xr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+xr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[xr,t.join(".")]}return[xr,""]}],[/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/,[PC,""]],[/Linux|debian/i,["Linux",""]]];var Am="utf8",DC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function NC(e){return typeof e=="string"&&DC.test(e)}function os(e,t){return NC(e)?e:t()}function Dm(e){return e?.replace(/\/+$/,"")}async function Nm(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 vl(){return new Date().toISOString()}function ue(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Lm=(e)=>e instanceof Error;function wl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var qC={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}},A1=qC.info;function $l(e){if(gm(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(Ze(e))return{arrayValue:{values:e.map((t)=>$l(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function Di(e){let t=[];for(let r in e){let i=e[r];if(!(hm(i)||zt(i)))t.push({key:r,value:$l(i)})}return t}var Ni=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function El(e){return String(e)+"000000"}function Il(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 qm(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Sl(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 xl(e,t,r,i){return{resourceMetrics:[{resource:{attributes:Di(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function as(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 Mm=1;class ls{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=Il(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(Ni.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[qm(t,Ni)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=Ze(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=ue(()=>{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 xl(this._buildMetrics(e),Sl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=El(Date.now()),r=new Map;for(let i of e.values()){let n=Il(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:Mm,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:Mm,dataPoints:[]};r.set(n,s)}let o=Di(i.attributes??{}),a=El(i.windowStartMs);if(i.type==="count"){let d={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(d)}else if(i.type==="gauge"){let d={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(d)}else if(i.hist){let d={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:Ni};s.histogram.dataPoints.push(d)}}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 Rl{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 $e={};U_($e,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>_s,DOMExceptionCoercer:()=>Xm,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Li,ErrorCoercer:()=>fs,ErrorEventCoercer:()=>Zm,ErrorPropertiesBuilder:()=>us,EventCoercer:()=>th,ExceptionStepsBuffer:()=>nh,ObjectCoercer:()=>gs,PrimitiveCoercer:()=>ys,PromiseRejectionEventCoercer:()=>rh,ReduceableCache:()=>ih,StringCoercer:()=>ms,chromeStackLineParser:()=>Cl,createDefaultStackParser:()=>jl,createStackParser:()=>Ym,geckoStackLineParser:()=>Ol,getUtf8ByteLength:()=>sh,nodeStackLineParser:()=>Wm,opera10StackLineParser:()=>Vm,opera11StackLineParser:()=>Km,resolveExceptionStepsConfig:()=>Fl,reverseAndStripFrames:()=>Qm,stripReservedExceptionStepFields:()=>aO,winjsStackLineParser:()=>Gm});var cs,Um,ds;function Bm(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(ds&&r.length===Um)return ds;return Um=r.length,ds=r.reduce((i,n)=>{if(!cs)cs={};let s=cs[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,cs[n]=[u,l];break}}}return i},{}),ds}var GC=4;class us{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&&Ze(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:Bm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=GC))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 et(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!zt(i))s.lineno=i;if(!zt(n))s.colno=n;return s}var ps=(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 VC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,KC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,zC=/\((\S*)(?::(\d+))(?::(\d+))\)/,Cl=(e,t)=>{let r=VC.exec(e);if(r){let[,n,s,o]=r;return et(t,n,se,+s,+o)}let i=KC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=zC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ps(i[1]||se,i[2]);return et(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var WC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,HC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ol=(e,t)=>{let r=WC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=HC.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]=ps(s,n),et(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var JC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Gm=(e,t)=>{let r=JC.exec(e);return r?et(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var QC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Vm=(e,t)=>{let r=QC.exec(e);return r?et(t,r[2],r[3]||se,+r[1]):void 0},YC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Km=(e,t)=>{let r=YC.exec(e);return r?et(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var XC=/^\s*[-]{4,}$/,ZC=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,eO=/^Promise\.(?:all|any)$/,tO=/^index \d+$/,rO="node:internal/promise",Wm=(e,t)=>{let r=e.match(ZC);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 c=i.indexOf(".Module");if(c>0)s=s.slice(c+1),i=i.slice(0,c)}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 d=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(d?.match(/\/[A-Z]:/))d=d.slice(1);if(!d&&r[5]&&!u)d=r[5];if(eO.test(s)&&tO.test(d||""))d=rO;return{filename:d?decodeURI(d):void 0,module:void 0,function:s,lineno:zm(r[3]),colno:zm(r[4]),in_app:iO(d||"",u),platform:t}}if(e.match(XC))return{filename:e,platform:t}};function iO(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 zm(e){return parseInt(e||"",10)||void 0}var Hm=/\(error: (.*)\)/,Jm=50;function Qm(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Jm).map((r)=>({...r,filename:r.filename||nO(t).filename,function:r.function||se}))}function nO(e){return e[e.length-1]||{}}function jl(){return Ym("web:javascript",Cl,Ol)}function Ym(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 d=Hm.test(a)?a.replace(Hm,"$1"):a;if(!d.match(/\S*Error: /)){for(let u of t){let l=u(d,e);if(l){n.push(l);break}}if(n.length>=Jm)break}}return Qm(n)}}class Xm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=ht(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 Wt(e,"DOMException")}isDOMError(e){return Wt(e,"DOMError")}}class fs{match(e){return ym(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 Zm{constructor(){}match(e){return _m(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 sO=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ms{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(sO);if(i)t=i[1],r=i[2];return[t,r]}}var eh=["fatal","error","warning","log","info","debug"];function hs(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 gs{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 Sr(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=hs(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return ht(e)&&!mm(e)&&eh.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(Lm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class th{match(e){return Sr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${hs(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class ys{match(e){return ts(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class rh{match(e){return Wt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Sr(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(ts(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 ih{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 Li={MESSAGE:"$message",TIMESTAMP:"$timestamp"},oO=new Set([Li.MESSAGE,Li.TIMESTAMP]),_s={enabled:!0,max_bytes:32768};function Fl(e){if(!e)return{..._s};return{enabled:e.enabled??_s.enabled,max_bytes:lO(e.max_bytes,_s.max_bytes)}}function aO(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(oO.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class nh{constructor(e){this._entries=[],this._totalBytes=0,this._config=Fl(e)}setConfig(e){this._config=Fl(e),this._trimToMaxBytes()}add(e){let t=cO(e);if(!t)return;let r=sh(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 lO(e,t){if(!Ti(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function cO(e){let t;try{t=Ir(e)}catch{return}try{let r=JSON.parse(t);if(!Fi(r))return;let i=r,n=i[Li.MESSAGE],s=i[Li.TIMESTAMP];if(!ht(n)||n.trim().length===0)return;if(!ht(s)&&!Ti(s))return;return{step:i,json:t}}catch{return}}function sh(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 jt 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 Jt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var lh=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function oh(e){if(e instanceof jt){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 dO(e){return typeof e=="object"&&(e instanceof jt||ch(e))}function ch(e){return e instanceof Jt}function uO(e){if(e instanceof jt)return e.status===502||e.status===504;if(!(e instanceof Jt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Cr(e){return typeof e=="object"&&e instanceof jt&&e.status===413}function qi(e){if(e instanceof jt)return e.status===408||e.status===429||e.status>=500;return ch(e)}function ah(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tl="default";class bs{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new us([new fs,new gs,new ms,new ys],jl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new hl,this._events=new Rl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=Em("[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=Dm(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:qi},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=!fl()||(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(Se.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Se.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Se.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(lh(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=Oi(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}`,d={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)d.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)d.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(d)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:uO},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:pl(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof jt)return{type:"api_error",statusCode:e.status};if(e instanceof Jt){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=Ci(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 d=a.response;if(d.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(d.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:d?.requestId,quotaLimited:d.quotaLimited};return d}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(Se.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Se.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Se.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Tl}persistedQueueKeyForRoute(e){return Se.Queue}getActiveQueueRoutes(){return[Tl]}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=ue(()=>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=ah(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=os(n.uuid,xe),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:vl(),uuid:os(t?.uuid,xe)};if(t?.disableGeoip??this.disableGeoip){if(!ah(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 oh(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(()=>wl([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),wl([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=Tl){let i={api_key:this.apiKey,batch:e,sent_at:vl()};if(this.historicalMigration)i.historical_migration=!0;let n=Ir(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await Kt(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)),d=async()=>{let c=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,c),i=c,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Cr(l))return!1;return qi(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Cr(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 Jt))await d();throw this._events.emit("error",l),l}await d(),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 Kt(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(Cr(s))return!1;return qi(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(s instanceof Jt)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 Kt(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(Cr(s))return!1;return qi(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(qi(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,Am)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await Nm(async()=>{let o=new AbortController,a=i??this.requestTimeout,d=ue(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(c){throw new Jt(c)}finally{clearTimeout(d)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new jt(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(!dO(n))throw n;await oh(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=ue(()=>{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 ph=require("fs"),fh=require("readline"),Ps=new $e.ReduceableCache(25),mh=new $e.ReduceableCache(20),kl=7,gO=1000,yO=1e4;async function hh(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"||vO(o)||wO(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(mh.get(n))continue;let s=t[n];if(!s)continue;s.sort((d,u)=>d-u);let o=EO(s);if(o.every((d)=>$O(n,d)))continue;let a=IO(Ps,n,{});i.push(_O(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)bO(e,Ps);return Ps.reduce(),e}function _O(e,t,r){return new Promise((i)=>{let n=ph.createReadStream(e),s=fh.createInterface({input:n});function o(){n.destroy(),i()}let a=0,d=0,u=t[d];if(u===void 0)return void o();let l=u[0],c=u[1];function p(){mh.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]=SO(f,0),a>=c){if(d===t.length-1){s.close(),s.removeAllListeners();return}d++;let m=t[d];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],c=m[1]}})})}function bO(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;PO(r.lineno,r,i)}}function PO(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=gh(e);n<e;n++){let s=r[n];if(s===void 0)return void dh(t);t.pre_context.push(s)}if(r[e]===void 0)return void dh(t);t.context_line=r[e];let i=yh(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 dh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function vO(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function wO(e){if(e.lineno!==void 0&&e.lineno>yO)return!0;if(e.colno!==void 0&&e.colno>gO)return!0;return!1}function $O(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 EO(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=uh(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+kl;else n.push(i),i=uh(s);t++}return n}function uh(e){return[gh(e),yh(e)]}function gh(e){return Math.max(1,e-kl)}function yh(e){return e+kl}function IO(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function SO(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 Or=require("path");function _h(e=process.cwd()){let t=Or.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(Or.isAbsolute(s.filename))s.filename=r(Or.relative(i,r(s.filename)))}return n}}var bh="5.46.1";var gt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Qt{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 Qt({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(gt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(gt.QUOTA_LIMITED);if(t===void 0)n.push(gt.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 Ph(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 xO=60000,RO=1152921504606847000,CO=["is_not","is_set"];class jr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,jr.prototype)}}function Eh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);Eh(this,q)}}class tt extends Error{constructor(e){super(e);Eh(this,tt)}}class Al{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(d){if(d instanceof tt||d instanceof q)this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${e}: ${d.message}`));else if(d instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${d}`))}}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:d,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=d,u)i[a.key]=u}catch(d){if(d instanceof tt||d instanceof q)this.logMsgIfDebug(()=>console.debug(`${d.name} when computing flag locally: ${a.key}: ${d.message}`));else if(d instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${d}`));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 d=this.groupTypeMapping[String(a)];if(!d)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(!(d 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[d];return await this.matchFeatureFlagProperties(e,i[d],u,t)}{let d=this.getBucketingValueForFlag(e,r,n);if(d===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,d,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:d,groupProperties:u}=i,l=!1,c;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 _=this.groupTypeMapping[String(f)];if(!_||!(_ in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(_ in u)){l=!0;continue}m=u[_],h=d[_]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let _=p.variant,b=n.multivariate?.variants||[];c=_&&b.some((v)=>v.key===_)?_:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof tt)throw f;if(f instanceof q)l=!0;else throw f}if(c!==void 0)return c;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 d=a.type,u=!1;if(d==="cohort"){let l=await Sh(a,i,this.cohorts,this.debugMode,(c)=>this.evaluateFlagDependency(c,i,n));u=a.operator==="not_in"?!l:l}else u=d==="flag"?await this.evaluateFlagDependency(a,i,n):Ih(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await vh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await vh(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(xO,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 jr(`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 jr(`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 jr(`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 jr)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=ue(()=>{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 vh(e,t,r=""){let i=await Ph(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/RO}function Ih(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&&!CO.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((c)=>String(c).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function d(u,l,c){if(c==="gt")return u>l;if(c==="gte")return u>=l;if(c==="lt")return u<l;if(c==="lte")return u<=l;throw Error(`Invalid operator: ${c}`)}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 wh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return wh(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 d(l,u,s);return d(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=kO(String(n));if(u==null)u=$h(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=$h(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return ke(oe(String(o)),oe(String(n)))===0;case"semver_neq":return ke(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return ke(oe(String(o)),oe(String(n)))>0;case"semver_gte":return ke(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return ke(oe(String(o)),oe(String(n)))<0;case"semver_lte":return ke(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:c}=jO(String(n));return ke(u,l)>=0&&ke(u,c)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:c}=FO(String(n));return ke(u,l)>=0&&ke(u,c)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:c}=TO(String(n));return ke(u,l)>=0&&ke(u,c)<0}default:throw new q(`Unknown operator: ${s}`)}}function OO(e,t){if(!(e in t))throw new tt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Sh(e,t,r,i=!1,n){let s=String(e.value);OO(s,r);let o=r[s];return xh(o,t,r,i,n)}async function xh(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 d of o)try{let u=await xh(d,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof tt)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${d} 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 d of o)try{let u;if(d.type==="cohort")u=await Sh(d,t,r,i,n);else if(d.type==="flag"){if(!n)throw new q(`Flag dependency '${d.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(d)}else u=Ih(d,t);let l=d.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 tt)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${d} 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 wh(e){try{return new RegExp(e),!0}catch(t){return!1}}function Rh(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=(d)=>{if(d===void 0||d==="")return 0;return Rh(d,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function ke(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 jO(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 FO(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 TO(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(d)=>{try{return Rh(d,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 d=n(i[1]);o=[s,d,0],a=[s,d+1,0]}return{lower:o,upper:a}}function $h(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 kO(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 AO(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 Ch(e,t){globalThis.process?.on("uncaughtException",AO(e,t))}function Oh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var DO=2000;class rt{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new ml({...Pm(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Fi(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())Ch(this.onException.bind(this),this.onFatalError.bind(this)),Oh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!rt.isPreviouslyCapturedError(e)){let r=await rt.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(DO),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class Dl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function NO(e){return e==="v0"||e==="v1"}function jh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return NO(e)?e:"v0"}var Mi="analytics",Ui="ai";function Fh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class Fr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(Fr.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 Nl(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 LO(e){return typeof e=="string"?e:void 0}var qO=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Nl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Nl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Nl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:LO}],MO=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function UO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function BO(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 Th(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function GO(e){let r={...UO(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of qO)if(s in r){let d=a(r[s]);if(d!==void 0)i[o]=d;delete r[s]}let n={};for(let{property:s,field:o}of MO)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,Th(r,"$set",e.$set),Th(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:BO(e.timestamp),...n,options:i,properties:r}}function kh(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(GO)};if(r)i.historical_migration=!0;return i}var VO="/i/v1/analytics/events",KO=30000,zO=new Set([408,500,502,503,504]);class Ll{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??KO,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>ue(i,r))),this.generateRequestId=t.generateRequestId??xe,this.compress=t.compress??Kt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=kh(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${VO}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let d=1;d<=a;d++){let u=d===a,l=Ir({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),c;try{c=await this.sendOnce(n,l,d,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(d));continue}let{status:p}=c;if(p<200||p>=300){if(!u&&zO.has(p)){let _=this.parseRetryAfter(c);await this.cancelBody(c),await this.sleep(this.backoffDelay(d,_));continue}let g=await this.buildHttpError(c,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(c)}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 Fr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(c);await this.sleep(this.backoffDelay(d,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let d=await this.compress(t,this.config.isDebug);if(d!==null)s=d,n["Content-Encoding"]="gzip"}let o=new AbortController,a=ue(()=>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 Fr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Fr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var WO=100,Ah=30000,HO=50000,JO=50,QO=500,YO="https://us.i.posthog.com",Dh=new Set;function vs(e,t){if(Dh.has(e))return;Dh.add(e),console.warn(`[PostHog] ${t}`)}function XO(e){return typeof e=="string"?e.trim():""}function ZO(e){return(typeof e=="string"?e.trim():"")||void 0}function ej(e){return(typeof e=="string"?e.trim():"")||YO}function tj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function rj(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 ql extends bs{constructor(e,t={}){let r=XO(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:ej(t.host),personalApiKey:ZO(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new Dl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=jh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,WO):Ah,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 Al({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 rt(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||HO}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??QO,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??JO;this._waitUntilCycle.timer=ue(()=>{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"&&Fh(e)?Ui:Mi}persistedQueueKeyForRoute(e){return e===Ui?Se.AiQueue:Se.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Mi,Ui]:[Mi]}async sendBatch(e,t,r=Mi){if(this.captureMode!=="v1"||r===Ui)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 Ll({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 bh}get metrics(){if(!this._metrics)this._metrics=new ls(this,as(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 d={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,d):this.enqueue(e,u,d)}).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=tj(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=Ah){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:d,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,_,b,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,c,{matchValue:i});if(x){f=!0;let T=x.value;_=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 tt||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(c.distinctId,c.groups,d,u,o,[e]);if(E===void 0)g=gt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(gt.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(gt.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(gt.FLAG_MISSING);else{_=T.metadata?.id,b=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:_,$feature_flag_version:b,$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){vs("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(vs("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){vs("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:d,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(c.distinctId,c.groups,d,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 Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:d,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,d,u);d=l.allPersonProperties,u=l.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,d),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,o),b=new Set;if(_)for(let[w,I]of Object.entries(_.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:_.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},b.add(w)}if((_?_.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,d,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(b.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 Qt({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))}`:"",d=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(d))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(d);else this.distinctIdHasSentFlagCalls[t]=new Set([d]);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)=>ue(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=ue(()=>{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(bm(s)&&t&&n in t){let o={};for(let[a,d]of Object.entries(s))o[String(a)]=String(d);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 d={};for(let[u,l]of Object.entries(t||{}))d[u]=String(l);return await this.getAllFlags(e,{groups:d,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[u,l]of Object.entries(t||{}))d[u]=String(l);return await this.getAllFlags(e,{groups:d,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(!rt.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(rt.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(!rt.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(rt.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:d,disableGeoip:u,uuid:l}=e,c=this.context?.get(),p=t.includeContextProperties??!0,f=r||c?.distinctId,m=p?{...this.props,...c?.properties||{},...n||{}}:{...n||{}};if(!f)f=xe(),m.$process_person_profile=!1;if(p&&c?.sessionId&&!m.$session_id)m.$session_id=c.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?Oi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:d,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let _=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){vs("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 b=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,b);return rj(v)}return{}}).catch(()=>({})).then((b)=>{let v=g.groups||s;return{...b,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof _.$raw_user_agent=="string"){if(pm(_.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",_.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:_,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 Nh=require("async_hooks");class Ml{constructor(){this.storage=new Nh.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 ij(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 d=o.tags[Lh.POSTHOG_ID_TAG];if(d===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${d}`,u).toString();o.tags["PostHog Person URL"]=l;let c=o.exception?.values||[],p=c.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:c[0]?.value||o.message,$exception_type:c[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:c[0]?.value||o.message,$sentry_exception_type:c[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:d,properties:f});return o}}class Lh{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(ij(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ul extends ql{getLibraryId(){return"posthog-node"}initializeContext(){return new Ml}createErrorPropertiesBuilder(){return new $e.ErrorPropertiesBuilder([new $e.EventCoercer,new $e.ErrorCoercer,new $e.ObjectCoercer,new $e.StringCoercer,new $e.PrimitiveCoercer],$e.createStackParser("node:javascript",$e.nodeStackLineParser),[cm(),hh,_h()])}}var ee=require("fs/promises"),fe=require("path");var qh={name:"@toloka-platform/sdk",version:"0.1.0-preview.5",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","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts",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 Mh=require("fs/promises"),Uh=require("path"),ws=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),$s=(e)=>ws(e,"ENOENT"),Tr=async(e)=>{try{return await Mh.lstat(e)}catch(t){if($s(t))return;throw t}},Bi=async(e,t,r="write")=>{let i=e;for(let n of t.split("/")){i=Uh.join(i,n);let s=await Tr(i);if(s===void 0)return;y(!s.isSymbolicLink(),`Refusing to ${r} through symbolic link ${i}.`)}};var Kh=require("crypto"),Y=require("fs/promises"),pe=require("path"),zh=require("url");var sj=(e)=>{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?void 0:t},Gi=(e)=>{if(e instanceof re){let t=sj(e);return t===void 0?e.message:`${e.message}
56
- ${t}`}return e instanceof Error?e.message:String(e)};var Bl=zh.fileURLToPath(new URL("../../skills","file:///Users/gzarip/code/potato-sdk-dx/packages/sdk/src/cli/skill.ts")),Es="catalog.json",Ar=".agents/skills",kr="SKILL.md",Wh="skills",Bh=500,Gh=1048576,Hh=64,oj=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,aj=/^[a-f0-9]{64}$/u,Jh=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Vh=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),Gl=(e)=>typeof e==="string"&&e.trim().length>0,lj=(e)=>typeof e==="string"&&e.length<=Hh&&oj.test(e),cj=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),dj=(e,t)=>{y(Jh(e),t("every skill must be an object."));let{id:r,name:i,description:n,tags:s,version:o,digest:a,files:d}=e;return y(lj(r),t(`skill id ${JSON.stringify(r)} must be at most ${Hh} lowercase letters, digits, and single hyphens.`)),y(Gl(i),t(`skill ${r} needs a name.`)),y(Gl(n),t(`skill ${r} needs a description.`)),y(Vh(s),t(`skill ${r} tags must be strings.`)),y(Gl(o),t(`skill ${r} needs a version.`)),y(typeof a==="string"&&aj.test(a),t(`skill ${r} digest must be the sha256 hex digest of its files.`)),y(Vh(d)&&d.includes(kr),t(`skill ${r} files must include ${kr}.`)),y(d.every(cj),t(`skill ${r} files must be relative paths inside its directory.`)),y(new Set(d).size===d.length,t(`skill ${r} lists a file more than once.`)),{id:r,name:i,description:n,tags:s,version:o,digest:a,files:d}},uj=(e,t)=>{try{return JSON.parse(e)}catch(r){throw Error(`Invalid skill catalog ${t}: ${Gi(r)}`)}},Qh=async(e)=>{try{return(await Y.stat(e)).isFile()}catch(t){if(ws(t,"ENOENT","ENOTDIR"))return!1;throw t}},Yh=async(e)=>{let t=pe.join(e,Wh);if(await Qh(pe.join(t,Es)))return t;let r=pe.dirname(e);return r===e?void 0:Yh(r)};async function pj(e=process.argv[1]){let t=e===void 0?void 0:await Y.realpath(e),r=t===void 0?void 0:await Yh(pe.dirname(t));if(r!==void 0)return r;let i=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return y(await Qh(pe.join(Bl,Es)),`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${Wh}/${Es} in a directory above its runtime entry, but ${i}, and the source checkout catalog ${Bl} is absent. Reinstall @toloka-platform/sdk.`),Bl}var Vl=async()=>fj(await pj());async function fj(e){let t=pe.join(e,Es),r=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:i}=await Y.stat(t);y(i<=Gh,r(`the manifest is ${i} bytes; the limit is ${Gh} bytes.`));let n=uj(await Y.readFile(t,"utf8"),t);y(Jh(n)&&Array.isArray(n.skills),r("expected an object with a skills array.")),y(n.skills.length<=Bh,r(`${n.skills.length} skills exceed the limit of ${Bh}.`));let s=n.skills.map((a)=>dj(a,r)),o=new Set;for(let a of s)y(!o.has(a.id),r(`skill id ${a.id} appears more than once.`)),o.add(a.id);return{root:e,manifestPath:t,skills:s}}async function Xh(e,t){let r=Kh.createHash("sha256");for(let i of t.toSorted())r.update(i),r.update("\x00"),r.update(await Y.readFile(pe.join(e,i))),r.update("\x00");return r.digest("hex")}var mj=(e,t)=>{let r=t.trim().toLowerCase();return e.filter((i)=>[i.id,i.name,i.description,...i.tags].some((n)=>n.toLowerCase().includes(r)))};async function hj(e,t){let r=pe.join(e,Ar,t.id);if(await Tr(r)===void 0)return"not-installed";try{return await Xh(r,t.files)===t.digest?"current":"stale"}catch(i){if(ws(i,"ENOENT","ENOTDIR"))return"stale";throw i}}var Zh=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(r)=>({...r,status:await hj(e,r)}))),gj=async(e,t,r,i)=>{await e(r,i);try{await e(t,r)}catch(n){try{await e(i,r)}catch(s){throw Error(`Failed to replace ${r}; the previous version is preserved at ${i}. ${Gi(s)}`,{cause:n})}throw n}await Y.rm(i,{recursive:!0,force:!0})};async function yj({catalog:e,sourceRoot:t,skillId:r,force:i=!1,rename:n=Y.rename}){let s=e.skills.find((c)=>c.id===r);y(s,`Skill ${JSON.stringify(r)} is not in the catalog. Run \`toloka skill list\` to see the available skills.`);let o=`${Ar}/${s.id}`;await Bi(t,o);let a=pe.join(t,o),d=await Tr(a);y(d===void 0||i,`${o} already exists. Re-run with --force to replace it with the catalog version of ${s.id}.`);let u=pe.dirname(a);await Y.mkdir(u,{recursive:!0});let l=await Y.mkdtemp(pe.join(u,`.${s.id}.tmp-`));try{for(let c of s.files){let p=pe.join(l,c);await Y.mkdir(pe.dirname(p),{recursive:!0}),await Y.copyFile(pe.join(e.root,s.id,c),p)}if(y(await Xh(l,s.files)===s.digest,`Skill ${s.id} failed its digest check: the packaged files do not match the catalog digest ${s.digest}. Nothing was installed.`),d===void 0)await n(l,a);else await gj(n,l,a,`${l}.backup`)}catch(c){throw await Y.rm(l,{recursive:!0,force:!0}),c}return{skill:s,directory:a,replaced:d!==void 0}}var eg=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let r=Math.max(...e.map((n)=>n.id.length)),i=Math.max(...e.map((n)=>n.status.length));return e.flatMap((n)=>[`${n.id.padEnd(r)} ${n.status.padEnd(i)} ${n.name}`,` ${n.description}`]).join(`
57
- `)};async function tg({sourceRoot:e,json:t,io:r}){let i=await Vl();r.stdout(eg(await Zh({sourceRoot:e,skills:i.skills}),t))}async function rg({sourceRoot:e,query:t,json:r,io:i}){let n=await Vl(),s=await Zh({sourceRoot:e,skills:mj(n.skills,t)});if(r||s.length>0){i.stdout(eg(s,r));return}i.stdout(`No skills match ${JSON.stringify(t)}. Run \`toloka skill list\` to see the catalog.`)}async function ig({sourceRoot:e,skillId:t,force:r,io:i}){let n=await Vl(),s=await yj({catalog:n,sourceRoot:e,skillId:t,force:r}),o=`${Ar}/${s.skill.id}`,a=s.skill.files.length;i.stdout(`${s.replaced?"Replaced":"Installed"} ${s.skill.id} in ${o} (${a} ${a===1?"file":"files"}). Start with ${o}/${kr}.`)}var Ve=qh.version,Ke="@toloka-platform/sdk",Hl="toloka-bootstrap",sg=`.claude/skills/${Hl}/SKILL.md`,og=`.cursor/rules/${Hl}.mdc`,Yt="AGENTS.md",_j=[sg,og,Yt],Dr={begin:"<toloka>",end:"</toloka>"},Kl={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},zl=/<!-- toloka:sdk-version ([^\s>]+) -->/u,ag=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),Nr=async(e)=>{try{return await ee.readFile(e,"utf8")}catch(t){if($s(t))return;throw t}},Wl=async(e)=>{try{return(await ee.lstat(e)).isDirectory()}catch(t){if($s(t))return!1;throw t}},Jl=(e)=>zl.test(e),lg=`Generated by \`${Ke}\` version \`${Ve}\`.
58
- <!-- toloka:sdk-version ${Ve} -->`,bj=`${Dr.begin}
51
+ This does not revoke the key. Delete it in console.toloka.ai to do that.`}}var vm=(e)=>e.find((t)=>t!==void 0),IR=(e,t,r,n)=>vm([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 ${n}`}]),ER=(e,t,r)=>{let n=ht(t);return vm([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"},n===void 0?void 0:{value:n,source:`from ENV=${t.ENV}`},r===void 0?void 0:{value:r.credentials.baseUrl,source:"stored"}])??{value:Vt,source:"default"}};async function wm(e={}){let t=e.environment??process.env,r=e.credentialLookup??await xn(t,e.flagApiKey??t.POTATO_API_KEY),{found:n,warning:i}=r,s=n?.path??Ge(t),o=IR(e,t,n,s),a=ER(e,t,n),l=gl(e.project,n?.credentials),d=i===void 0?[]:[i,""];if(o===void 0)return d.push("Not logged in.","","Run toloka login to store an API key for this machine.","",l),{authenticated:!1,output:d.join(`
52
+ `)};let{value:c,source:p}=a;if(d.push(`Platform: ${c} (${p})`,`API key: ${e.showToken===!0?o.value:dm(o.value)} (${o.source})`,l),t.POTATO_API_KEY!==void 0&&n!==void 0)d.push("",`POTATO_API_KEY is set, so the key stored in ${n.path} is ignored.`);if(n?.legacy===!0)d.push("",`Credentials still live at the old path ${n.path}. Run toloka login to move them to ${Ge(t)}.`);let h=e.probe?.({baseUrl:c,apiKey:o.value})??ct({baseUrl:c,apiKey:o.value});try{let u=await h.projects.listPage({limit:1});return d.push("",`Reachable: ${u.pagination.total} project(s) visible.`),{authenticated:!0,output:d.join(`
53
+ `)}}catch(u){let f=u instanceof Error?u.message:String(u);return d.push("",`Not reachable: ${f}`,"","Run toloka login to store a working key."),{authenticated:!1,output:d.join(`
54
+ `)}}}var xg=require("crypto"),Xt=require("fs/promises"),js=require("path");var Er=require("path");function Im(){let e=SR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function SR(e=process.argv[1]?Er.dirname(process.argv[1]):process.cwd(),t=Er.sep==="\\"){let r=t?$m(e):e;return(n)=>{if(!n)return;let i=t?$m(n):n,{dir:s,base:o,ext:a}=Er.posix.parse(i);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let l=decodeURIComponent(o);if(!s)s=".";let d=s.lastIndexOf("/node_modules");if(d>-1)return`${s.slice(d+14).replace(/\//g,".")}:${l}`;if(s.startsWith(r)){let c=s.slice(r.length+1).replace(/\//g,".");return c?`${c}:${l}`:l}return l}}function $m(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _l=(e)=>{if("flags"in e){let t=Em(e.flags),r=Sm(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,s])=>[i,es(s)])),n=Object.fromEntries(Object.entries(t).map(([i,s])=>[i,xR(i,s,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:n}}};function xR(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 Em=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Cn(r)]).filter(([,t])=>t!==void 0)),Sm=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let n=t[r];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map((r)=>{let n=t[r].metadata?.payload;return[r,n?es(n):void 0]}))},Cn=(e)=>e===void 0?void 0:e.variant??e.enabled,es=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var jR=["$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"],On=(e,t=[])=>{let r={},n=(i)=>{if(e[i]!==void 0)r[i]=e[i]};return jR.forEach(n),t.forEach(n),r};var Se=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 bl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var CR="NativeGzipValidationError",OR=31,FR=139,TR=8,AR=(e)=>e.length>=2&&e[0]===OR&&e[1]===FR;var Fn,kR=()=>{if(Fn)return Fn;Fn=[];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;Fn[e]=t>>>0}return Fn},DR=(e)=>{let t=kR(),r=4294967295;for(let n=0;n<e.length;n++)r=t[(r^e[n])&255]^r>>>8;return(4294967295^r)>>>0},ts=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=CR,t},NR=async(e,t)=>{if(e.size<18)ts("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!AR(r)||r[2]!==TR)ts("invalid-header");let n=new DataView(await e.slice(e.size-8).arrayBuffer());if(n.getUint32(0,!0)!==DR(t))ts("invalid-crc");let i=t.length>>>0;if(n.getUint32(4,!0)!==i)ts("invalid-size")};async function zt(e,t=!0,r){try{let n=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),s=i.writable.getWriter(),o=s.write(n).then(()=>s.close()).catch(async(d)=>{try{await s.abort(d)}catch{}throw d}),a=new Response(i.readable).blob(),[l]=await Promise.all([a,o]);return await NR(l,n),l}catch(n){if(r?.rethrow)throw n;if(t)console.error("Failed to gzip compress data",n);return null}}var MR=["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"],xm=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return MR.concat(t).some((n)=>{let i=n.toLowerCase();return r.indexOf(i)!==-1})};function Sr(e){let t=[];return JSON.stringify(e,function(r,n){if(typeof n=="bigint")return n.toString();if(typeof n=="function"||typeof n=="symbol")return;if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(n))return"[Circular]";t.push(n)}return n})??"null"}var qR=Array.isArray,jm=Object.prototype,qN=jm.hasOwnProperty,rs=jm.toString,et=qR||function(e){return rs.call(e)==="[object Array]"};var Tn=(e)=>e===Object(e)&&!et(e);var Kt=(e)=>e===void 0,gt=(e)=>rs.call(e)=="[object String]",Rm=(e)=>gt(e)&&e.trim().length===0,Cm=(e)=>e===null;var An=(e)=>rs.call(e)=="[object Number]"&&e===e;var Om=(e)=>rs.call(e)==="[object Boolean]";var Fm=(e)=>e instanceof Error;function ns(e){return e===null||typeof e!="object"}function Wt(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function Tm(e){return Wt(e,"ErrorEvent")}function xr(e){return typeof Event<"u"&&UR(e,Event)}function Am(e){return Wt(e,"Object")}function UR(e,t){try{return e instanceof t}catch{return!1}}function kn(e,t,r,n,i){if(t>r)n.warn("min cannot be greater than max."),t=r;if(An(e))if(e>r)return n.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return n.warn(" cannot be less than min: "+t+". Using min value instead."),t}return n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),kn(i||r,t,r,n)}var BR=86400000,GR=1,VR=10;function km(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??GR,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??VR}}class Pl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=kn(e.bucketSize,0,100,e._logger),this._refillRate=kn(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=kn(e.refillInterval,0,BR,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,n=Math.floor(r/this._refillInterval);if(n>0){let i=n*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+n*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),n=this._buckets[r];if(n)this._applyRefill(n,t);else n={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=n;if(n.tokens===0)return!0;if(n.tokens--,n.tokens===0)this._onBucketRateLimited?.(e);return n.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Ht{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Ht(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>281474976710655||t>4095||r>1073741823||n>4294967295)throw RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/1099511627776,i[1]=e/4294967296,i[2]=e/16777216,i[3]=e/65536,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new Ht(i)}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 n=0;n<16;n+=4){let i=parseInt(t.substring(2*n,2*n+8),16);r[n+0]=i>>>24,r[n+1]=i>>>16,r[n+2]=i>>>8,r[n+3]=i}return new Ht(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 Ht(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 Nm{constructor(e){this.timestamp=0,this.counter=0,this.random=e??zR()}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 Ht.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,Ht.ofInner(e)}}var zR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Dm,xe=()=>KR().toString(),KR=()=>(Dm||(Dm=new Nm)).generate();class vl{add(e){let t=xe(),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((n)=>n.id<=t&&!r.has(n.promise)).map((n)=>n.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function WR(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Mm=(e,t,r)=>{function n(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{n("debug",...s)},info:(...s)=>{n("log",...s)},warn:(...s)=>{n("warn",...s)},error:(...s)=>{n("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>Mm(`${e} ${s}`,t,r)}},HR=(e)=>e();function Lm(e,t=HR){return Mm(e,t,WR())}var Rr="Mobile",ss="iOS",jr="Android",Vm="Tablet",XN=jr+" "+Vm;var QR="Apple",ZN=QR+" Watch",zm="Safari",os="BlackBerry",Km="Samsung",YR=Km+"Browser",XR=Km+" Internet",as="Chrome",ZR=as+" OS",eC=as+" "+ss,Wm="Internet Explorer",tC=Wm+" "+Rr,$l="Opera",e1=$l+" Mini",Hm="Edge",rC="Microsoft "+Hm,Il="Firefox",nC=Il+" "+ss,El="Nintendo",Sl="PlayStation",is="Xbox",iC=jr+" "+Rr,sC=Rr+" "+zm,Dn="Windows",oC=Dn+" Phone";var Jm="Generic",t1=Jm+" "+Rr.toLowerCase(),r1=Jm+" "+Vm.toLowerCase(),aC="Konqueror",lC="Oculus Browser",qm="Vivaldi",dC="Yandex",Um="Whale",cC="DuckDuckGo",uC="Pale Moon",Bm="Waterfox",Gm="Brave",pC="Google Search App",J="(\\d+(\\.\\d+)?)",wl=new RegExp("Version/"+J);var n1=new RegExp(is,"i"),i1=new RegExp(Sl+" \\w+","i"),s1=new RegExp(El+" \\w+","i"),fC=new RegExp(os+"|PlayBook|BB10","i"),mC={"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 o1={[tC]:[new RegExp("rv:"+J)],[rC]:[new RegExp(Hm+"?\\/"+J)],[as]:[new RegExp("("+as+"|CrMo)\\/"+J)],[eC]:[new RegExp("CriOS\\/"+J)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+J)],[zm]:[wl],[sC]:[wl],[$l]:[new RegExp("("+$l+"|OPR)\\/"+J)],[Il]:[new RegExp(Il+"\\/"+J)],[nC]:[new RegExp("FxiOS\\/"+J)],[aC]:[new RegExp("Konqueror[:/]?"+J,"i")],[os]:[new RegExp(os+" "+J),wl],[iC]:[new RegExp("android\\s"+J,"i")],[XR]:[new RegExp(YR+"\\/"+J)],[lC]:[new RegExp("OculusBrowser\\/"+J)],[qm]:[new RegExp(qm+"\\/"+J)],[dC]:[new RegExp("YaBrowser\\/"+J)],[Um]:[new RegExp(Um+"\\/"+J)],[Gm]:[new RegExp(Gm+"\\/"+J)],[cC]:[new RegExp("(DuckDuckGo|Ddg)\\/"+J)],[uC]:[new RegExp("PaleMoon\\/"+J)],[Bm]:[new RegExp(Bm+"\\/"+J)],[pC]:[new RegExp("GSA\\/"+J)],[Wm]:[new RegExp("(rv:|MSIE )"+J)],Mozilla:[new RegExp("rv:"+J)]};var a1=[[new RegExp(is+"; "+is+" (.*?)[);]","i"),(e)=>[is,e&&e[1]||""]],[new RegExp(El,"i"),[El,""]],[new RegExp(Sl,"i"),[Sl,""]],[fC,[os,""]],[new RegExp(Dn,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[oC,""];if(new RegExp(Rr).test(t)&&!/IEMobile\b/.test(t))return[Dn+" "+Rr,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=r[1],i=mC[n]||"";if(/arm/i.test(t))i="RT";return[Dn,i]}return[Dn,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[ss,t.join(".")]}return[ss,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=Kt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+jr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+jr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[jr,t.join(".")]}return[jr,""]}],[/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/,[ZR,""]],[/Linux|debian/i,["Linux",""]]];var Qm="utf8",hC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gC(e){return typeof e=="string"&&hC.test(e)}function ls(e,t){return gC(e)?e:t()}function Ym(e){return e?.replace(/\/+$/,"")}async function Xm(e,t){let r=null;for(let n=0;n<t.retryCount+1;n++){if(n>0)await new Promise((i)=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function xl(){return new Date().toISOString()}function ue(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var Zm=(e)=>e instanceof Error;function jl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var _C={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}},b1=_C.info;function Rl(e){if(Om(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(et(e))return{arrayValue:{values:e.map((t)=>Rl(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function Nn(e){let t=[];for(let r in e){let n=e[r];if(!(Cm(n)||Kt(n)))t.push({key:r,value:Rl(n)})}return t}var Mn=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Cl(e){return String(e)+"000000"}function Ol(e,t,r,n){let i="";if(n)i=Object.keys(n).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${i}`}function eh(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Fl(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 Tl(e,t,r,n){return{resourceMetrics:[{resource:{attributes:Nn(t)},scopeMetrics:[{scope:{name:r,version:n},metrics:e}]}]}}function ds(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 th=1;class cs{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,n;try{r=t.attributes?{...t.attributes}:void 0,n=Ol(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let i=this._series.get(n);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(n,i)}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(i,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(Mn.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[eh(t,Mn)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=et(t)?t:[t],n=e;for(let i of r)try{let s=i(n);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;n=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return n}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=ue(()=>{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 Tl(this._buildMetrics(e),Fl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Cl(Date.now()),r=new Map;for(let n of e.values()){let i=Ol(n.type,n.name,n.unit,void 0),s=r.get(i);if(!s){if(s={name:n.name,...n.unit&&{unit:n.unit}},n.type==="count")s.sum={aggregationTemporality:th,isMonotonic:!0,dataPoints:[]};else if(n.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:th,dataPoints:[]};r.set(i,s)}let o=Nn(n.attributes??{}),a=Cl(n.windowStartMs);if(n.type==="count"){let l={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:n.total??0};s.sum.dataPoints.push(l)}else if(n.type==="gauge"){let l={attributes:o,timeUnixNano:t,asDouble:n.last??0};s.gauge.dataPoints.push(l)}else if(n.hist){let l={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:n.hist.count,sum:n.hist.sum,min:n.hist.min,max:n.hist.max,bucketCounts:n.hist.bucketCounts,explicitBounds:Mn};s.histogram.dataPoints.push(l)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let n=this._series.get(t);if(!n){if(this._admitNewSeries())this._series.set(t,r);continue}switch(n.windowStartMs=Math.min(n.windowStartMs,r.windowStartMs),n.type){case"count":n.total=(n.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(n.hist){n.hist.count+=r.hist.count,n.hist.sum+=r.hist.sum,n.hist.min=Math.min(n.hist.min,r.hist.min),n.hist.max=Math.max(n.hist.max,r.hist.max);for(let i=0;i<n.hist.bucketCounts.length;i++)n.hist.bucketCounts[i]+=r.hist.bucketCounts[i]}else n.hist=r.hist;break}}}}class Al{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 $e={};ub($e,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Ps,DOMExceptionCoercer:()=>fh,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ln,ErrorCoercer:()=>hs,ErrorEventCoercer:()=>mh,ErrorPropertiesBuilder:()=>fs,EventCoercer:()=>gh,ExceptionStepsBuffer:()=>bh,ObjectCoercer:()=>_s,PrimitiveCoercer:()=>bs,PromiseRejectionEventCoercer:()=>yh,ReduceableCache:()=>_h,StringCoercer:()=>gs,chromeStackLineParser:()=>kl,createDefaultStackParser:()=>Nl,createStackParser:()=>ph,geckoStackLineParser:()=>Dl,getUtf8ByteLength:()=>Ph,nodeStackLineParser:()=>lh,opera10StackLineParser:()=>sh,opera11StackLineParser:()=>oh,resolveExceptionStepsConfig:()=>Ml,reverseAndStripFrames:()=>uh,stripReservedExceptionStepFields:()=>qC,winjsStackLineParser:()=>ih});var us,rh,ps;function nh(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(ps&&r.length===rh)return ps;return rh=r.length,ps=r.reduce((n,i)=>{if(!us)us={};let s=us[i];if(s)n[s[0]]=s[1];else{let o=e(i);for(let a=o.length-1;a>=0;a--){let d=o[a]?.filename,c=t[i];if(d&&c){n[d]=c,us[i]=[d,c];break}}}return n},{}),ps}var wC=4;class fs{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let n=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(n,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,n),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&et(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 n;if(e.stack!=""&&e.stack!=null)n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:n}}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 n=[r];if(e.cause!=null)n.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return n}buildParsingContext(e){return{chunkIdMap:nh(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let n=(s,o)=>{if(!(o<=wC))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)=>n(s,r),next:(s)=>n(s,r+1)}}}var oe="?";function tt(e,t,r,n,i){let s={platform:e,filename:t,function:r==="<anonymous>"?oe:r,in_app:!0};if(!Kt(n))s.lineno=n;if(!Kt(i))s.colno=i;return s}var ms=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:oe,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var $C=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,IC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,EC=/\((\S*)(?::(\d+))(?::(\d+))\)/,kl=(e,t)=>{let r=$C.exec(e);if(r){let[,i,s,o]=r;return tt(t,i,oe,+s,+o)}let n=IC.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=EC.exec(n[2]);if(a)n[2]=a[1],n[3]=a[2],n[4]=a[3]}let[s,o]=ms(n[1]||oe,n[2]);return tt(t,o,s,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var SC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Dl=(e,t)=>{let r=SC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=xC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let i=r[3],s=r[1]||oe;return[s,i]=ms(s,i),tt(t,i,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var jC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ih=(e,t)=>{let r=jC.exec(e);return r?tt(t,r[2],r[1]||oe,+r[3],r[4]?+r[4]:void 0):void 0};var RC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,sh=(e,t)=>{let r=RC.exec(e);return r?tt(t,r[2],r[3]||oe,+r[1]):void 0},CC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,oh=(e,t)=>{let r=CC.exec(e);return r?tt(t,r[5],r[3]||r[4]||oe,+r[1],+r[2]):void 0};var OC=/^\s*[-]{4,}$/,FC=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,TC=/^Promise\.(?:all|any)$/,AC=/^index \d+$/,kC="node:internal/promise",lh=(e,t)=>{let r=e.match(FC);if(r){let n,i,s,o,a;if(r[1]){s=r[1];let c=s.lastIndexOf(".");if(s[c-1]===".")c--;if(c>0){n=s.slice(0,c),i=s.slice(c+1);let p=n.indexOf(".Module");if(p>0)s=s.slice(p+1),n=n.slice(0,p)}o=void 0}if(i)o=n,a=i;if(i==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||oe,s=o?`${o}.${a}`:a;let l=r[2]?.startsWith("file://")?r[2].slice(7):r[2],d=r[5]==="native";if(l?.match(/\/[A-Z]:/))l=l.slice(1);if(!l&&r[5]&&!d)l=r[5];if(TC.test(s)&&AC.test(l||""))l=kC;return{filename:l?decodeURI(l):void 0,module:void 0,function:s,lineno:ah(r[3]),colno:ah(r[4]),in_app:DC(l||"",d),platform:t}}if(e.match(OC))return{filename:e,platform:t}};function DC(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 ah(e){return parseInt(e||"",10)||void 0}var dh=/\(error: (.*)\)/,ch=50;function uh(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,ch).map((r)=>({...r,filename:r.filename||NC(t).filename,function:r.function||oe}))}function NC(e){return e[e.length-1]||{}}function Nl(){return ph("web:javascript",kl,Dl)}function ph(e,...t){return(r,n=0)=>{let i=[],s=r.split(`
55
+ `);for(let o=n;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let l=dh.test(a)?a.replace(dh,"$1"):a;if(!l.match(/\S*Error: /)){for(let d of t){let c=d(l,e);if(c){i.push(c);break}}if(i.length>=ch)break}}return uh(i)}}class fh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=gt(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 Wt(e,"DOMException")}isDOMError(e){return Wt(e,"DOMError")}}class hs{match(e){return Fm(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 mh{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 MC=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class gs{match(e){return typeof e=="string"}coerce(e,t){let[r,n]=this.getInfos(e);return{type:r??"Error",value:n??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,n=e.match(MC);if(n)t=n[1],r=n[2];return[t,r]}}var hh=["fatal","error","warning","log","info","debug"];function ys(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){let i=r.slice(0,n).join(", ");if(!(i.length>t)){if(n===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class _s{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 xr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let n=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")n+=` with message: '${e.message}'`;return n}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=ys(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return gt(e)&&!Rm(e)&&hh.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(Zm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class gh{match(e){return xr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${ys(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class bs{match(e){return ns(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class yh{match(e){return Wt(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!xr(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(ns(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 _h{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 Ln={MESSAGE:"$message",TIMESTAMP:"$timestamp"},LC=new Set([Ln.MESSAGE,Ln.TIMESTAMP]),Ps={enabled:!0,max_bytes:32768};function Ml(e){if(!e)return{...Ps};return{enabled:e.enabled??Ps.enabled,max_bytes:UC(e.max_bytes,Ps.max_bytes)}}function qC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,i)=>{if(LC.has(i))return t.push(i),n;return n[i]=e[i],n},{}),droppedKeys:t}}class bh{constructor(e){this._entries=[],this._totalBytes=0,this._config=Ml(e)}setConfig(e){this._config=Ml(e),this._trimToMaxBytes()}add(e){let t=BC(e);if(!t)return;let r=Ph(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 UC(e,t){if(!An(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function BC(e){let t;try{t=Sr(e)}catch{return}try{let r=JSON.parse(t);if(!Tn(r))return;let n=r,i=n[Ln.MESSAGE],s=n[Ln.TIMESTAMP];if(!gt(i)||i.trim().length===0)return;if(!gt(s)&&!An(s))return;return{step:n,json:t}}catch{return}}function Ph(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let n=0;n<t.length;n++)if(t[n]==="%")r+=1,n+=2;else r+=1;return r}class Ot 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 Jt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var $h=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function vh(e){if(e instanceof Ot){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 GC(e){return typeof e=="object"&&(e instanceof Ot||Ih(e))}function Ih(e){return e instanceof Jt}function VC(e){if(e instanceof Ot)return e.status===502||e.status===504;if(!(e instanceof Jt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Cr(e){return typeof e=="object"&&e instanceof Ot&&e.status===413}function qn(e){if(e instanceof Ot)return e.status===408||e.status===429||e.status>=500;return Ih(e)}function wh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ll="default";class vs{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new fs([new hs,new _s,new gs,new bs],Nl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new vl,this._events=new Al,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",i=!r;if(this._logger=Lm("[PostHog]",this.logMsgIfDebug.bind(this)),i)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=Ym(n||"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:qn},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)||i,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=!bl()||(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(Se.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Se.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Se.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,n)=>this._logger.info(r,n));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($h(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=On(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 n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,r)})}async identifyStatelessImmediate(e,t,r){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,r)}captureStateless(e,t,r,n){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",i,n)})}async captureStatelessImmediate(e,t,r,n){let i=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",i,n)}aliasStateless(e,t,r,n){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",i,n)})}async aliasStatelessImmediate(e,t,r,n){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,n)}groupIdentifyStateless(e,t,r,n,i,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,n)})}async groupIdentifyStatelessImmediate(e,t,r,n,i,s){let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,n)}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((n)=>n.json()).catch((n)=>{this._logger.error("Remote config could not be loaded",n),this._events.emit("error",n)})}async getFlags(e,t={},r={},n={},i={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:n,...i};if(r.$device_id)l.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)l.evaluation_contexts=this.evaluationContexts;let d={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,d,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:VC},this.featureFlagsRequestTimeoutMs).then((c)=>c.json()).then((c)=>({success:!0,response:_l(c)})).catch((c)=>(this._events.emit("error",c),{success:!1,error:this.categorizeRequestError(c)}))}categorizeRequestError(e){if(e instanceof Ot)return{type:"api_error",statusCode:e.status};if(e instanceof Jt){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={},n={},i={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,n,i,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=Cn(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},n={},i={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,n,i,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},n={},i={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,n,i,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},n={},i,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},n={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,n,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},n={},i,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,n,i,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={},n={},i,s){await this._initPromise;let o={geoip_disable:i??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,n,o);if(!a.success)return;let l=a.response;if(l.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(l.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:l?.requestId,quotaLimited:l.quotaLimited};return l}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"}},n=(await this.fetchWithRetry(e,t).then((i)=>{if(i.status!==200||!i.json){let s=`Surveys API could not be loaded: ${i.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return i.json()}).catch((i)=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Se.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Se.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Se.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ll}persistedQueueKeyForRoute(e){return Se.Queue}getActiveQueueRoutes(){return[Ll]}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 n=this.prepareMessage(t,r);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let i=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),s=this.getPersistedProperty(i)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:n}),this.setPersistedProperty(i,s),this._events.emit(e,n),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=ue(()=>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 n=this.prepareMessage(t,r);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(i){this._events.emit("error",i)}}normalizeMessage(e){let{type:t,library:r,library_version:n,...i}=e,s=wh(i.properties)?i.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(n!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:n};if(s)i.properties=s;return i.uuid=ls(i.uuid,xe),i}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:xl(),uuid:ls(t?.uuid,xe)};if(t?.disableGeoip??this.disableGeoip){if(!wh(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 vh(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((i)=>!!i),n=0;while(!0){let i=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(i.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`);await Promise.all(i.map((s)=>s.catch(()=>{}))),n++}}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,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,n])}).then(()=>jl([t])).then(()=>{if(this.pendingFlushPromise===n)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=n,this.flushPromise=n,this.flushPromises.add(n),this.addPendingPromise(n),jl([n]).then(()=>{if(this.flushPromises.delete(n),this.pendingFlushPromise===n)this.pendingFlushPromise=null;if(this.flushPromise===n)this.flushPromise=null}),n}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=Ll){let n={api_key:this.apiKey,batch:e,sent_at:xl()};if(this.historicalMigration)n.historical_migration=!0;let i=Sr(n),s=`${this.host}/batch/`,o=this.disableCompression?null:await zt(i,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||i};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((n)=>this.getRouteQueue(n).length>0))return;let t=[],r;for(let n of e)try{await this._flushRoute(n,t)}catch(i){if(r===void 0)r=i}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(r)||[];if(!n.length)return;let i=n.length,s=0;while(n.length>0&&s<i){let o=n.slice(0,this.maxBatchSize),a=o.map((c)=>c.message===void 0?c.message:this.normalizeMessage(c.message)),l=async()=>{let p=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,p),n=p,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},d={retryCheck:(c)=>{if(Cr(c))return!1;return qn(c)}};try{await this.sendBatch(a,d,e)}catch(c){if(Cr(c)&&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(!(c instanceof Jt))await l();throw this._events.emit("error",c),c}await l(),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)}`,n=this.disableCompression?null:await zt(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(r,i,{retryCheck:(s)=>{if(Cr(s))return!1;return qn(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(s instanceof Jt)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)}`,n=this.disableCompression?null:await zt(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(r,i,{retryCheck:(s)=>{if(Cr(s))return!1;return qn(s)}}),{kind:"ok"}}catch(s){if(Cr(s))return{kind:"too-large"};if(qn(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,n){let i=t.body?t.body:"",s=-1;try{s=i instanceof Blob?i.size:Buffer.byteLength(i,Qm)}catch{if(i instanceof Blob)s=i.size;else s=new TextEncoder().encode(i).length}return await Xm(async()=>{let o=new AbortController,a=n??this.requestTimeout,l=ue(()=>o.abort(),a),d=null;try{d=await this.fetch(e,{signal:o.signal,...t})}catch(p){throw new Jt(p)}finally{clearTimeout(l)}if(t.mode!=="no-cors"&&(d.status<200||d.status>=400))throw new Ot(d,s);return d},{...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(i){if(!GC(i))throw i;await vh(i)}},n;try{return await Promise.race([new Promise((i,s)=>{n=ue(()=>{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(n)}}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 xh=require("fs"),jh=require("readline"),ws=new $e.ReduceableCache(25),Rh=new $e.ReduceableCache(20),ql=7,JC=1000,QC=1e4;async function Ch(e){let t={};for(let i=e.length-1;i>=0;i--){let s=e[i],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||eO(o)||tO(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let n=[];for(let i of r){if(Rh.get(i))continue;let s=t[i];if(!s)continue;s.sort((l,d)=>l-d);let o=nO(s);if(o.every((l)=>rO(i,l)))continue;let a=iO(ws,i,{});n.push(YC(i,o,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)XC(e,ws);return ws.reduce(),e}function YC(e,t,r){return new Promise((n)=>{let i=xh.createReadStream(e),s=jh.createInterface({input:i});function o(){i.destroy(),n()}let a=0,l=0,d=t[l];if(d===void 0)return void o();let c=d[0],p=d[1];function h(){Rh.set(e,1),s.close(),s.removeAllListeners(),o()}i.on("error",h),s.on("error",h),s.on("close",o),s.on("line",(u)=>{if(a++,a<c)return;if(r[a]=sO(u,0),a>=p){if(l===t.length-1){s.close(),s.removeAllListeners();return}l++;let f=t[l];if(f===void 0){s.close(),s.removeAllListeners();return}c=f[0],p=f[1]}})})}function XC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let n=t.get(r.filename);if(n===void 0)continue;ZC(r.lineno,r,n)}}function ZC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Oh(e);i<e;i++){let s=r[i];if(s===void 0)return void Eh(t);t.pre_context.push(s)}if(r[e]===void 0)return void Eh(t);t.context_line=r[e];let n=Fh(e);t.post_context=[];for(let i=e+1;i<=n;i++){let s=r[i];if(s===void 0)break;t.post_context.push(s)}}function Eh(e){delete e.pre_context,delete e.context_line,delete e.post_context}function eO(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function tO(e){if(e.lineno!==void 0&&e.lineno>QC)return!0;if(e.colno!==void 0&&e.colno>JC)return!0;return!1}function rO(e,t){let r=ws.get(e);if(r===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(r[n]===void 0)return!1;return!0}function nO(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let n=Sh(r),i=[];while(!0){if(t===e.length-1){i.push(n);break}let s=e[t+1];if(typeof s!="number")break;if(s<=n[1])n[1]=s+ql;else i.push(n),n=Sh(s);t++}return i}function Sh(e){return[Oh(e),Fh(e)]}function Oh(e){return Math.max(1,e-ql)}function Fh(e){return e+ql}function iO(e,t,r){let n=e.get(t);if(n===void 0)return e.set(t,r),r;return n}function sO(e,t){let r=e,n=r.length;if(n<=150)return r;if(t>n)t=n;let i=Math.max(t-60,0);if(i<5)i=0;let s=Math.min(i+140,n);if(s>n-5)s=n;if(s===n)i=Math.max(s-140,0);if(r=r.slice(i,s),i>0)r=`...${r}`;if(s<n)r+="...";return r}var Or=require("path");function Th(e=process.cwd()){let t=Or.sep==="\\",r=(i)=>t?i.replace(/\\/g,"/"):i,n=r(e);return async(i)=>{for(let s of i)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Or.isAbsolute(s.filename))s.filename=r(Or.relative(n,r(s.filename)))}return i}}var Ah="5.46.1";var yt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Qt{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 n of e){let i=this._flags[n];if(i)t[n]=i;else r.push(n)}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,n]of Object.entries(this._flags)){let i=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${r}`]=i,n.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Qt({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,n={$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)n.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)n.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let i=[];if(this._errorsWhileComputing)i.push(yt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)i.push(yt.QUOTA_LIMITED);if(t===void 0)i.push(yt.FLAG_MISSING);if(i.length>0)n.$feature_flag_error=i.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function kh(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((i)=>i.toString(16).padStart(2,"0")).join("")}var oO=60000,aO=1152921504606847000,lO=["is_not","is_set"];class Fr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Fr.prototype)}}function Lh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class L extends Error{constructor(e){super(e);Lh(this,L)}}class rt extends Error{constructor(e){super(e);Lh(this,rt)}}class Ul{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:n,host:i,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=n,this.projectApiKey=r,this.host=i,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={},n={},i={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:n,evaluationCache:i}}async getFeatureFlag(e,t,r={},n={},i={}){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,n,i);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(l){if(l instanceof rt||l instanceof L)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${e}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${l}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},n={},i=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:l,payload:d}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=l,d)n[a.key]=d}catch(l){if(l instanceof rt||l instanceof L)this.logMsgIfDebug(()=>console.debug(`${l.name} when computing flag locally: ${a.key}: ${l.message}`));else if(l instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${l}`));i=!0}})),{response:r,payloads:n,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:n,skipLoadCheck:i=!1}=r;if(!i)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=n!==void 0?n: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:n,personProperties:i,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new L("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let l=this.groupTypeMapping[String(a)];if(!l)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new L("Flag has unknown group type index");if(!(l in n))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"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let d=s[l];return await this.matchFeatureFlagProperties(e,n[l],d,t)}{let l=this.getBucketingValueForFlag(e,r,i);if(l===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 L(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,i,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=r?.$device_id;if(n==null||n==="")return;return n}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:n}=r,i=e.key;if(!this.featureFlagsByKey)throw new L("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new L(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new L(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new L(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let a of s){if(!(a in n)){let d=this.featureFlagsByKey[a];if(d)if(d.active)try{let c=await this.computeFlagValueLocally(d,r);n[a]=c}catch(c){throw new L(`Error evaluating flag dependency '${a}' for flag '${i}': ${c}`)}else n[a]=!1;else throw new L(`Missing flag dependency '${a}' for flag '${i}'`)}if(n[a]==null)throw new L(`Dependency '${a}' could not be evaluated`)}let o=n[i];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,n){let i=e.filters||{},s=i.groups||[],o=i.aggregation_group_type_index,a=i.early_exit??!1,{groups:l,groupProperties:d}=n,c=!1,p;for(let h of s)try{let u=h.aggregation_group_type_index!==void 0?h.aggregation_group_type_index:o,f=r,m=t;if(u!==o){if(u!=null){let y=this.groupTypeMapping[String(u)];if(!y||!(y in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${u} not available`));continue}if(!(y in d)){c=!0;continue}f=d[y],m=l[y]}}let g=await this.isConditionMatch(e,m,h,f,n);if(g==="match"){let y=h.variant,b=i.multivariate?.variants||[];p=y&&b.some((v)=>v.key===y)?y:await this.getMatchingVariant(e,m)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(u){if(u instanceof rt)throw u;if(u instanceof L)c=!0;else throw u}if(p!==void 0)return p;if(c)throw new L("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,n,i){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let l=a.type,d=!1;if(l==="cohort"){let c=await Uh(a,n,this.cohorts,this.debugMode,(p)=>this.evaluateFlagDependency(p,n,i));d=a.operator==="not_in"?!c:c}else d=l==="flag"?await this.evaluateFlagDependency(a,n,i):qh(a,n,o);if(!d)return"no_match"}if(s==null)return"match"}if(s!=null&&await Dh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await Dh(e.key,t,"variant"),n=this.variantLookupTable(e).find((i)=>r>=i.valueMin&&r<i.valueMax);if(n)return n.key}variantLookupTable(e){let t=[],r=0,n=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{n=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:n,key:o.key}),r=n}),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(oO,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 Fr(`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 Fr(`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 Fr(`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 n={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(i){this.onError?.(Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof Fr)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 n=new AbortController;r=ue(()=>{n.abort()},this.timeout),t.signal=n.signal}try{let n=this.fetch;return n(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,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function Dh(e,t,r=""){let n=await kh(`${e}.${t}${r}`);return parseInt(n.slice(0,15),16)/aO}function qh(e,t,r){let{key:n,value:i}=e,s=e.operator||"exact";if(n in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new L(`Property ${n} not found in propertyValues`)}let o=t[n];if(o==null&&!lO.includes(s)){if(r)r(`Property ${n} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(d,c){if(Array.isArray(d))return d.map((p)=>String(p).toLowerCase()).includes(String(c).toLowerCase());return String(d).toLowerCase()===String(c).toLowerCase()}function l(d,c,p){if(p==="gt")return d>c;if(p==="gte")return d>=c;if(p==="lt")return d<c;if(p==="lte")return d<=c;throw Error(`Invalid operator: ${p}`)}switch(s){case"exact":return a(i,o);case"is_not":return!a(i,o);case"is_set":return n in t;case"icontains":return String(o).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(i).toLowerCase());case"regex":return Nh(String(i))&&String(o).match(String(i))!==null;case"not_regex":return Nh(String(i))&&String(o).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let d=typeof i=="number"?i:parseFloat(String(i)),c;if(c=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(d)&&Number.isFinite(c))return l(c,d,s);return l(String(o),String(i),s)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new L("Date operations cannot be performed on boolean values");let d=fO(String(i));if(d==null)d=Mh(i);if(d==null)throw new L(`Invalid date: ${i}`);let c=Mh(o);if(["is_date_before"].includes(s))return c<d;return c>d}case"semver_eq":return Ae(ae(String(o)),ae(String(i)))===0;case"semver_neq":return Ae(ae(String(o)),ae(String(i)))!==0;case"semver_gt":return Ae(ae(String(o)),ae(String(i)))>0;case"semver_gte":return Ae(ae(String(o)),ae(String(i)))>=0;case"semver_lt":return Ae(ae(String(o)),ae(String(i)))<0;case"semver_lte":return Ae(ae(String(o)),ae(String(i)))<=0;case"semver_tilde":{let d=ae(String(o)),{lower:c,upper:p}=cO(String(i));return Ae(d,c)>=0&&Ae(d,p)<0}case"semver_caret":{let d=ae(String(o)),{lower:c,upper:p}=uO(String(i));return Ae(d,c)>=0&&Ae(d,p)<0}case"semver_wildcard":{let d=ae(String(o)),{lower:c,upper:p}=pO(String(i));return Ae(d,c)>=0&&Ae(d,p)<0}default:throw new L(`Unknown operator: ${s}`)}}function dO(e,t){if(!(e in t))throw new rt(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Uh(e,t,r,n=!1,i){let s=String(e.value);dO(s,r);let o=r[s];return Bh(o,t,r,n,i)}async function Bh(e,t,r,n=!1,i){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 l of o)try{let d=await Bh(l,t,r,n,i);if(s==="AND"){if(!d)return!1}else if(d)return!0}catch(d){if(d instanceof rt)throw d;if(d instanceof L){if(n)console.debug(`Failed to compute property ${l} locally: ${d}`);a=!0}else throw d}if(a)throw new L("Can't match cohort without a given cohort property value");return s==="AND"}for(let l of o)try{let d;if(l.type==="cohort")d=await Uh(l,t,r,n,i);else if(l.type==="flag"){if(!i)throw new L(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);d=await i(l)}else d=qh(l,t);let c=l.negation||!1;if(s==="AND"){if(!d&&!c)return!1;if(d&&c)return!1}else{if(d&&!c)return!0;if(!d&&c)return!0}}catch(d){if(d instanceof rt)throw d;if(d instanceof L){if(n)console.debug(`Failed to compute property ${l} locally: ${d}`);a=!0}else throw d}if(a)throw new L("can't match cohort without a given cohort property value");return s==="AND"}function Nh(e){try{return new RegExp(e),!0}catch(t){return!1}}function Gh(e,t){if(!/^\d+$/.test(e))throw new L(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new L(`Invalid semver: ${t}`);return parseInt(e,10)}function ae(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new L(`Invalid semver: ${e}`);let n=r.split("."),i=(l)=>{if(l===void 0||l==="")return 0;return Gh(l,e)},s=i(n[0]),o=i(n[1]),a=i(n[2]);return[s,o,a]}function Ae(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 cO(e){let t=ae(e),r=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:r,upper:n}}function uO(e){let t=ae(e),[r,n,i]=t,s=[r,n,i],o;return o=r>0?[r+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:s,upper:o}}function pO(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new L(`Invalid wildcard semver: ${e}`);let n=r.split("."),i=(l)=>{try{return Gh(l,e)}catch{throw new L(`Invalid wildcard semver: ${e}`)}},s=i(n[0]),o,a;if(n.length===1)o=[s,0,0],a=[s+1,0,0];else{let l=i(n[1]);o=[s,l,0],a=[s,l+1,0]}return{lower:o,upper:a}}function Mh(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 L(`${e} is in an invalid date format`)}throw new L(`The date provided ${e} must be a string, number, or date object`)}function fO(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),n=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let s=r.groups.interval;if(s=="h")n.setUTCHours(n.getUTCHours()-i);else if(s=="d")n.setUTCDate(n.getUTCDate()-i);else if(s=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(s=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(s!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}function mO(e,t){let r=!1;return Object.assign((n)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(n)},{_posthogErrorHandler:!0})}function Vh(e,t){globalThis.process?.on("uncaughtException",mO(e,t))}function zh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var hO=2000;class nt{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new Pl({...km(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Tn(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,n,i){let s={...i},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:n,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Vh(this.onException.bind(this),this.onFatalError.bind(this)),zh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!nt.isPreviouslyCapturedError(e)){let r=await nt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(i))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(hO),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class Bl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function gO(e){return e==="v0"||e==="v1"}function Kh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return gO(e)?e:"v0"}var Un="analytics",Bn="ai";function Wh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class Tr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:n}){super(Tr.buildMessage(e,t,r,n)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=n}static buildMessage(e,t,r,n){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(n instanceof Error)i+=` (${n.message})`;return i}}function Gl(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 yO(e){return typeof e=="string"?e:void 0}var _O=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Gl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Gl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Gl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:yO}],bO=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function PO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vO(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 Hh(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function wO(e){let r={...PO(e.properties)?e.properties:{}},n={};for(let{property:s,optionKey:o,coerce:a}of _O)if(s in r){let l=a(r[s]);if(l!==void 0)n[o]=l;delete r[s]}let i={};for(let{property:s,field:o}of bO)if(s in r){let a=r[s];if(typeof a=="string")i[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,Hh(r,"$set",e.$set),Hh(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:vO(e.timestamp),...i,options:n,properties:r}}function Jh(e,{createdAt:t,historicalMigration:r}){let n={created_at:t,batch:e.map(wO)};if(r)n.historical_migration=!0;return n}var $O="/i/v1/analytics/events",IO=30000,EO=new Set([408,500,502,503,504]);class Vl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??IO,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((n)=>ue(n,r))),this.generateRequestId=t.generateRequestId??xe,this.compress=t.compress??zt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:n}=Jh(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${$O}`,s=[],o=n,a=Math.max(1,this.config.maxAttempts);for(let l=1;l<=a;l++){let d=l===a,c=Sr({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),p;try{p=await this.sendOnce(i,c,l,t)}catch(g){if(d)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(l));continue}let{status:h}=p;if(h<200||h>=300){if(!d&&EO.has(h)){let y=this.parseRetryAfter(p);await this.cancelBody(p),await this.sleep(this.backoffDelay(l,y));continue}let g=await this.buildHttpError(p,h);return this.surfaceBatchFailure(t,s,o,g)}let u;try{u=await this.parseResponse(p)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${h} response body`))}let f=this.classify(o,u,s);if(f.length===0)return this.surfacePartialDrops(t,s);if(d)return void this.onError(new Tr({requestId:t,drops:s,retryExhausted:f.map((g)=>g.uuid)}));o=f;let m=this.parseRetryAfter(p);await this.sleep(this.backoffDelay(l,m))}}async sendOnce(e,t,r,n){let i=this.buildHeaders(r,n),s=t;if(this.config.compressionEnabled){let l=await this.compress(t,this.config.isDebug);if(l!==null)s=l,i["Content-Encoding"]="gzip"}let o=new AbortController,a=ue(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:i,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,n={"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)n["User-Agent"]=this.config.userAgent;return n}classify(e,t,r){let n=t.results??{},i=[];for(let s of e){let o=n[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")i.push(s)}}return i}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 n=Date.parse(r);if(Number.isNaN(n))return;let i=n-this.now();return i>0?i: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 n=r.results;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw Error("unexpected results shape");return{results:n??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let n=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${n}`)}surfaceBatchFailure(e,t,r,n){this.onError(new Tr({requestId:e,drops:t,retryExhausted:r.map((i)=>i.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Tr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var SO=100,Qh=30000,xO=50000,jO=50,RO=500,CO="https://us.i.posthog.com",Yh=new Set;function $s(e,t){if(Yh.has(e))return;Yh.add(e),console.warn(`[PostHog] ${t}`)}function OO(e){return typeof e=="string"?e.trim():""}function FO(e){return(typeof e=="string"?e.trim():"")||void 0}function TO(e){return(typeof e=="string"?e.trim():"")||CO}function AO(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function kO(e){if(!e)return{};let t={};for(let[n,i]of Object.entries(e))t[`$feature/${n}`]=i;let r=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class zl extends vs{constructor(e,t={}){let r=OO(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:TO(t.host),personalApiKey:FO(t.secretKey??t.personalApiKey)};if(super(r,n),this._memoryStorage=new Bl,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=Kh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,SO):Qh,typeof n.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(n.waitUntilDebounceMs,0);if(typeof n.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(n.waitUntilMaxWaitMs,0);if(!this.disabled&&n.personalApiKey){if(n.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(n.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Ul({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:r,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new nt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||xO}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??RO,n=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??jO;this._waitUntilCycle.timer=ue(()=>{this.resolveWaitUntilFlush()},i)}_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"&&Wh(e)?Bn:Un}persistedQueueKeyForRoute(e){return e===Bn?Se.AiQueue:Se.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Un,Bn]:[Un]}async sendBatch(e,t,r=Un){if(this.captureMode!=="v1"||r===Bn)return super.sendBatch(e,t,r);let n=e.filter((i)=>i!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Vl({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 Ah}get metrics(){if(!this._metrics)this._metrics=new cs(this,ds(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,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:i,event:s,properties:o,options:a})=>{let l={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},d={distinctId:i,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,d,l):this.enqueue(e,d,l)}).catch((i)=>{if(i)console.error(i)}))}_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:n,$set_once:i,$anon_distinct_id:s,...o}=t,d={$set:n||o,$set_once:i||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:d,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:n,$set_once:i,$anon_distinct_id:s,...o}=t,d={$set:n||o,$set_once:i||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:d,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 n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(r).length>0)n.$set_once=r;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let r=AO(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=Qh){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",(i)=>{clearTimeout(r),n(),t(i>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={},n){if(this.disabled)return void this._logger.warn("The client is disabled");let i=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let w=this._flagOverrides[e];if(w===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:w!==!1,variant:typeof w=="string"?w:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:l,groupProperties:d}=r,c=this.addLocalPersonAndGroupProperties(t,s,l,d);l=c.allPersonProperties,d=c.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,l),d);if(a==null)a=this.options.strictLocalEvaluation??!1;let h,u=!1,f,m,g,y,b,v,I;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let w=this.featureFlagsPoller?.featureFlagsByKey[e];if(w)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(w,p,{matchValue:n});if(x){u=!0;let T=x.value;y=w.id,v="Evaluated locally",I=w.has_experiment,h={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof rt||x instanceof L)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!u&&!a){let w=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,l,d,o,[e]);if(w===void 0)g=yt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt;let x=[];if(w.errorsWhileComputingFlags)x.push(yt.ERRORS_WHILE_COMPUTING);if(w.quotaLimited?.includes("feature_flags"))x.push(yt.QUOTA_LIMITED);let T=w.flags[e];if(T===void 0)x.push(yt.FLAG_MISSING);else{y=T.metadata?.id,b=T.metadata?.version,v=T.reason?.description??T.reason?.code,I=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}h={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(i){let w=h===void 0?void 0:h.enabled===!1?!1:h.variant??!0,x={$feature_flag:e,$feature_flag_response:w,$feature_flag_id:y,$feature_flag_version:b,$feature_flag_reason:v,locally_evaluated:u,[`$feature/${e}`]:w,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():m};if(I!==void 0)x.$feature_flag_has_experiment=I;if(u&&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:w,groups:s,disableGeoip:o,properties:x})}if(h!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)h={...h,payload:this._payloadOverrides[e]};return h}async getFeatureFlag(e,t,r){$s("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 n=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return n.variant??!0}async getFeatureFlagPayload(e,t,r,n){if($s("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 i=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},r);if(i===void 0)return;return i.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:n,options:i}=this._resolveDistinctId(t,r);if(!n)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,n,{...i,sendFeatureFlagEvents:i?.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(n){}return r}async isFeatureEnabled(e,t,r){$s("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 n=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return!!(n.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:n}=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,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:n}=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:i,disableGeoip:s,flagKeys:o}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:d}=n||{},c=this.addLocalPersonAndGroupProperties(r,i,l,d);l=c.allPersonProperties,d=c.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,l),d);if(a==null)a=this.options.strictLocalEvaluation??!1;let h=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,o),u={},f={},m=!0;if(h)u=h.response,f=h.payloads,m=h.fallbackToFlags;if(m&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(p.distinctId,p.groups,l,d,s,o);u={...u,...g.flags||{}},f={...f,...g.payloads||{}}}if(this._flagOverrides!==void 0)u={...u,...this._flagOverrides};if(this._payloadOverrides!==void 0)f={...f,...this._payloadOverrides};return{featureFlags:u,featureFlagPayloads:f}}async evaluateFlags(e,t){let{distinctId:r,options:n}=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 Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:i,disableGeoip:s,flagKeys:o}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:d}=n||{},c=this.addLocalPersonAndGroupProperties(r,i,l,d);l=c.allPersonProperties,d=c.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,l),d);if(a==null)a=this.options.strictLocalEvaluation??!1;let h={},u,f,m=!1,g=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,o),b=new Set;if(y)for(let[I,E]of Object.entries(y.response)){let w=this.featureFlagsPoller?.featureFlagsByKey[I];h[I]={key:I,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:y.payloads[I],id:w?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:w?.has_experiment},b.add(I)}if((y?y.fallbackToFlags:!0)&&!a){let I=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,l,d,s,o);if(I){this._minimalFlagCalledEvents=I.minimalFlagCalledEvents===!0,u=I.requestId,f=I.evaluatedAt,m=Boolean(I.errorsWhileComputingFlags),g=Array.isArray(I.quotaLimited)&&I.quotaLimited.includes("feature_flags");for(let[E,w]of Object.entries(I.flags)){if(b.has(E))continue;let x;if(w.metadata?.payload!==void 0)try{x=JSON.parse(w.metadata.payload)}catch{x=w.metadata.payload}h[E]={key:E,enabled:w.enabled,variant:w.variant,payload:x,id:w.metadata?.id,version:w.metadata?.version,reason:w.reason?.description??w.reason?.code,locallyEvaluated:!1,hasExperiment:w.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[I,E]of Object.entries(this._flagOverrides)){if(E===void 0){delete h[I];continue}let w=h[I];h[I]={key:I,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:w?.payload,id:w?.id,version:w?.version,reason:w?.reason,locallyEvaluated:w?.locallyEvaluated??!1,hasExperiment:w?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[I,E]of Object.entries(this._payloadOverrides)){let w=h[I];if(w)h[I]={...w,payload:E}}return new Qt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:i,disableGeoip:s,flags:h,requestId:u,evaluatedAt:f,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,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:n,groups:i,disableGeoip:s,properties:o}=e,a=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([d],[c])=>d<c?-1:d>c?1:0))}`:"",l=`${r}_${n}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(l);else this.distinctIdHasSentFlagCalls[t]=new Set([l]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:i,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:n,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:n,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((n)=>[n,!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((n)=>ue(n,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}`}},n=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;n=ue(()=>{i.abort()},this.options.requestTimeout),r.signal=i.signal}try{return await this.fetch(t,r)}catch(i){this._events.emit("error",i);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},n={};for(let[i,s]of Object.entries(e))if(Am(s)&&t&&i in t){let o={};for(let[a,l]of Object.entries(s))o[String(a)]=String(l);n[String(i)]=o}else r[String(i)]=String(s);return{personProperties:r,groupProperties:n}}async getFeatureFlagsForEvent(e,t,r,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=n?.personProperties||{},s=n?.groupProperties||{},o=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let l={};for(let[d,c]of Object.entries(t||{}))l[d]=String(c);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[d,c]of Object.entries(t||{}))l[d]=String(c);return await this.getAllFlags(e,{groups:l,personProperties:i,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,n){let i={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...n?.[o]||{}};return{allPersonProperties:i,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,n){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,r,n,i){if(!nt.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(nt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:n,flags:i},!1)))}}async captureExceptionImmediate(e,t,r,n){if(!nt.isPreviouslyCapturedError(e)){let i=Error("PostHog syntheticException");return this.addPendingPromise(nt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,r).then((s)=>this.captureImmediate({...s,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:n,properties:i,groups:s,flags:o,sendFeatureFlags:a,timestamp:l,disableGeoip:d,uuid:c}=e,p=this.context?.get(),h=t.includeContextProperties??!0,u=r||p?.distinctId,f=h?{...this.props,...p?.properties||{},...i||{}}:{...i||{}};if(!u)u=xe(),f.$process_person_profile=!1;if(h&&p?.sessionId&&!f.$session_id)f.$session_id=p.sessionId;let m=this._shouldSendMinimalFlagCalledEvent(n,f)?On(f):f,g=this._runBeforeSend({distinctId:u,event:n,properties:m,groups:s,flags:o,sendFeatureFlags:a,timestamp:l,disableGeoip:d,uuid:c});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){$s("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 b=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,d,b);return kO(v)}return{}}).catch(()=>({})).then((b)=>{let v=g.groups||s;return{...b,...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(xm(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],n=e;for(let i of r){if(n=i(n),!n)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!n.properties||Object.keys(n.properties).length===0){let s=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return n}}var Xh=require("async_hooks");class Kl{constructor(){this.storage=new Xh.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 DO(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(i==="*"||i.includes(o.level)))return o;if(!o.tags)o.tags={};let l=o.tags[Zh.POSTHOG_ID_TAG];if(l===void 0)return o;let d=e.options.host??"https://us.i.posthog.com",c=new URL(`/project/${e.apiKey}/person/${l}`,d).toString();o.tags["PostHog Person URL"]=c;let p=o.exception?.values||[],h=p.map((f)=>({...f,stacktrace:f.stacktrace?{...f.stacktrace,type:"raw",frames:(f.stacktrace.frames||[]).map((m)=>({...m,platform:"node:javascript"}))}:void 0})),u={$exception_message:p[0]?.value||o.message,$exception_type:p[0]?.type,$exception_level:o.level,$exception_list:h,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:p[0]?.value||o.message,$sentry_exception_type:p[0]?.type,$sentry_tags:o.tags};if(t&&r)u.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:l,properties:u});return o}}class Zh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,n,i){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(DO(e,{organization:t,projectId:a,prefix:r,severityAllowList:n,sendExceptionsToPostHog:i??!0}))}}}class Wl extends zl{getLibraryId(){return"posthog-node"}initializeContext(){return new Kl}createErrorPropertiesBuilder(){return new $e.ErrorPropertiesBuilder([new $e.EventCoercer,new $e.ErrorCoercer,new $e.ObjectCoercer,new $e.StringCoercer,new $e.PrimitiveCoercer],$e.createStackParser("node:javascript",$e.nodeStackLineParser),[Im(),Ch,Th()])}}var re=require("fs/promises"),fe=require("path");var eg={name:"@toloka-platform/sdk",version:"0.1.0-preview.6",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","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts",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 tg=require("fs/promises"),rg=require("path"),Is=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),Es=(e)=>Is(e,"ENOENT"),Ar=async(e)=>{try{return await tg.lstat(e)}catch(t){if(Es(t))return;throw t}},Gn=async(e,t,r="write")=>{let n=e;for(let i of t.split("/")){n=rg.join(n,i);let s=await Ar(n);if(s===void 0)return;_(!s.isSymbolicLink(),`Refusing to ${r} through symbolic link ${n}.`)}};var og=require("crypto"),Z=require("fs/promises"),pe=require("path"),ag=require("url");var MO=(e)=>{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?void 0:t},Vn=(e)=>{if(e instanceof te){let t=MO(e);return t===void 0?e.message:`${e.message}
56
+ ${t}`}return e instanceof Error?e.message:String(e)};var Hl=ag.fileURLToPath(new URL("../../skills","file:///Users/gzarip/code/potato-5/packages/sdk/src/cli/skill.ts")),Ss="catalog.json",Dr=".agents/skills",kr="SKILL.md",lg="skills",ng=500,ig=1048576,dg=64,LO=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,qO=/^[a-f0-9]{64}$/u,cg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),sg=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),Jl=(e)=>typeof e==="string"&&e.trim().length>0,UO=(e)=>typeof e==="string"&&e.length<=dg&&LO.test(e),BO=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),GO=(e,t)=>{_(cg(e),t("every skill must be an object."));let{id:r,name:n,description:i,tags:s,version:o,digest:a,files:l}=e;return _(UO(r),t(`skill id ${JSON.stringify(r)} must be at most ${dg} lowercase letters, digits, and single hyphens.`)),_(Jl(n),t(`skill ${r} needs a name.`)),_(Jl(i),t(`skill ${r} needs a description.`)),_(sg(s),t(`skill ${r} tags must be strings.`)),_(Jl(o),t(`skill ${r} needs a version.`)),_(typeof a==="string"&&qO.test(a),t(`skill ${r} digest must be the sha256 hex digest of its files.`)),_(sg(l)&&l.includes(kr),t(`skill ${r} files must include ${kr}.`)),_(l.every(BO),t(`skill ${r} files must be relative paths inside its directory.`)),_(new Set(l).size===l.length,t(`skill ${r} lists a file more than once.`)),{id:r,name:n,description:i,tags:s,version:o,digest:a,files:l}},VO=(e,t)=>{try{return JSON.parse(e)}catch(r){throw Error(`Invalid skill catalog ${t}: ${Vn(r)}`)}},ug=async(e)=>{try{return(await Z.stat(e)).isFile()}catch(t){if(Is(t,"ENOENT","ENOTDIR"))return!1;throw t}},pg=async(e)=>{let t=pe.join(e,lg);if(await ug(pe.join(t,Ss)))return t;let r=pe.dirname(e);return r===e?void 0:pg(r)};async function zO(e=process.argv[1]){let t=e===void 0?void 0:await Z.realpath(e),r=t===void 0?void 0:await pg(pe.dirname(t));if(r!==void 0)return r;let n=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return _(await ug(pe.join(Hl,Ss)),`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${lg}/${Ss} in a directory above its runtime entry, but ${n}, and the source checkout catalog ${Hl} is absent. Reinstall @toloka-platform/sdk.`),Hl}var Ql=async()=>KO(await zO());async function KO(e){let t=pe.join(e,Ss),r=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:n}=await Z.stat(t);_(n<=ig,r(`the manifest is ${n} bytes; the limit is ${ig} bytes.`));let i=VO(await Z.readFile(t,"utf8"),t);_(cg(i)&&Array.isArray(i.skills),r("expected an object with a skills array.")),_(i.skills.length<=ng,r(`${i.skills.length} skills exceed the limit of ${ng}.`));let s=i.skills.map((a)=>GO(a,r)),o=new Set;for(let a of s)_(!o.has(a.id),r(`skill id ${a.id} appears more than once.`)),o.add(a.id);return{root:e,manifestPath:t,skills:s}}async function fg(e,t){let r=og.createHash("sha256");for(let n of t.toSorted())r.update(n),r.update("\x00"),r.update(await Z.readFile(pe.join(e,n))),r.update("\x00");return r.digest("hex")}var WO=(e,t)=>{let r=t.trim().toLowerCase();return e.filter((n)=>[n.id,n.name,n.description,...n.tags].some((i)=>i.toLowerCase().includes(r)))};async function HO(e,t){let r=pe.join(e,Dr,t.id);if(await Ar(r)===void 0)return"not-installed";try{return await fg(r,t.files)===t.digest?"current":"stale"}catch(n){if(Is(n,"ENOENT","ENOTDIR"))return"stale";throw n}}var mg=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(r)=>({...r,status:await HO(e,r)}))),JO=async(e,t,r,n)=>{await e(r,n);try{await e(t,r)}catch(i){try{await e(n,r)}catch(s){throw Error(`Failed to replace ${r}; the previous version is preserved at ${n}. ${Vn(s)}`,{cause:i})}throw i}await Z.rm(n,{recursive:!0,force:!0})};async function QO({catalog:e,sourceRoot:t,skillId:r,force:n=!1,rename:i=Z.rename}){let s=e.skills.find((p)=>p.id===r);_(s,`Skill ${JSON.stringify(r)} is not in the catalog. Run \`toloka skill list\` to see the available skills.`);let o=`${Dr}/${s.id}`;await Gn(t,o);let a=pe.join(t,o),l=await Ar(a);_(l===void 0||n,`${o} already exists. Re-run with --force to replace it with the catalog version of ${s.id}.`);let d=pe.dirname(a);await Z.mkdir(d,{recursive:!0});let c=await Z.mkdtemp(pe.join(d,`.${s.id}.tmp-`));try{for(let p of s.files){let h=pe.join(c,p);await Z.mkdir(pe.dirname(h),{recursive:!0}),await Z.copyFile(pe.join(e.root,s.id,p),h)}if(_(await fg(c,s.files)===s.digest,`Skill ${s.id} failed its digest check: the packaged files do not match the catalog digest ${s.digest}. Nothing was installed.`),l===void 0)await i(c,a);else await JO(i,c,a,`${c}.backup`)}catch(p){throw await Z.rm(c,{recursive:!0,force:!0}),p}return{skill:s,directory:a,replaced:l!==void 0}}var hg=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let r=Math.max(...e.map((i)=>i.id.length)),n=Math.max(...e.map((i)=>i.status.length));return e.flatMap((i)=>[`${i.id.padEnd(r)} ${i.status.padEnd(n)} ${i.name}`,` ${i.description}`]).join(`
57
+ `)};async function gg({sourceRoot:e,json:t,io:r}){let n=await Ql();r.stdout(hg(await mg({sourceRoot:e,skills:n.skills}),t))}async function yg({sourceRoot:e,query:t,json:r,io:n}){let i=await Ql(),s=await mg({sourceRoot:e,skills:WO(i.skills,t)});if(r||s.length>0){n.stdout(hg(s,r));return}n.stdout(`No skills match ${JSON.stringify(t)}. Run \`toloka skill list\` to see the catalog.`)}async function _g({sourceRoot:e,skillId:t,force:r,io:n}){let i=await Ql(),s=await QO({catalog:i,sourceRoot:e,skillId:t,force:r}),o=`${Dr}/${s.skill.id}`,a=s.skill.files.length;n.stdout(`${s.replaced?"Replaced":"Installed"} ${s.skill.id} in ${o} (${a} ${a===1?"file":"files"}). Start with ${o}/${kr}.`)}var Ve=eg.version,ze="@toloka-platform/sdk",ed="toloka-bootstrap",Pg=`.claude/skills/${ed}/SKILL.md`,vg=`.cursor/rules/${ed}.mdc`,Yt="AGENTS.md",YO=[Pg,vg,Yt],Nr={begin:"<toloka>",end:"</toloka>"},Yl={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},Xl=/<!-- toloka:sdk-version ([^\s>]+) -->/u,wg=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),Mr=async(e)=>{try{return await re.readFile(e,"utf8")}catch(t){if(Es(t))return;throw t}},Zl=async(e)=>{try{return(await re.lstat(e)).isDirectory()}catch(t){if(Es(t))return!1;throw t}},td=(e)=>Xl.test(e),$g=`Generated by \`${ze}\` version \`${Ve}\`.
58
+ <!-- toloka:sdk-version ${Ve} -->`,XO=`${Nr.begin}
59
59
 
60
60
  ## Toloka Agent Bootstrap
61
61
 
62
- ${lg}
62
+ ${$g}
63
63
  Re-run \`toloka init\` to refresh this block. Keep your own instructions outside it.
64
64
 
65
65
  This repository works with the Toloka platform through the \`toloka\` CLI. Before starting a Toloka task:
66
66
 
67
67
  1. Run \`toloka --help\`, then \`toloka <resource> --help\` for the resource you need.
68
68
  2. Run \`toloka skill search <query>\` to find a bundled skill for the task; \`toloka skill list\` shows every skill and whether it is installed.
69
- 3. Run \`toloka skill install <skill-id>\` and read \`${Ar}/<skill-id>/${kr}\` before acting; add \`--force\` to refresh a stale skill.
69
+ 3. Run \`toloka skill install <skill-id>\` and read \`${Dr}/<skill-id>/${kr}\` before acting; add \`--force\` to refresh a stale skill.
70
70
  4. Follow the installed skill. When no skill matches, continue with the CLI help and never invent commands or SDK helpers.
71
71
  5. To report a Toloka platform problem or unexpected failure to support, run \`toloka skill search report-issue\` and install \`toloka-report-issue\` before collecting evidence.
72
72
 
73
- ${Dr.end}`,cg=`# Toloka Agent Bootstrap pointer
73
+ ${Nr.end}`,Ig=`# Toloka Agent Bootstrap pointer
74
74
 
75
- ${lg}
75
+ ${$g}
76
76
 
77
- Read the \`${Dr.begin}\` block in \`${Yt}\` at the source root and follow it before doing Toloka work. It tells you to run \`toloka --help\`, search the bundled Skill Catalog with \`toloka skill search <query>\`, install the match with \`toloka skill install <skill-id>\`, and read \`${Ar}/<skill-id>/${kr}\` before acting.
78
- `,Pj=`---
79
- name: ${Hl}
80
- description: Toloka platform work with the toloka CLI and ${Ke}, such as pipeline projects, datasets, runs, secrets, and issue reporting. Use when the user mentions Toloka or the toloka CLI. Start by reading the ${Dr.begin} Agent Bootstrap block in ${Yt}, then find and install the matching skill.
77
+ Read the \`${Nr.begin}\` block in \`${Yt}\` at the source root and follow it before doing Toloka work. It tells you to run \`toloka --help\`, search the bundled Skill Catalog with \`toloka skill search <query>\`, install the match with \`toloka skill install <skill-id>\`, and read \`${Dr}/<skill-id>/${kr}\` before acting.
78
+ `,ZO=`---
79
+ name: ${ed}
80
+ description: Toloka platform work with the toloka CLI and ${ze}, such as pipeline projects, datasets, runs, secrets, and issue reporting. Use when the user mentions Toloka or the toloka CLI. Start by reading the ${Nr.begin} Agent Bootstrap block in ${Yt}, then find and install the matching skill.
81
81
  ---
82
82
 
83
- ${cg}`,vj=`---
84
- description: Toloka Agent Bootstrap pointer for the toloka CLI and ${Ke}
83
+ ${Ig}`,eF=`---
84
+ description: Toloka Agent Bootstrap pointer for the toloka CLI and ${ze}
85
85
  alwaysApply: true
86
86
  ---
87
87
 
88
- ${cg}`,ng=(e,t,r)=>{let i=e.indexOf(t.begin),n=e.indexOf(t.end);if(i===-1&&n===-1)return;return y(i!==-1&&n!==-1&&i<n,`Malformed Toloka block in ${r}: expected one ${t.begin} followed by one ${t.end}. Repair the file by hand, then re-run \`toloka init\`.`),y(!e.includes(t.begin,i+t.begin.length)&&!e.includes(t.end,n+t.end.length),`Multiple Toloka blocks in ${r}: keep exactly one ${t.begin} ... ${t.end} block, then re-run \`toloka init\`.`),{beginIndex:i,endIndex:n+t.end.length}},wj=(e,t)=>{let r=ng(e,Dr,t),i=ng(e,Kl,t);y(r===void 0||i===void 0,`Ambiguous Toloka blocks in ${t}: both ${Dr.begin} and ${Kl.begin} are present. Keep one, then re-run \`toloka init\`.`);let n=e.includes(`\r
88
+ ${Ig}`,bg=(e,t,r)=>{let n=e.indexOf(t.begin),i=e.indexOf(t.end);if(n===-1&&i===-1)return;return _(n!==-1&&i!==-1&&n<i,`Malformed Toloka block in ${r}: expected one ${t.begin} followed by one ${t.end}. Repair the file by hand, then re-run \`toloka init\`.`),_(!e.includes(t.begin,n+t.begin.length)&&!e.includes(t.end,i+t.end.length),`Multiple Toloka blocks in ${r}: keep exactly one ${t.begin} ... ${t.end} block, then re-run \`toloka init\`.`),{beginIndex:n,endIndex:i+t.end.length}},tF=(e,t)=>{let r=bg(e,Nr,t),n=bg(e,Yl,t);_(r===void 0||n===void 0,`Ambiguous Toloka blocks in ${t}: both ${Nr.begin} and ${Yl.begin} are present. Keep one, then re-run \`toloka init\`.`);let i=e.includes(`\r
89
89
  `)?`\r
90
90
  `:`
91
- `,s=bj.replaceAll(`
92
- `,n),o=r??i;if(o!==void 0)return`${e.slice(0,o.beginIndex)}${s}${e.slice(o.endIndex)}`;if(e.length===0)return`${s}${n}`;let a=e.endsWith(`${n}${n}`)?"":e.endsWith(n)?n:`${n}${n}`;return`${e}${a}${s}${n}`},$j=async(e)=>{if(await Wl(fe.join(e,"node_modules",Ke)))return!0;let t=await Nr(fe.join(e,"package.json"));if(t===void 0)return!1;let r=JSON.parse(t);return y(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,Ke)==="string"})},Ej=async(e,t)=>{if(await Nr(e)===t)return!1;return await ee.mkdir(fe.dirname(e),{recursive:!0}),await ee.writeFile(e,t,"utf8"),!0},Ij=async(e,t)=>{let r=fe.join(e,t),i=await Nr(r);y(i===void 0||Jl(i),`Refusing to overwrite ${r}: it carries no \`<!-- toloka:sdk-version ... -->\` marker, so it is not a pointer generated by ${Ke}. Move it aside, then re-run \`toloka init\`.`)},Sj=async(e)=>(await Promise.all(ag.map(async(r)=>{let i=fe.join(e,r.file);if(await Tr(i)===void 0)return;return await Bi(e,r.file,"remove legacy agent entry point"),Jl(await ee.readFile(i,"utf8"))?r:void 0}))).filter((r)=>r!==void 0),xj=async(e,t)=>{if(await ee.rm(fe.join(e,t.file),{force:!0}),t.directory===void 0)return;let r=fe.join(e,t.directory);if((await ee.readdir(r)).length===0)await ee.rmdir(r)},Rj=(e,t,r,i)=>[`${r.length===0&&i.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${Ke} ${Ve} in ${e}:`,...t.map((n)=>` ${n}`),...i.map((n)=>` removed ${n} (replaced by the ${Yt} Agent Bootstrap)`)].join(`
93
- `),Cj=async(e,t)=>{if(t===void 0)return;let r=await Ie(e);if(y(r===void 0||r.projectId===t,`This directory is already bound to ${r?.projectId}.`),r!==void 0)return;return await Gt(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function dg(e,t={}){await ee.mkdir(e,{recursive:!0});let r=await ee.realpath(e),i=fe.join(r,Yt),n=await Nr(i),s=wj(n??"",i),[o,a]=await Promise.all([Wl(fe.join(r,".claude")),Wl(fe.join(r,".cursor","rules"))]),u=[...o||!o&&!a&&n===void 0?[{relativePath:sg,source:Pj}]:[],...a?[{relativePath:og,source:vj}]:[]],l=[...u,{relativePath:Yt,source:s}];await Promise.all(l.map((b)=>Bi(r,b.relativePath))),await Promise.all(u.map((b)=>Ij(r,b.relativePath)));let c=await Sj(r),p=await Cj(r,t.projectId),f=p===void 0?[]:[p];for(let b of l)if(await Ej(fe.join(r,b.relativePath),b.source))f.push(b.relativePath);for(let b of c)await xj(r,b);let m=c.map((b)=>b.file),h=await $j(r),g=[...l.map((b)=>b.relativePath),...p===void 0?[]:[p]],_=h?void 0:`Warning: ${Ke} is not listed in dependencies or devDependencies in ${fe.join(r,"package.json")}. Run \`bun add --dev ${Ke}\` before using \`toloka\`, then re-run \`toloka init\`.`;return{targetDirectory:r,files:g,writtenFiles:f,removedFiles:m,sdkVersion:Ve,dependencyReady:h,output:Rj(r,g,f,m),..._===void 0?{}:{warning:_}}}async function ug(e){let t=[],r=new Set,i=(s,o)=>{t.push(s);let a=zl.exec(o)?.[1];if(a!==void 0)r.add(a)};for(let{file:s}of ag){let o=await Nr(fe.join(e,s));if(o!==void 0&&Jl(o))i(s,o)}for(let s of _j){let o=await Nr(fe.join(e,s));if(o===void 0)continue;let a=zl.exec(o)?.[1];if(o.includes(Kl.begin)||a!==void 0&&a!==Ve)i(s,o)}if(t.length===0)return;return`Warning: Agent instructions generated by ${r.size===0?`an earlier ${Ke} build`:`${Ke} ${[...r].toSorted().join(", ")}`} are out of date (${t.join(", ")}). The installed ${Ve} manages one Agent Bootstrap in ${Yt} plus pointer files. Re-run \`toloka init\`.`}var Oj="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",jj="https://eu.posthog.com",Fj={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0},Is=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},Tj=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};function kj(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(Tj(t))return!1;if(Is(t))return!0;if(Is(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(Is(e.CI??process.env.CI))return!1;if(Is(process.env.VITEST))return!1;return!0}var Aj={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},skill:{list:!0,search:!0,install:!0}},Dj={apply:!0,"auth-status":!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},Ql=(e)=>{let t=e[0];if(t===void 0)return"help";let r=Aj[t];if(r===void 0)return Dj[t]===!0?t:"unknown";let i=e[1];return i!==void 0&&r[i]===!0?`${t} ${i}`:t};function fg(e){if(e.includes("-v")||e.includes("--version"))return"version";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(Fj[i]===!0)r+=1;continue}t.push(i)}return Ql(t)}function Nj(e){if(e===void 0)return{error_code:"command_failed"};if(e instanceof re||e instanceof or)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var Lj=(e)=>Ss.join(Ss.dirname(Ge(e)),"anonymous-id"),qj=async(e)=>{let t=Lj(e);await ll(t);try{let i=(await Xt.readFile(t,"utf8")).trim();if(i.length>0)return await Xt.chmod(t,384),i}catch(i){if(!(i instanceof Error&&("code"in i)&&i.code==="ENOENT"))throw i}let r=pg.randomUUID();return await Xt.writeFile(t,`${r}
94
- `,{mode:384}),await Xt.chmod(t,384),r},Mj=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){y(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.")},async shutdown(){}});function mg(e){let{environment:t}=e;if(e.client===void 0&&!kj(t))return Mj();let{client:r,distinctId:i}=e,n,s=[],o=(l)=>{s.push(l)};r?.on?.("error",o);let a=async()=>{if(r!==void 0&&i!==void 0)return;if(r===void 0){let l=new Ul(Oj,{host:jj,flushAt:1,flushInterval:0});l.on("error",o),r=l}i??=await qj(t)},d=()=>({sdk_version:Ve,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),u=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(l){u=u.then(()=>{if(r===void 0||i===void 0)return;if(n===l.id)return;if(n=l.id,i!==l.id)r.alias({distinctId:l.id,alias:i});i=l.id}).catch(()=>{})},captureCommand(l){u=u.then(()=>{if(r===void 0||i===void 0)return;let c=d();if(l.outcome==="failed"){let p=Nj(l.error);r.capture({distinctId:i,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...c,command:Ql(l.command.split(" ")),duration_ms:l.durationMs,exit_code:l.exitCode,...p}});return}r.capture({distinctId:i,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...c,command:Ql(l.command.split(" ")),duration_ms:l.durationMs,exit_code:l.exitCode,outcome:l.outcome}})}).catch(()=>{})},submitIssueReport(l){let c=u.then(async()=>{y(r&&i,"PostHog issue reporting could not be initialized."),s.length=0,r.capture({distinctId:i,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...d(),report_id:l.reportId,report_text:l.reportText,report_length_bytes:new TextEncoder().encode(l.reportText).length,authored_by:l.authoredBy,platform:l.platform,$process_person_profile:!1}}),await r.flush();let p=s[0];if(s.length=0,p!==void 0)throw p});return u=c.catch(()=>{}),c},async shutdown(){try{await u,await r?.shutdown(2000)}catch{}}}}var Br=require("fs/promises"),Ur=require("path");var _g=Symbol("sourceReference"),bg={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},Uj={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 Ft(e,t){return e<t?-1:e>t?1:0}function hg(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 Pg(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function vg(e,t){let[r,...i]=Pg(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(Uj,o)?`${o}Value`:o}function Bj(e,t){return Pg(e).map((r)=>r.toLowerCase()).join("-")||t}function Yl(e,t,r){let i=new Map,n=new Set;for(let d of e){y(!n.has(d.key),`Naming key "${d.key}" is duplicated`),n.add(d.key);let u=t(d),l=i.get(u)??[];l.push(d),i.set(u,l)}let s=new Set(i.keys()),o=new Set,a=new Map;for(let[d,u]of[...i.entries()].toSorted(([l],[c])=>Ft(l,c))){let l=u.toSorted((c,p)=>Ft(c.key,p.key));for(let c of l){let p=d;if(l.length>1||r!==void 0&&Object.hasOwn(r,p))p=`${d}_${hg(c.key)}`;let f=2;while(o.has(p)||r!==void 0&&Object.hasOwn(r,p)||p!==d&&s.has(p))p=`${d}_${hg(c.key)}_${f}`,f+=1;o.add(p),a.set(c.key,p)}}return a}function Gj(e){return typeof e==="object"&&e!==null&&_g in e}function te(e){return" ".repeat(e)}function Ae(e,t=0){if(Gj(e))return e.name;if(y(e!==void 0,"Cannot emit an undefined source value"),typeof e==="number")y(Number.isFinite(e),"Cannot emit a non-finite number");if(e===null||typeof e!=="object"){let n=JSON.stringify(e);return y(n!==void 0,`Cannot emit a ${typeof e} source value`),n}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
95
- ${e.map((s)=>`${te(t+1)}${Ae(s,t+1)}`).join(`,
91
+ `,s=XO.replaceAll(`
92
+ `,i),o=r??n;if(o!==void 0)return`${e.slice(0,o.beginIndex)}${s}${e.slice(o.endIndex)}`;if(e.length===0)return`${s}${i}`;let a=e.endsWith(`${i}${i}`)?"":e.endsWith(i)?i:`${i}${i}`;return`${e}${a}${s}${i}`},rF=async(e)=>{if(await Zl(fe.join(e,"node_modules",ze)))return!0;let t=await Mr(fe.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((n)=>{let i=Reflect.get(r,n);return typeof i==="object"&&i!==null&&typeof Reflect.get(i,ze)==="string"})},nF=async(e,t)=>{if(await Mr(e)===t)return!1;return await re.mkdir(fe.dirname(e),{recursive:!0}),await re.writeFile(e,t,"utf8"),!0},iF=async(e,t)=>{let r=fe.join(e,t),n=await Mr(r);_(n===void 0||td(n),`Refusing to overwrite ${r}: it carries no \`<!-- toloka:sdk-version ... -->\` marker, so it is not a pointer generated by ${ze}. Move it aside, then re-run \`toloka init\`.`)},sF=async(e)=>(await Promise.all(wg.map(async(r)=>{let n=fe.join(e,r.file);if(await Ar(n)===void 0)return;return await Gn(e,r.file,"remove legacy agent entry point"),td(await re.readFile(n,"utf8"))?r:void 0}))).filter((r)=>r!==void 0),oF=async(e,t)=>{if(await re.rm(fe.join(e,t.file),{force:!0}),t.directory===void 0)return;let r=fe.join(e,t.directory);if((await re.readdir(r)).length===0)await re.rmdir(r)},aF=(e,t,r,n)=>[`${r.length===0&&n.length===0?"Agent entry points are up to date":"Initialized agent entry points"} for ${ze} ${Ve} in ${e}:`,...t.map((i)=>` ${i}`),...n.map((i)=>` removed ${i} (replaced by the ${Yt} Agent Bootstrap)`)].join(`
93
+ `),lF=async(e,t)=>{if(t===void 0)return;let r=await Ee(e);if(_(r===void 0||r.projectId===t,`This directory is already bound to ${r?.projectId}.`),r!==void 0)return;return await Gt(e,{projectId:t,pipelines:{},datasets:{}}),"toloka.json"};async function Eg(e,t={}){await re.mkdir(e,{recursive:!0});let r=await re.realpath(e),n=fe.join(r,Yt),i=await Mr(n),s=tF(i??"",n),[o,a]=await Promise.all([Zl(fe.join(r,".claude")),Zl(fe.join(r,".cursor","rules"))]),d=[...o||!o&&!a&&i===void 0?[{relativePath:Pg,source:ZO}]:[],...a?[{relativePath:vg,source:eF}]:[]],c=[...d,{relativePath:Yt,source:s}];await Promise.all(c.map((b)=>Gn(r,b.relativePath))),await Promise.all(d.map((b)=>iF(r,b.relativePath)));let p=await sF(r),h=await lF(r,t.projectId),u=h===void 0?[]:[h];for(let b of c)if(await nF(fe.join(r,b.relativePath),b.source))u.push(b.relativePath);for(let b of p)await oF(r,b);let f=p.map((b)=>b.file),m=await rF(r),g=[...c.map((b)=>b.relativePath),...h===void 0?[]:[h]],y=m?void 0:`Warning: ${ze} is not listed in dependencies or devDependencies in ${fe.join(r,"package.json")}. Run \`bun add --dev ${ze}\` before using \`toloka\`, then re-run \`toloka init\`.`;return{targetDirectory:r,files:g,writtenFiles:u,removedFiles:f,sdkVersion:Ve,dependencyReady:m,output:aF(r,g,u,f),...y===void 0?{}:{warning:y}}}async function Sg(e){let t=[],r=new Set,n=(s,o)=>{t.push(s);let a=Xl.exec(o)?.[1];if(a!==void 0)r.add(a)};for(let{file:s}of wg){let o=await Mr(fe.join(e,s));if(o!==void 0&&td(o))n(s,o)}for(let s of YO){let o=await Mr(fe.join(e,s));if(o===void 0)continue;let a=Xl.exec(o)?.[1];if(o.includes(Yl.begin)||a!==void 0&&a!==Ve)n(s,o)}if(t.length===0)return;return`Warning: Agent instructions generated by ${r.size===0?`an earlier ${ze} build`:`${ze} ${[...r].toSorted().join(", ")}`} are out of date (${t.join(", ")}). The installed ${Ve} manages one Agent Bootstrap in ${Yt} plus pointer files. Re-run \`toloka init\`.`}var dF="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",cF="https://eu.posthog.com",uF={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0},xs=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},pF=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};function fF(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(pF(t))return!1;if(xs(t))return!0;if(xs(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if(xs(e.CI??process.env.CI))return!1;if(xs(process.env.VITEST))return!1;return!0}var mF={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},skill:{list:!0,search:!0,install:!0}},hF={apply:!0,"auth-status":!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},rd=(e)=>{let t=e[0];if(t===void 0)return"help";let r=mF[t];if(r===void 0)return hF[t]===!0?t:"unknown";let n=e[1];return n!==void 0&&r[n]===!0?`${t} ${n}`:t};function jg(e){if(e.includes("-v")||e.includes("--version"))return"version";let t=[];for(let r=0;r<e.length;r+=1){let n=e[r];if(n===void 0)continue;if(n==="--help"||n==="-h")break;if(n.startsWith("-")){if(uF[n]===!0)r+=1;continue}t.push(n)}return rd(t)}function gF(e){if(e===void 0)return{error_code:"command_failed"};if(e instanceof te||e instanceof ar)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var yF=(e)=>js.join(js.dirname(Ge(e)),"anonymous-id"),_F=async(e)=>{let t=yF(e);await ml(t);try{let n=(await Xt.readFile(t,"utf8")).trim();if(n.length>0)return await Xt.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let r=xg.randomUUID();return await Xt.writeFile(t,`${r}
94
+ `,{mode:384}),await Xt.chmod(t,384),r},bF=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){_(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.")},async shutdown(){}});function Rg(e){let{environment:t}=e;if(e.client===void 0&&!fF(t))return bF();let{client:r,distinctId:n}=e,i,s=[],o=(c)=>{s.push(c)};r?.on?.("error",o);let a=async()=>{if(r!==void 0&&n!==void 0)return;if(r===void 0){let c=new Wl(dF,{host:cF,flushAt:1,flushInterval:0});c.on("error",o),r=c}n??=await _F(t)},l=()=>({sdk_version:Ve,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),d=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(c){d=d.then(()=>{if(r===void 0||n===void 0)return;if(i===c.id)return;if(i=c.id,n!==c.id)r.alias({distinctId:c.id,alias:n});n=c.id}).catch(()=>{})},captureCommand(c){d=d.then(()=>{if(r===void 0||n===void 0)return;let p=l();if(c.outcome==="failed"){let h=gF(c.error);r.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...p,command:rd(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,...h}});return}r.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...p,command:rd(c.command.split(" ")),duration_ms:c.durationMs,exit_code:c.exitCode,outcome:c.outcome}})}).catch(()=>{})},submitIssueReport(c){let p=d.then(async()=>{_(r&&n,"PostHog issue reporting could not be initialized."),s.length=0,r.capture({distinctId:n,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...l(),report_id:c.reportId,report_text:c.reportText,report_length_bytes:new TextEncoder().encode(c.reportText).length,authored_by:c.authoredBy,platform:c.platform,$process_person_profile:!1}}),await r.flush();let h=s[0];if(s.length=0,h!==void 0)throw h});return d=p.catch(()=>{}),p},async shutdown(){try{await d,await r?.shutdown(2000)}catch{}}}}var Br=require("fs/promises"),Yn=require("path");var Tg=Symbol("sourceReference"),Ag={code:!0,connect:!0,definePipeline:!0,field:!0,generation:!0,match:!0,pipeline:!0,quorum:!0,root:!0},PF={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 Ft(e,t){return e<t?-1:e>t?1:0}function Cg(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 kg(e){return e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").split(/[^A-Za-z0-9]+/).filter(Boolean)}function Dg(e,t){let[r,...n]=kg(e),s=`${(r??t).toLowerCase()}${n.map((a)=>`${a.slice(0,1).toUpperCase()}${a.slice(1).toLowerCase()}`).join("")}`,o=/^\d/.test(s)?`_${s}`:s;return Object.hasOwn(PF,o)?`${o}Value`:o}function vF(e,t){return kg(e).map((r)=>r.toLowerCase()).join("-")||t}function nd(e,t,r){let n=new Map,i=new Set;for(let l of e){_(!i.has(l.key),`Naming key "${l.key}" is duplicated`),i.add(l.key);let d=t(l),c=n.get(d)??[];c.push(l),n.set(d,c)}let s=new Set(n.keys()),o=new Set,a=new Map;for(let[l,d]of[...n.entries()].toSorted(([c],[p])=>Ft(c,p))){let c=d.toSorted((p,h)=>Ft(p.key,h.key));for(let p of c){let h=l;if(c.length>1||r!==void 0&&Object.hasOwn(r,h))h=`${l}_${Cg(p.key)}`;let u=2;while(o.has(h)||r!==void 0&&Object.hasOwn(r,h)||h!==l&&s.has(h))h=`${l}_${Cg(p.key)}_${u}`,u+=1;o.add(h),a.set(p.key,h)}}return a}function wF(e){return typeof e==="object"&&e!==null&&Tg in e}function ne(e){return" ".repeat(e)}function ke(e,t=0){if(wF(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 i=JSON.stringify(e);return _(i!==void 0,`Cannot emit a ${typeof e} source value`),i}if(Array.isArray(e)){if(e.length===0)return"[]";return`[
95
+ ${e.map((s)=>`${ne(t+1)}${ke(s,t+1)}`).join(`,
96
96
  `)}
97
- ${te(t)}]`}let r=Object.entries(e).filter(([,n])=>n!==void 0).toSorted(([n],[s])=>Ft(n,s));if(r.length===0)return"{}";return`{
98
- ${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`${te(t+1)}${o}: ${Ae(s,t+1)}`}).join(`,
97
+ ${ne(t)}]`}let r=Object.entries(e).filter(([,i])=>i!==void 0).toSorted(([i],[s])=>Ft(i,s));if(r.length===0)return"{}";return`{
98
+ ${r.map(([i,s])=>{let o=i==="__proto__"?`[${JSON.stringify(i)}]`:/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(i)?i:JSON.stringify(i);return`${ne(t+1)}${o}: ${ke(s,t+1)}`}).join(`,
99
99
  `)}
100
- ${te(t)}}`}function Vi(e,t){return{field:t(e.id),optional:e.optional}}function xs(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 Xl(e,t){let{targetEntity:r,...i}=e;return{...i,targetEntity:t(r)}}function gg(e,t){return{...e,gradedEntities:e.gradedEntities.map((r)=>Xl(r,t))}}function Vj(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)=>Vi(a,t)),completed:s.input.map((a)=>Vi(a,t))}}case"code":{let{fieldProxies:r,...i}=e.settings;return{...i,fieldProxies:{input:r.input.map((n)=>Vi(n,t)),output:r.output.map((n)=>Vi(n,t))}}}case"generation":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>xs(o,t)),output:r.output.map((o)=>xs(o,t))},qualityCriteria:i.map((o)=>Xl(o,t)),...n===void 0?{}:{exam:gg(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,...d})=>({...d,field:t(a)}))})),fieldProxies:{input:i.input.map((s)=>Vi(s,t))}}}case"quorum":{let{entities:r,qualityCriteria:i,exam:n,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>xs(o,t)),output:r.output.map((o)=>xs(o,t))},qualityCriteria:i.map((o)=>Xl(o,t)),...n===void 0?{}:{exam:gg(n,t)}}}}}function Kj(e,t,r,i){let n=new Set,o=Vj(e,(l)=>{let c=i.get(l);return y(c,`Node "${e.id}" references unknown field "${l}"`),n.add(c),{name:c,[_g]:!0}}),a=[...n].toSorted(Ft),d=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],u=e.type==="root"?[`${te(1)}${Ae(o,1)}`,`${te(1)}${Ae({id:e.id},1)}`]:[`${te(1)}${Ae(e.settings.about.name,1)}`,`${te(1)}${Ae(o,1)}`,`${te(1)}${Ae({id:e.id},1)}`];return{binding:t,path:r,source:`${d.join(`
100
+ ${ne(t)}}`}function zn(e,t){return{field:t(e.id),optional:e.optional}}function Rs(e,t){let{fieldProxyId:r,relations:n,...i}=e;return{...i,field:t(r),...n===void 0?{}:{relations:n.map(({id:s,...o})=>({...o,field:t(s)}))}}}function id(e,t){let{targetEntity:r,...n}=e;return{...n,targetEntity:t(r)}}function Og(e,t){return{...e,gradedEntities:e.gradedEntities.map((r)=>id(r,t))}}function $F(e,t){switch(e.type){case"root":{let{datasetId:r,itemFilter:n,startedFieldProxies:i,completedFieldProxies:s,...o}=e.settings;return{...o,started:i.output.map((a)=>zn(a,t)),completed:s.input.map((a)=>zn(a,t))}}case"code":{let{fieldProxies:r,...n}=e.settings;return{...n,fieldProxies:{input:r.input.map((i)=>zn(i,t)),output:r.output.map((i)=>zn(i,t))}}}case"generation":{let{entities:r,qualityCriteria:n,exam:i,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Rs(o,t)),output:r.output.map((o)=>Rs(o,t))},qualityCriteria:n.map((o)=>id(o,t)),...i===void 0?{}:{exam:Og(i,t)}}}case"match":{let{conditions:r,fieldProxies:n,...i}=e.settings;return{...i,conditions:r.map(({predicates:s,...o})=>({...o,predicates:s.map(({fieldProxyId:a,...l})=>({...l,field:t(a)}))})),fieldProxies:{input:n.input.map((s)=>zn(s,t))}}}case"quorum":{let{entities:r,qualityCriteria:n,exam:i,...s}=e.settings;return{...s,entities:{input:r.input.map((o)=>Rs(o,t)),output:r.output.map((o)=>Rs(o,t))},qualityCriteria:n.map((o)=>id(o,t)),...i===void 0?{}:{exam:Og(i,t)}}}}}function IF(e,t,r,n){let i=new Set,o=$F(e,(c)=>{let p=n.get(c);return _(p,`Node "${e.id}" references unknown field "${c}"`),i.add(p),{name:p,[Tg]:!0}}),a=[...i].toSorted(Ft),l=[`import { ${e.type} } from '@toloka-platform/sdk';`,...a.length===0?[]:["",`import { ${a.join(", ")} } from '../../fields';`]],d=e.type==="root"?[`${ne(1)}${ke(o,1)}`,`${ne(1)}${ke({id:e.id},1)}`]:[`${ne(1)}${ke(e.settings.about.name,1)}`,`${ne(1)}${ke(o,1)}`,`${ne(1)}${ke({id:e.id},1)}`];return{binding:t,path:r,source:`${l.join(`
101
101
  `)}
102
102
 
103
103
  export const ${t} = ${e.type}(
104
- ${u.join(`,
104
+ ${d.join(`,
105
105
  `)}
106
106
  );
107
- `}}function wg(e,t){if(e.length===0)return`export {};
107
+ `}}function Ng(e,t){if(e.length===0)return`export {};
108
108
  `;return`import { field } from '@toloka-platform/sdk';
109
109
 
110
- ${e.map((i)=>{let n=t(i),s=[`${te(1)}${Ae(i.name,1)}`,`${te(1)}${Ae(i.jsonSchema,1)}`,...i.options===void 0?[]:[`${te(1)}${Ae(i.options,1)}`]];return{binding:n,source:`export const ${n} = field(
110
+ ${e.map((n)=>{let i=t(n),s=[`${ne(1)}${ke(n.name,1)}`,`${ne(1)}${ke(n.jsonSchema,1)}`,...n.options===void 0?[]:[`${ne(1)}${ke(n.options,1)}`]];return{binding:i,source:`export const ${i} = field(
111
111
  ${s.join(`,
112
112
  `)}
113
- );`}}).toSorted((i,n)=>Ft(i.binding,n.binding)).map(({source:i})=>i).join(`
113
+ );`}}).toSorted((n,i)=>Ft(n.binding,i.binding)).map(({source:n})=>n).join(`
114
114
 
115
115
  `)}
116
- `}function $g(e){let t=new Map(e.map((i)=>[i,`field:${i.options?.id??i.name}`])),r=Yl(e.map((i)=>({key:t.get(i)??"",name:i.name,fallback:"field"})),({name:i,fallback:n})=>vg(i,n),bg);return wg(e,(i)=>{let n=t.get(i);y(n,`Field "${i.name}" has no source key`);let s=r.get(n);return y(s,`Field "${i.name}" has no source binding`),s})}function zj(e,t){return wg(e.fields.map((r)=>({name:r.name,jsonSchema:r.jsonSchema,options:{id:r.id}})),(r)=>{let i=r.options?.id;y(i,`Field "${r.name}" has no source ID`);let n=t.get(i);return y(n,`Field "${i}" has no source binding`),n})}function yg(e,t,r,i){let n=r.get(e.node);y(n,`Connection references unknown node "${e.node}"`);let s=i.get(n.id);switch(y(s,`Node "${n.id}" has no source binding`),n.type){case"root":return y(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 y(e.handle===t,`${n.type} ${t} handle "${e.handle}" cannot be authored`),`${s}.${t}`;case"match":if(t==="input")return y(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);y(o,`Match output handle "${e.handle}" cannot be authored`);let a=o[1];return y(a!==void 0,`Match output handle "${e.handle}" has no index`),y(String(Number(a))===a,`Match output handle "${e.handle}" is not canonical`),`${s}.matched(${a})`}}function Wj(e,t,r,i,n){let s=new Map(e.nodes.map((c)=>[c.id,c])),o=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...i.values()].toSorted(Ft).join(", ")} } from './fields';`],...r.toSorted((c,p)=>Ft(c.path,p.path)).flatMap(({binding:c,path:p})=>[`import { ${c} } from './${p.slice(0,-3)}';`])],a=e.fields.map(({id:c})=>{let p=i.get(c);return y(p,`Field "${c}" has no source binding`),p}),d=e.nodes.map(({id:c})=>{let p=n.get(c);return y(p,`Node "${c}" has no source binding`),p}),u=e.connections.map((c)=>{let p=yg(c.from,"output",s,n),f=yg(c.to,"input",s,n);if(Object.keys(c.settings).length===0)return`connect(${p}, ${f})`;return`connect(
117
- ${te(3)}${p},
118
- ${te(3)}${f},
119
- ${te(3)}${Ae(c.settings,3)}
120
- ${te(2)})`}),l=(c,p)=>{if(c.length===0)return"[]";return`[
121
- ${c.map((f)=>`${te(p+1)}${f}`).join(`,
116
+ `}function Mg(e){let t=new Map(e.map((n)=>[n,`field:${n.options?.id??n.name}`])),r=nd(e.map((n)=>({key:t.get(n)??"",name:n.name,fallback:"field"})),({name:n,fallback:i})=>Dg(n,i),Ag);return Ng(e,(n)=>{let i=t.get(n);_(i,`Field "${n.name}" has no source key`);let s=r.get(i);return _(s,`Field "${n.name}" has no source binding`),s})}function EF(e,t){return Ng(e.fields.map((r)=>({name:r.name,jsonSchema:r.jsonSchema,options:{id:r.id}})),(r)=>{let n=r.options?.id;_(n,`Field "${r.name}" has no source ID`);let i=t.get(n);return _(i,`Field "${n}" has no source binding`),i})}function Fg(e,t,r,n){let i=r.get(e.node);_(i,`Connection references unknown node "${e.node}"`);let s=n.get(i.id);switch(_(s,`Node "${i.id}" has no source binding`),i.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,`${i.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 SF(e,t,r,n,i){let s=new Map(e.nodes.map((p)=>[p.id,p])),o=[`import { ${e.connections.length===0?"definePipeline":"connect, definePipeline"} } from '@toloka-platform/sdk';`,...e.fields.length===0?[]:["",`import { ${[...n.values()].toSorted(Ft).join(", ")} } from './fields';`],...r.toSorted((p,h)=>Ft(p.path,h.path)).flatMap(({binding:p,path:h})=>[`import { ${p} } from './${h.slice(0,-3)}';`])],a=e.fields.map(({id:p})=>{let h=n.get(p);return _(h,`Field "${p}" has no source binding`),h}),l=e.nodes.map(({id:p})=>{let h=i.get(p);return _(h,`Node "${p}" has no source binding`),h}),d=e.connections.map((p)=>{let h=Fg(p.from,"output",s,i),u=Fg(p.to,"input",s,i);if(Object.keys(p.settings).length===0)return`connect(${h}, ${u})`;return`connect(
117
+ ${ne(3)}${h},
118
+ ${ne(3)}${u},
119
+ ${ne(3)}${ke(p.settings,3)}
120
+ ${ne(2)})`}),c=(p,h)=>{if(p.length===0)return"[]";return`[
121
+ ${p.map((u)=>`${ne(h+1)}${u}`).join(`,
122
122
  `)}
123
- ${te(p)}]`};return`${o.join(`
123
+ ${ne(h)}]`};return`${o.join(`
124
124
  `)}
125
125
 
126
126
  export default definePipeline({
127
- dataset: ${Ae(t)},
128
- fields: ${l(a,1)},
129
- nodes: ${l(d,1)},
130
- connections: ${l(u,1)}
127
+ dataset: ${ke(t)},
128
+ fields: ${c(a,1)},
129
+ nodes: ${c(l,1)},
130
+ connections: ${c(d,1)}
131
131
  });
132
- `}function Eg(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=Yl(r,({name:u,fallback:l})=>vg(u,l),bg),n=Yl(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})=>Bj(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return y(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 y(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),c=n.get(`node:${u.id}`);return y(l&&c,`Node "${u.id}" has no allocated source name`),Kj(u,l,`nodes/${c}/node.ts`,s)}),d=[{path:"fields.ts",source:zj(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:Wj(e,t.dataset,a,s,o)}].toSorted((u,l)=>Ft(u.path,l.path));return Object.fromEntries(d.map(({path:u,source:l})=>[u,l]))}var yt=require("fs/promises"),Zt=require("path");var Kg=Ce(nl(),1),zg=Ce(Bg(),1);var Gg={$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"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],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 Wg=new Kg.default({strict:!1});zg.default(Wg);var Vg=Wg.compile(Gg),SF=(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 lc(e){if(Vg(e))return;let t=Vg.errors;y(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=SF(n),o=`${s.path}
133
- ${s.reason}`;if(r.has(o))continue;r.add(o),i.push(s)}throw or.fromIssues(i)}var xF=Symbol("fieldDefinition"),RF=Symbol.for("@toloka-platform/sdk/pipeline-definition"),Jg=Symbol("portDefinition"),CF=Symbol("nodeFieldReferences");function Qg(e,t){return{node:e,handle:t,direction:"input",[Jg]:"input"}}function Yg(e,t){return{node:e,handle:t,direction:"output",[Jg]:"output"}}function Xg(e){return typeof e==="object"&&e!==null&&xF in e}function cc(e,t){if(Xg(e)){t.push(e);return}if(Array.isArray(e)){for(let r of e)cc(r,t);return}if(typeof e==="object"&&e!==null)for(let r of Object.values(e))cc(r,t)}function OF(e){let t=[];return cc(e,t),t}function Hg(e){return Xg(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function jF(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:Yg(r,"started"),completed:Qg(r,"completed"),[CF]:OF(e)}}var tU=Object.assign(jF,{started:Yg("root","started"),completed:Qg("root","completed")});function FF(e){return typeof e==="object"&&e!==null&&RF in e}function Os(e){y(FF(e),"Invalid pipeline definition: expected a value returned by definePipeline"),y(e.dataset.length>0,"Dataset name must not be empty");for(let t of e.graph.nodes){if(t.type!=="root")continue;y(!("datasetId"in t.settings),"An unresolved pipeline definition cannot contain a dataset id"),y(!("itemFilter"in t.settings),"An unresolved pipeline definition cannot contain a dataset item filter")}lc(e.graph)}function Wi(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 lc(r),r}function Zg(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 Hi=require("fs/promises"),_e=require("path"),ey=require("url");var ty=async(e)=>{let t;try{t=await Hi.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=_e.join(e,i.name);if(i.isDirectory())r.push(...await ty(n));else if(i.isFile()&&i.name==="pipeline.ts")r.push(n)}return r},TF="toloka.json",kF=async(e)=>{try{return(await Hi.stat(_e.join(e,TF))).isFile()}catch{return!1}};async function ry(e){let t=_e.resolve(e);for(;;){if(await kF(t))return t;let r=_e.dirname(t);if(r===t)return;t=r}}async function js(e){let t=await ty(_e.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(i)=>{let n=await Hi.stat(i),s=ey.pathToFileURL(i);s.searchParams.set("version",`${n.mtimeMs}-${n.size}`);let o=await import(s.href);y(typeof o==="object"&&o!==null,`Invalid ${i}: expected a module`);let a=Reflect.get(o,"default");Os(a);let d=_e.relative(e,_e.dirname(i)).split(_e.sep).join("/");return{sourceDirectory:d,name:_e.basename(d),definition:a}}))).toSorted((i,n)=>i.sourceDirectory.localeCompare(n.sourceDirectory))}}var AF=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,uc=(e)=>{if(Array.isArray(e))return e.map(uc);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,uc(r)]))},Ee=(e)=>JSON.stringify(uc(e)),iy=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),sy=(e,t)=>{if(!iy(e)||!iy(t))return t;return Object.fromEntries(Object.keys(e).map((r)=>[r,sy(e[r],t[r])]))},DF=(e,t)=>Ee(e)===Ee(sy(e,t)),Ji=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},pc=(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},NF=(e)=>`${e.name} (${e.id})`,LF=(e,t)=>{let r=t.get(e.from.node),i=t.get(e.to.node),n=r===void 0?e.from.node:pc(r),s=i===void 0?e.to.node:pc(i);return`${n}.${e.from.handle} -> ${s}.${e.to.handle}`},Fs=(e)=>new Map(e.map((t)=>[t.id,t])),dc=(e,t,r,i)=>{let n=[];for(let[s,o]of[...e].toSorted(([a],[d])=>a.localeCompare(d))){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],[d])=>a.localeCompare(d)))if(!e.has(s))n.push(i(o,"removed"));return n};function qF(e,t){let r=Fs(e.nodes),i=Fs(t.nodes),n=new Map(e.connections.map((o)=>[Ee(o),o])),s=new Map(t.connections.map((o)=>[Ee(o),o]));return[...dc(Fs(e.fields),Fs(t.fields),(o,a)=>Ee(o)===Ee(a),(o,a)=>({kind:"field",action:a,label:NF(o),id:o.id})),...dc(r,i,DF,(o,a)=>({kind:"node",action:a,label:pc(o),id:o.id})),...dc(n,s,()=>!0,(o,a)=>({kind:"connection",action:a,label:LF(o,a==="removed"?i:r)})),...Ee(e.layout)===Ee(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var fc=(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)}},Ts=(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(y(s===void 0||Ee(s.jsonSchema)===Ee(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))}))},MF=(e)=>{let t=new Set;for(let r of e.pipelines)y(AF.test(r.sourceDirectory),`Invalid pipeline source directory ${r.sourceDirectory}`),y(!t.has(r.sourceDirectory),`Pipeline source directory ${r.sourceDirectory} is declared more than once`),t.add(r.sourceDirectory),Os(r.definition);Ts(e)},UF=(e,t,r)=>{let i=t===void 0?void 0:r.find((s)=>s.id===t.datasetId);if(i!==void 0)return y(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 y(n.length<=1,`Project has multiple datasets named "${e}".`),n[0]},BF=(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 y(n.length<=1,`Project has multiple pipelines named "${e.name}".`),n[0]},GF=(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}`}},VF=(e,t)=>{if(e.length===0)return"No changes.";let r=e.length===1?"change":"changes",i=[`Plan: ${e.length} ${r}`,...e.map(GF)];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(`
134
- `)},KF=async(e,t,r,i)=>{let n=t.map((o)=>({desired:o,dataset:UF(o.name,r?.datasets[o.name],i)})),s=await Promise.all(n.map(async({dataset:o})=>o===void 0?[]:Ji(e.datasets.listAllFields({datasetId:o.id}))));return n.map(({desired:o,dataset:a},d)=>{let u=s[d]??[],l=new Map(u.map((c)=>[c.name,c]));return{...o,...a===void 0?{}:{dataset:a},liveFields:u,missingFields:o.fields.filter((c)=>!l.has(c.name)),conflictingFields:o.fields.filter((c)=>{let p=l.get(c.name);return p!==void 0&&Ee(p.jsonSchema)!==Ee(c.jsonSchema)})}})},zF=async(e,t,r,i,n)=>{let s=t.pipelines.map((a)=>({source:a,pipeline:BF(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:d},u)=>{let l=o[u],c=i.find((f)=>f.name===a.definition.dataset)?.dataset,p=[];if(d!==void 0&&l!==void 0)p=c===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:qF(fc(Wi(a.definition,{datasetId:c.id}),l.graph),l.graph);return{source:a,...d===void 0?{}:{pipeline:d},...l===void 0?{}:{snapshot:l},graphChanges:p}})},WF=(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},ks=async(e,t)=>{let r=t.source??await js(t.sourceRoot);MF(r);let i=await Ie(t.sourceRoot),n=t.projectId??i?.projectId;y(n,de);let s=i?.projectId===n?i:void 0,o=new Set(r.pipelines.flatMap(({definition:b})=>Zg(b.graph))),a=t.listAllSecrets===!0||o.size>0,[d,u,l]=await Promise.all([Ji(e.pipelines.listAll({projectId:n})),Ji(e.datasets.listAll({projectId:n})),a?e.secrets.list({projectId:n}):Promise.resolve([])]),c=Ts(r),p=Object.keys(s?.datasets??{}).filter((b)=>!c.some((v)=>v.name===b)).toSorted(),f=Object.keys(s?.pipelines??{}).filter((b)=>!r.pipelines.some((v)=>v.sourceDirectory===b)).toSorted(),m=await KF(e,c,s,u),h=await zF(e,r,s,m,d),g=new Set(l.map((b)=>b.name)),_=[...o].filter((b)=>!g.has(b)).toSorted();return{projectId:n,source:r,state:i,datasets:m,pipelines:h,livePipelines:d,liveDatasets:u,liveSecrets:l,changes:WF(m,h,_,p,f),missingSecrets:_,removedDatasets:p,removedPipelines:f}},ny=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",HF=(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")},JF=(e)=>{let t=Map.groupBy(e,(r)=>ny(r.name));return new Map(e.map((r)=>{let i=ny(r.name),n=(t.get(i)?.length??0)>1;return[r.id,`pipelines/${n?`${i}-${HF(r.id)}`:i}`]}))};async function oy(e,t){let r=(await Ji(e.pipelines.listAll({projectId:t.projectId}))).toSorted((b,v)=>b.name.localeCompare(v.name)||b.id.localeCompare(v.id)),i=await Promise.all(r.map((b)=>e.pipelines.getGraph({pipelineId:b.id}))),n=new Set;for(let b of i){let v=b.graph.nodes.find((w)=>w.type==="root");y(v?.settings.datasetId,"Every imported pipeline must have a bound dataset."),n.add(v.settings.datasetId)}let s=await Ji(e.datasets.listAll({projectId:t.projectId})),o=[];for(let b of[...n].toSorted()){let v=s.find((w)=>w.id===b);y(v,`Project ${t.projectId} has no dataset ${b}.`),o.push(v)}let a=new Map(o.map((b)=>[b.id,b])),d=JF(r),u={},l={},c={};for(let[b,v]of r.entries()){let w=i[b];y(w,`Pipeline ${v.id} has no graph snapshot.`);let I=w.graph.nodes.find((R)=>R.type==="root");y(I?.settings.datasetId,`Pipeline ${v.id} has no dataset binding.`);let E=a.get(I.settings.datasetId);y(E,`Pipeline ${v.id} references unknown dataset ${I.settings.datasetId}.`);let x=c[E.name];y(x===void 0||x.datasetId===E.id,`Project has multiple referenced datasets named "${E.name}".`),c[E.name]={datasetId:E.id};let T=d.get(v.id);y(T,`Pipeline ${v.id} has no source directory.`),l[T]={pipelineId:v.id};for(let[R,V]of Object.entries(Eg(w.graph,{dataset:E.name})))u[`${T}/${R}`]=V}await yt.mkdir(t.sourceRoot,{recursive:!0});let p=Zt.join(t.sourceRoot,"pipelines"),f=!1;try{f=(await yt.stat(p)).isDirectory()}catch(b){if(!(b instanceof Error)||!("code"in b)||b.code!=="ENOENT")throw b}if(y(!f||t.force===!0,`Folder already exists: ${p}. Pass --force to replace it.`),f)await yt.rm(p,{recursive:!0,force:!0});for(let[b,v]of Object.entries(u).toSorted(([w],[I])=>w.localeCompare(I))){let w=Zt.join(t.sourceRoot,b);await yt.mkdir(Zt.dirname(w),{recursive:!0}),await yt.writeFile(w,v,"utf8")}let m={projectId:t.projectId,pipelines:l,datasets:c};await Gt(t.sourceRoot,m);let h=[...Object.keys(u),Kn].toSorted(),g=r.length===1?"pipeline":"pipelines",_=o.length===1?"dataset":"datasets";return{state:m,files:h,output:`Imported project ${t.projectId} with ${r.length} ${g} and ${o.length} ${_} into ${Zt.resolve(t.sourceRoot)}.`}}async function ay(e,t){let r=await ks(e,t);return{projectId:r.projectId,changes:r.changes,missingSecrets:r.missingSecrets,output:VF(r.changes,r.missingSecrets)}}async function ly(e,t){let r=t.projectId;y(r,de);let i=await e.projects.get({projectId:r}),n=await ks(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(`
135
- `)}}async function cy(e,t){let r=await ks(e,t);y(r.removedPipelines.length===0,`Refusing to delete pipelines absent from source: ${r.removedPipelines.join(", ")}.`),y(r.removedDatasets.length===0,`Refusing to delete datasets absent from source: ${r.removedDatasets.join(", ")}. Dataset items are never deleted.`),y(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((c)=>`${l.name}.${c.name}`));y(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 c=l.dataset;if(c===void 0)c=await e.datasets.create({projectId:r.projectId,name:l.name}),n+=1;if(s.set(l.name,c.id),l.missingFields.length>0)await e.datasets.createFields({datasetId:c.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 c=s.get(l.source.definition.dataset);y(c,`Dataset ${l.source.definition.dataset} has no resolved ID.`);let p=Wi(l.source.definition,{datasetId:c});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:c}),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;y(f,`Pipeline ${l.pipeline.id} has no graph snapshot.`),await e.pipelines.replaceGraph({pipelineId:l.pipeline.id,graph:fc(p,f.graph),expectedVersion:f.version}),n+=1}let a={projectId:r.projectId,pipelines:Object.fromEntries(r.source.pipelines.map((l)=>{let c=o.get(l.sourceDirectory);return y(c,`Pipeline ${l.sourceDirectory} has no resolved ID.`),[l.sourceDirectory,{pipelineId:c}]})),datasets:Object.fromEntries(r.datasets.map((l)=>{let c=s.get(l.name);return y(c,`Dataset ${l.name} has no resolved ID.`),[l.name,{datasetId:c}]}))};if(Ee(r.state)!==Ee(a))await Gt(t.sourceRoot,a);let d=n===0?"unchanged":"changed",u=n===0?"No changes.":`Applied ${n} ${n===1?"write":"writes"} to project ${r.projectId}.`;return{action:d,state:a,changes:r.changes,writes:n,output:u}}var QF=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),YF=(e)=>e.issues.map((t)=>{let r=QF(t);return` ${t.severity} ${t.code}${r.length===0?"":` ${r}`}: ${t.message}`});async function dy(e,t){let r=await ks(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 d=o.snapshot===void 0?Wi(o.source.definition,{datasetId:a.id}):fc(Wi(o.source.definition,{datasetId:a.id}),o.snapshot.graph),u=await e.pipelines.validateGraph({pipelineId:o.pipeline.id,graph:d});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 y(o.report,`Pipeline ${o.sourceDirectory} is missing a validation report`),[o.report.valid?`- ${o.sourceDirectory}: valid`:`- ${o.sourceDirectory}: invalid`,...YF(o.report)]});return{projectId:r.projectId,results:i,valid:n,output:s.length===0?"No pipelines to validate.":s.join(`
136
- `)}}var py="uploaded",XF=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ZF=(e)=>XF.test(e)?e.toLowerCase():void 0,hc=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),mc=(e)=>{if(!hc(e))return"unknown";if(Array.isArray(e.anyOf)){let i=[...new Set(e.anyOf.map(mc))];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=mc(e.items);return n==="unknown"?"array":`array<${n}>`}).join(" | ")},eT=(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}: ${mc(t.jsonSchema)}`)].join(`
137
- `)},fy=async(e)=>{let t=e.source??await js(e.sourceRoot),r=Ts(t).find((i)=>i.name===e.datasetName);return r===void 0?[]:r.fields.map((i)=>({name:i.name,jsonSchema:i.jsonSchema}))},uy=(e)=>`${e.name} (${e.id})`,my=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})},gc=async(e,t,r)=>{let i=await Ie(t.sourceRoot),n=t.projectId??i?.projectId;y(n,de);let s=t.datasetName,o=await my(e,n),a=(f)=>o.filter((m)=>m.name===f).length<=1,d=ZF(s),u=o.find((f)=>f.id===s||f.id.toLowerCase()===d);if(u!==void 0)return{datasetId:u.id,name:u.name,nameIsUnique:a(u.name)};let l=o.filter((f)=>f.name===s);if(y(l.length<=1,`Project ${n} has multiple datasets named "${s}": ${l.map(uy).join(", ")}.`),l.length===1){let[f]=l;return y(f,`Dataset "${s}" has no resolved ID.`),{datasetId:f.id,name:f.name,nameIsUnique:!0}}let c=i?.projectId===n?i.datasets[s]:void 0;if(c!==void 0){let f=o.find((m)=>m.id===c.datasetId);if(f!==void 0)return{datasetId:f.id,name:f.name,nameIsUnique:a(f.name)}}y(r&&d===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(uy).join(", ")}.`),y((await fy(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}},tT=async(e)=>(await Br.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{y(!1,`${Ur.basename(e)}:${i} is not valid JSON`)}return y(hc(n),`${Ur.basename(e)}:${i} must contain a JSON object`),n});async function hy(e,t){let r=await tT(t.filePath),i=await gc(e,t,!0),n=i.datasetId,s=new Map;for await(let b of e.datasets.listAllFields({datasetId:n})){if(b.internal||b.name===py)continue;s.set(b.name,{name:b.name,jsonSchema:b.jsonSchema})}for(let b of await fy({...t,datasetName:i.name}))if(!s.has(b.name))s.set(b.name,b);let o=[...s.values()],a=JSON.stringify(r),d=new TextEncoder().encode(a),u=await e.datasets.startUpload({datasetId:n,filename:Ur.basename(t.filePath),format:"json",declaredSizeBytes:d.byteLength,fields:o}),l=await(t.fetch??globalThis.fetch)(u.uploadUrl,{method:"PUT",headers:{"Content-Type":"application/json","x-ms-blob-type":"BlockBlob"},body:d});y(l.ok,`Dataset upload failed with HTTP ${l.status}.`),await e.datasets.finalizeUpload({uploadId:u.job.id});let c=await e.waitFor({type:"datasetUpload",uploadId:u.job.id},t.waitFor),p=i.nameIsUnique?i.name:i.datasetId,f=c.status==="failed"&&c.error?.startsWith("Schema incompatible with existing upload")===!0?`
138
- Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";y(c.status==="succeeded",`${c.error??`Dataset upload ${c.id} failed.`}${f}`);let m=`Uploaded ${c.result.itemsIngested} rows to dataset ${i.name}.`,h=[],g,_;try{h=(await e.datasets.getInferredFields({datasetId:n})).fields,g=eT(h)}catch(b){_=`Upload succeeded, but inferred fields could not be fetched: ${b instanceof Error?b.message:String(b)}`}return{datasetId:n,rowsUploaded:c.result.itemsIngested,inferredFields:h,output:g===void 0?m:`${m}
139
- ${g}`,..._===void 0?{}:{warning:_}}}async function gy(e,t){let r=await gc(e,t,!1),i=await e.datasets.getInferredFields({datasetId:r.datasetId}),n=i.fields.filter((o)=>o.depth===1),s=$g(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 yy(e,t){let r=await my(e,t.projectId);if(r.length===0)return{output:"This project has no datasets."};return{output:r.map((i)=>`${i.name} ${i.id}`).join(`
140
- `)}}var rT=async(e)=>{let t=await e.fetch(e.downloadUrl);y(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})}y(Array.isArray(i),`Dataset export ${e.exportId} is not a JSON array.`);let n=[];for(let[s,o]of i.entries())y(hc(o),`Dataset export ${e.exportId} row ${s} is not a JSON object.`),n.push(o);return n};async function _y(e,t){let r=await gc(e,t,!1),i=[];for await(let d of e.datasets.listAllFields({datasetId:r.datasetId})){if(d.internal||d.name===py)continue;i.push(d.name)}y(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(d){throw y(!(d instanceof re&&d.code==="wait_timeout"),`Stopped waiting for dataset export ${n.id}; raise --timeout to wait longer.`),d}y(s.result.downloadUrl,`Dataset export ${s.id} succeeded without a download URL.`);let o=await rT({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 Br.mkdir(Ur.dirname(t.outPath),{recursive:!0}),await Br.writeFile(t.outPath,a.length===0?"":`${a.map((d)=>JSON.stringify(d)).join(`
132
+ `}function Lg(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((d)=>({key:`field:${d.id}`,name:d.name,fallback:"field"})),...e.nodes.map((d)=>({key:`node:${d.id}`,name:d.type==="root"?"root":d.settings.about.name||d.type,fallback:d.type}))],n=nd(r,({name:d,fallback:c})=>Dg(d,c),Ag),i=nd(e.nodes.map((d)=>({key:`node:${d.id}`,name:d.type==="root"?"root":d.settings.about.name||d.type,fallback:d.type})),({name:d,fallback:c})=>vF(d,c)),s=new Map(e.fields.map((d)=>{let c=n.get(`field:${d.id}`);return _(c,`Field "${d.id}" has no allocated binding`),[d.id,c]})),o=new Map(e.nodes.map((d)=>{let c=n.get(`node:${d.id}`);return _(c,`Node "${d.id}" has no allocated binding`),[d.id,c]})),a=e.nodes.map((d)=>{let c=o.get(d.id),p=i.get(`node:${d.id}`);return _(c&&p,`Node "${d.id}" has no allocated source name`),IF(d,c,`nodes/${p}/node.ts`,s)}),l=[{path:"fields.ts",source:EF(e,s)},...a.map(({path:d,source:c})=>({path:d,source:c})),{path:"pipeline.ts",source:SF(e,t.dataset,a,s,o)}].toSorted((d,c)=>Ft(d.path,c.path));return Object.fromEntries(l.map(({path:d,source:c})=>[d,c]))}var _t=require("fs/promises"),Zt=require("path");var oy=Re(cl(),1),ay=Re(ny(),1);var iy={$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"},maxCostPerAttempt:{type:"number"}},required:["audienceType","maxCostPerAttempt"],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 ly=new oy.default({strict:!1});ay.default(ly);var sy=ly.compile(iy),sT=(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 md(e){if(sy(e))return;let t=sy.errors;_(t,"Pipeline graph validation failed without errors");let r=new Set,n=[];for(let i of t){let s=sT(i),o=`${s.path}
133
+ ${s.reason}`;if(r.has(o))continue;r.add(o),n.push(s)}throw ar.fromIssues(n)}var oT=Symbol("fieldDefinition"),aT=Symbol.for("@toloka-platform/sdk/pipeline-definition"),cy=Symbol("portDefinition"),lT=Symbol("nodeFieldReferences");function uy(e,t){return{node:e,handle:t,direction:"input",[cy]:"input"}}function py(e,t){return{node:e,handle:t,direction:"output",[cy]:"output"}}function fy(e){return typeof e==="object"&&e!==null&&oT in e}function hd(e,t){if(fy(e)){t.push(e);return}if(Array.isArray(e)){for(let r of e)hd(r,t);return}if(typeof e==="object"&&e!==null)for(let r of Object.values(e))hd(r,t)}function dT(e){let t=[];return hd(e,t),t}function dy(e){return fy(e)?{id:e.id,optional:!1}:{id:e.field.id,optional:e.optional??!1}}function cT(e,t={}){let r=t.id??"root",{started:n,completed:i,...s}=e;return{id:r,type:"root",settings:{...s,startedFieldProxies:{output:n.map(dy)},completedFieldProxies:{input:i.map(dy)}},started:py(r,"started"),completed:uy(r,"completed"),[lT]:dT(e)}}var LU=Object.assign(cT,{started:py("root","started"),completed:uy("root","completed")});function uT(e){return typeof e==="object"&&e!==null&&aT in e}function Fs(e){_(uT(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")}md(e.graph)}function Hn(e,t){let r={version:e.graph.version,fields:e.graph.fields.map((n)=>({...n})),nodes:e.graph.nodes.map((n)=>n.type==="root"?{...n,settings:{...n.settings,datasetId:t.datasetId}}:n),connections:e.graph.connections.map((n)=>({from:{...n.from},to:{...n.to},settings:{...n.settings}}))};return md(r),r}function my(e){let t=new Set;for(let r of e.nodes){if(r.type!=="code")continue;for(let n of r.settings.envVars??[])if(n.type==="secret")t.add(n.secretName)}return[...t].toSorted((r,n)=>r.localeCompare(n))}var Jn=require("fs/promises"),_e=require("path"),hy=require("url");var gy=async(e)=>{let t;try{t=await Jn.readdir(e,{withFileTypes:!0})}catch(n){if(n instanceof Error&&Reflect.get(n,"code")==="ENOENT")return[];throw n}let r=[];for(let n of t.toSorted((i,s)=>i.name.localeCompare(s.name))){let i=_e.join(e,n.name);if(n.isDirectory())r.push(...await gy(i));else if(n.isFile()&&n.name==="pipeline.ts")r.push(i)}return r},pT="toloka.json",fT=async(e)=>{try{return(await Jn.stat(_e.join(e,pT))).isFile()}catch{return!1}};async function yy(e){let t=_e.resolve(e);for(;;){if(await fT(t))return t;let r=_e.dirname(t);if(r===t)return;t=r}}async function Ts(e){let t=await gy(_e.join(e,"pipelines"));return{pipelines:(await Promise.all(t.map(async(n)=>{let i=await Jn.stat(n),s=hy.pathToFileURL(n);s.searchParams.set("version",`${i.mtimeMs}-${i.size}`);let o=await import(s.href);_(typeof o==="object"&&o!==null,`Invalid ${n}: expected a module`);let a=Reflect.get(o,"default");Fs(a);let l=_e.relative(e,_e.dirname(n)).split(_e.sep).join("/");return{sourceDirectory:l,name:_e.basename(l),definition:a}}))).toSorted((n,i)=>n.sourceDirectory.localeCompare(i.sourceDirectory))}}var mT=/^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.?(?:\/|$))(?!.*\/\/).+$/u,yd=(e)=>{if(Array.isArray(e))return e.map(yd);if(typeof e!=="object"||e===null)return e;return Object.fromEntries(Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,yd(r)]))},Ie=(e)=>JSON.stringify(yd(e)),_y=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Py=(e,t)=>{if(!_y(e)||!_y(t))return t;return Object.fromEntries(Object.keys(e).map((r)=>[r,Py(e[r],t[r])]))},hT=(e,t)=>Ie(e)===Ie(Py(e,t)),Qn=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},_d=(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},gT=(e)=>`${e.name} (${e.id})`,yT=(e,t)=>{let r=t.get(e.from.node),n=t.get(e.to.node),i=r===void 0?e.from.node:_d(r),s=n===void 0?e.to.node:_d(n);return`${i}.${e.from.handle} -> ${s}.${e.to.handle}`},As=(e)=>new Map(e.map((t)=>[t.id,t])),gd=(e,t,r,n)=>{let i=[];for(let[s,o]of[...e].toSorted(([a],[l])=>a.localeCompare(l))){let a=t.get(s);if(a===void 0)i.push(n(o,"added"));else if(!r(o,a))i.push(n(o,"changed"))}for(let[s,o]of[...t].toSorted(([a],[l])=>a.localeCompare(l)))if(!e.has(s))i.push(n(o,"removed"));return i};function _T(e,t){let r=As(e.nodes),n=As(t.nodes),i=new Map(e.connections.map((o)=>[Ie(o),o])),s=new Map(t.connections.map((o)=>[Ie(o),o]));return[...gd(As(e.fields),As(t.fields),(o,a)=>Ie(o)===Ie(a),(o,a)=>({kind:"field",action:a,label:gT(o),id:o.id})),...gd(r,n,hT,(o,a)=>({kind:"node",action:a,label:_d(o),id:o.id})),...gd(i,s,()=>!0,(o,a)=>({kind:"connection",action:a,label:yT(o,a==="removed"?n:r)})),...Ie(e.layout)===Ie(t.layout)?[]:[{kind:"layout",action:"changed",label:"pipeline layout"}]]}var bd=(e,t)=>{let r=t.nodes.find((i)=>i.type==="root"),n=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((i)=>i.type==="root"?{...i,settings:{...n,...i.settings}}:i)}},ks=(e)=>{let t=new Map;for(let r of e.pipelines){let n=t.get(r.definition.dataset);if(n===void 0)n=new Map,t.set(r.definition.dataset,n);for(let i of r.definition.graph.fields){let s=n.get(i.name);if(_(s===void 0||Ie(s.jsonSchema)===Ie(i.jsonSchema),`Dataset "${r.definition.dataset}" has conflicting schemas for field "${i.name}".`),s===void 0)n.set(i.name,i)}}return[...t].toSorted(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({name:r,fields:[...n.values()].toSorted((i,s)=>i.name.localeCompare(s.name))}))},bT=(e)=>{let t=new Set;for(let r of e.pipelines)_(mT.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),Fs(r.definition);ks(e)},PT=(e,t,r)=>{let n=t===void 0?void 0:r.find((s)=>s.id===t.datasetId);if(n!==void 0)return _(n.name===e,`Dataset ${n.id} is bound as "${e}" but is named "${n.name}".`),n;let i=r.filter((s)=>s.name===e);return _(i.length<=1,`Project has multiple datasets named "${e}".`),i[0]},vT=(e,t,r)=>{let n=t===void 0?void 0:r.find((s)=>s.id===t.pipelineId);if(n!==void 0)return n;let i=r.filter((s)=>s.name===e.name);return _(i.length<=1,`Project has multiple pipelines named "${e.name}".`),i[0]},wT=(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}`}},$T=(e,t)=>{if(e.length===0)return"No changes.";let r=e.length===1?"change":"changes",n=[`Plan: ${e.length} ${r}`,...e.map(wT)];if(t.length>0){n.push("","Required secrets are missing:");for(let i of t)n.push(` ${i}`);n.push("Run `toloka secret set <name>` before apply.")}return n.join(`
134
+ `)},IT=async(e,t,r,n)=>{let i=t.map((o)=>({desired:o,dataset:PT(o.name,r?.datasets[o.name],n)})),s=await Promise.all(i.map(async({dataset:o})=>o===void 0?[]:Qn(e.datasets.listAllFields({datasetId:o.id}))));return i.map(({desired:o,dataset:a},l)=>{let d=s[l]??[],c=new Map(d.map((p)=>[p.name,p]));return{...o,...a===void 0?{}:{dataset:a},liveFields:d,missingFields:o.fields.filter((p)=>!c.has(p.name)),conflictingFields:o.fields.filter((p)=>{let h=c.get(p.name);return h!==void 0&&Ie(h.jsonSchema)!==Ie(p.jsonSchema)})}})},ET=async(e,t,r,n,i)=>{let s=t.pipelines.map((a)=>({source:a,pipeline:vT(a,r?.pipelines[a.sourceDirectory],i)})),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:l},d)=>{let c=o[d],p=n.find((u)=>u.name===a.definition.dataset)?.dataset,h=[];if(l!==void 0&&c!==void 0)h=p===void 0?[{kind:"node",action:"changed",label:"root dataset binding",id:"root"}]:_T(bd(Hn(a.definition,{datasetId:p.id}),c.graph),c.graph);return{source:a,...l===void 0?{}:{pipeline:l},...c===void 0?{}:{snapshot:c},graphChanges:h}})},ST=(e,t,r,n,i)=>{let s=[];for(let o of i)s.push({kind:"pipeline",action:"removed",label:o});for(let o of n)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},Ds=async(e,t)=>{let r=t.source??await Ts(t.sourceRoot);bT(r);let n=await Ee(t.sourceRoot),i=t.projectId??n?.projectId;_(i,X);let s=n?.projectId===i?n:void 0,o=new Set(r.pipelines.flatMap(({definition:b})=>my(b.graph))),a=t.listAllSecrets===!0||o.size>0,[l,d,c]=await Promise.all([Qn(e.pipelines.listAll({projectId:i})),Qn(e.datasets.listAll({projectId:i})),a?e.secrets.list({projectId:i}):Promise.resolve([])]),p=ks(r),h=Object.keys(s?.datasets??{}).filter((b)=>!p.some((v)=>v.name===b)).toSorted(),u=Object.keys(s?.pipelines??{}).filter((b)=>!r.pipelines.some((v)=>v.sourceDirectory===b)).toSorted(),f=await IT(e,p,s,d),m=await ET(e,r,s,f,l),g=new Set(c.map((b)=>b.name)),y=[...o].filter((b)=>!g.has(b)).toSorted();return{projectId:i,source:r,state:n,datasets:f,pipelines:m,livePipelines:l,liveDatasets:d,liveSecrets:c,changes:ST(f,m,y,h,u),missingSecrets:y,removedDatasets:h,removedPipelines:u}},by=(e)=>e.toLowerCase().match(/[a-z0-9]+/gu)?.join("-")||"pipeline",xT=(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")},jT=(e)=>{let t=Map.groupBy(e,(r)=>by(r.name));return new Map(e.map((r)=>{let n=by(r.name),i=(t.get(n)?.length??0)>1;return[r.id,`pipelines/${i?`${n}-${xT(r.id)}`:n}`]}))};async function vy(e,t){let r=(await Qn(e.pipelines.listAll({projectId:t.projectId}))).toSorted((b,v)=>b.name.localeCompare(v.name)||b.id.localeCompare(v.id)),n=await Promise.all(r.map((b)=>e.pipelines.getGraph({pipelineId:b.id}))),i=new Set;for(let b of n){let v=b.graph.nodes.find((I)=>I.type==="root");_(v?.settings.datasetId,"Every imported pipeline must have a bound dataset."),i.add(v.settings.datasetId)}let s=await Qn(e.datasets.listAll({projectId:t.projectId})),o=[];for(let b of[...i].toSorted()){let v=s.find((I)=>I.id===b);_(v,`Project ${t.projectId} has no dataset ${b}.`),o.push(v)}let a=new Map(o.map((b)=>[b.id,b])),l=jT(r),d={},c={},p={};for(let[b,v]of r.entries()){let I=n[b];_(I,`Pipeline ${v.id} has no graph snapshot.`);let E=I.graph.nodes.find((R)=>R.type==="root");_(E?.settings.datasetId,`Pipeline ${v.id} has no dataset binding.`);let w=a.get(E.settings.datasetId);_(w,`Pipeline ${v.id} references unknown dataset ${E.settings.datasetId}.`);let x=p[w.name];_(x===void 0||x.datasetId===w.id,`Project has multiple referenced datasets named "${w.name}".`),p[w.name]={datasetId:w.id};let T=l.get(v.id);_(T,`Pipeline ${v.id} has no source directory.`),c[T]={pipelineId:v.id};for(let[R,V]of Object.entries(Lg(I.graph,{dataset:w.name})))d[`${T}/${R}`]=V}await _t.mkdir(t.sourceRoot,{recursive:!0});let h=Zt.join(t.sourceRoot,"pipelines"),u=!1;try{u=(await _t.stat(h)).isDirectory()}catch(b){if(!(b instanceof Error)||!("code"in b)||b.code!=="ENOENT")throw b}if(_(!u||t.force===!0,`Folder already exists: ${h}. Pass --force to replace it.`),u)await _t.rm(h,{recursive:!0,force:!0});for(let[b,v]of Object.entries(d).toSorted(([I],[E])=>I.localeCompare(E))){let I=Zt.join(t.sourceRoot,b);await _t.mkdir(Zt.dirname(I),{recursive:!0}),await _t.writeFile(I,v,"utf8")}let f={projectId:t.projectId,pipelines:c,datasets:p};await Gt(t.sourceRoot,f);let m=[...Object.keys(d),Wi].toSorted(),g=r.length===1?"pipeline":"pipelines",y=o.length===1?"dataset":"datasets";return{state:f,files:m,output:`Imported project ${t.projectId} with ${r.length} ${g} and ${o.length} ${y} into ${Zt.resolve(t.sourceRoot)}.`}}async function wy(e,t){let r=await Ds(e,t);return{projectId:r.projectId,changes:r.changes,missingSecrets:r.missingSecrets,output:$T(r.changes,r.missingSecrets)}}async function $y(e,t){let r=t.projectId;_(r,X);let n=await e.projects.get({projectId:r}),i=await Ds(e,{...t,listAllSecrets:!0}),s=i.changes.length,o=s===0?"Source has no pending changes.":`Source has ${s} pending change${s===1?"":"s"}.`;return{projectId:r,output:[`Project: ${r} (${n.name})`,`Team: ${n.teamId}`,`Pipelines: ${i.livePipelines.length}`,`Datasets: ${i.liveDatasets.length}`,`Secrets: ${i.liveSecrets.length}`,o].join(`
135
+ `)}}async function Iy(e,t){let r=await Ds(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 n=r.datasets.flatMap((c)=>c.conflictingFields.map((p)=>`${c.name}.${p.name}`));_(n.length===0,`Dataset field schemas conflict with source: ${n.join(", ")}. Existing fields are never rewritten.`);let i=0,s=new Map;for(let c of r.datasets){let p=c.dataset;if(p===void 0)p=await e.datasets.create({projectId:r.projectId,name:c.name}),i+=1;if(s.set(c.name,p.id),c.missingFields.length>0)await e.datasets.createFields({datasetId:p.id,fields:c.missingFields.map((h)=>({name:h.name,jsonSchema:h.jsonSchema}))}),i+=c.missingFields.length}let o=new Map;for(let c of r.pipelines){let p=s.get(c.source.definition.dataset);_(p,`Dataset ${c.source.definition.dataset} has no resolved ID.`);let h=Hn(c.source.definition,{datasetId:p});if(c.pipeline===void 0){let f=await e.pipelines.import({projectId:r.projectId,name:c.source.name,graph:h});await e.pipelines.attachDataset({pipelineId:f.id,datasetId:p}),o.set(c.source.sourceDirectory,f.id),i+=2;continue}if(o.set(c.source.sourceDirectory,c.pipeline.id),c.graphChanges.length===0)continue;let u=c.snapshot;_(u,`Pipeline ${c.pipeline.id} has no graph snapshot.`),await e.pipelines.replaceGraph({pipelineId:c.pipeline.id,graph:bd(h,u.graph),expectedVersion:u.version}),i+=1}let a={projectId:r.projectId,pipelines:Object.fromEntries(r.source.pipelines.map((c)=>{let p=o.get(c.sourceDirectory);return _(p,`Pipeline ${c.sourceDirectory} has no resolved ID.`),[c.sourceDirectory,{pipelineId:p}]})),datasets:Object.fromEntries(r.datasets.map((c)=>{let p=s.get(c.name);return _(p,`Dataset ${c.name} has no resolved ID.`),[c.name,{datasetId:p}]}))};if(Ie(r.state)!==Ie(a))await Gt(t.sourceRoot,a);let l=i===0?"unchanged":"changed",d=i===0?"No changes.":`Applied ${i} ${i===1?"write":"writes"} to project ${r.projectId}.`;return{action:l,state:a,changes:r.changes,writes:i,output:d}}var RT=(e)=>[e.nodeId,e.checkId].filter((t)=>t!==void 0).join("/"),CT=(e)=>e.issues.map((t)=>{let r=RT(t);return` ${t.severity} ${t.code}${r.length===0?"":` ${r}`}: ${t.message}`});async function Ey(e,t){let r=await Ds(e,t),n=[];for(let o of r.pipelines){let a=r.datasets.find((c)=>c.name===o.source.definition.dataset)?.dataset;if(o.pipeline===void 0){n.push({sourceDirectory:o.source.sourceDirectory,skipped:"pipeline is not on the platform yet; run toloka apply first"});continue}if(a===void 0){n.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 l=o.snapshot===void 0?Hn(o.source.definition,{datasetId:a.id}):bd(Hn(o.source.definition,{datasetId:a.id}),o.snapshot.graph),d=await e.pipelines.validateGraph({pipelineId:o.pipeline.id,graph:l});n.push({sourceDirectory:o.source.sourceDirectory,pipelineId:o.pipeline.id,report:d})}let i=n.every((o)=>o.report?.valid!==!1),s=n.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`,...CT(o.report)]});return{projectId:r.projectId,results:n,valid:i,output:s.length===0?"No pipelines to validate.":s.join(`
136
+ `)}}var jy="uploaded",OT=/^ds\.[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sy=3;class Ms extends Error{constructor(e,t){super(e,{cause:t});this.name="DatasetUploadError"}}var FT=(e)=>OT.test(e)?e.toLowerCase():void 0,TT={json:"application/json",jsonl:"application/x-ndjson",csv:"text/csv"},vd=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Pd=(e)=>{if(!vd(e))return"unknown";if(Array.isArray(e.anyOf)){let n=[...new Set(e.anyOf.map(Pd))];return n.length===0?"unknown":n.join(" | ")}let t=e.type,r=typeof t==="string"?[t]:Array.isArray(t)?t.filter((n)=>typeof n==="string"):[];if(r.length===0)return"unknown";return r.map((n)=>{if(n!=="array")return n;let i=Pd(e.items);return i==="unknown"?"array":`array<${i}>`}).join(" | ")},AT=(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}: ${Pd(t.jsonSchema)}`)].join(`
137
+ `)},Ry=async(e)=>{let t=e.source??await Ts(e.sourceRoot),r=ks(t).find((n)=>n.name===e.datasetName);return r===void 0?[]:r.fields.map((n)=>({name:n.name,jsonSchema:n.jsonSchema}))},xy=(e)=>`${e.name} (${e.id})`,Cy=async(e,t)=>{let r=[];for await(let n of e.datasets.listAll({projectId:t}))r.push(n);return r.toSorted((n,i)=>{let s=n.name.localeCompare(i.name);return s===0?n.id.localeCompare(i.id):s})},wd=async(e,t,r)=>{let n=await Ee(t.sourceRoot),i=t.projectId??n?.projectId;_(i,X);let s=t.datasetName,o=await Cy(e,i),a=(u)=>o.filter((f)=>f.name===u).length<=1,l=FT(s),d=o.find((u)=>u.id===s||u.id.toLowerCase()===l);if(d!==void 0)return{datasetId:d.id,name:d.name,nameIsUnique:a(d.name)};let c=o.filter((u)=>u.name===s);if(_(c.length<=1,`Project ${i} has multiple datasets named "${s}": ${c.map(xy).join(", ")}.`),c.length===1){let[u]=c;return _(u,`Dataset "${s}" has no resolved ID.`),{datasetId:u.id,name:u.name,nameIsUnique:!0}}let p=n?.projectId===i?n.datasets[s]:void 0;if(p!==void 0){let u=o.find((f)=>f.id===p.datasetId);if(u!==void 0)return{datasetId:u.id,name:u.name,nameIsUnique:a(u.name)}}_(r&&l===void 0,o.length===0?`Dataset "${s}" does not exist in project ${i}. Run toloka apply first.`:`Dataset "${s}" does not exist in project ${i}. This project has: ${o.map(xy).join(", ")}.`),_((await Ry(t)).length>0,`Dataset "${s}" does not exist in project ${i} 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 h=await e.datasets.create({projectId:i,name:s});return{datasetId:h.id,name:h.name,nameIsUnique:!0}},kT=(e)=>{let t=e.toLowerCase();if(t.endsWith(".json"))return"json";if(t.endsWith(".jsonl"))return"jsonl";if(t.endsWith(".csv"))return"csv";_(!1,`${e} must have a .json, .jsonl, or .csv extension`)},DT=async(e)=>{let t=Yn.basename(e),r=kT(t),n=await Br.readFile(e,"utf8");if(r==="jsonl")for(let{line:i,lineNumber:s}of n.split(/\r?\n/u).map((o,a)=>({line:o,lineNumber:a+1})).filter(({line:o})=>o.length>0)){let o;try{o=JSON.parse(i)}catch{_(!1,`${t}:${s} is not valid JSON`)}_(vd(o),`${t}:${s} must contain a JSON object`)}return{payload:n,format:r,contentType:TT[r]}},Ns=async(e,t,r)=>{let n=r instanceof Error?r.message:String(r);try{await e.datasets.cancelUpload({uploadId:t})}catch(i){let s=i instanceof Error?i.message:String(i);throw AggregateError([r,i],`Dataset upload ${t} failed and could not be canceled. Upload error: ${n}. Cancellation error: ${s}.`)}throw new Ms(`Dataset upload ${t} failed and was canceled: ${n}`,r)},NT=async({client:e,started:t,payload:r,contentType:n,fetch:i,retryIntervalMs:s})=>{let o;try{o=await i(t.uploadUrl,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:r})}catch(l){return Ns(e,t.job.id,l)}if(!o.ok)return Ns(e,t.job.id,new Ms(`Dataset upload failed with HTTP ${o.status}.`,void 0));let a=0;while(!0)try{await e.datasets.finalizeUpload({uploadId:t.job.id});return}catch(l){if(!(l instanceof te&&l.status===503))return Ns(e,t.job.id,l);if(a+=1,a===Sy)return Ns(e,t.job.id,new Ms(`Storage remained unavailable after ${Sy} finalization attempts.`,l));let{promise:d,resolve:c}=Promise.withResolvers();setTimeout(c,s),await d}};async function Oy(e,t){let{payload:r,format:n,contentType:i}=await DT(t.filePath),s=await wd(e,t,!0),o=s.datasetId,a=new Map;for await(let y of e.datasets.listAllFields({datasetId:o})){if(y.internal||y.name===jy)continue;a.set(y.name,{name:y.name,jsonSchema:y.jsonSchema})}for(let y of await Ry({...t,datasetName:s.name}))if(!a.has(y.name))a.set(y.name,y);let l=[...a.values()],d=await e.datasets.startUpload({datasetId:o,filename:Yn.basename(t.filePath),format:n,declaredSizeBytes:new TextEncoder().encode(r).byteLength,fields:l});await NT({client:e,started:d,payload:r,contentType:i,fetch:t.fetch??globalThis.fetch,retryIntervalMs:t.waitFor?.intervalMs??1000});let c=await e.waitFor({type:"datasetUpload",uploadId:d.job.id},t.waitFor),p=s.nameIsUnique?s.name:s.datasetId,h=c.status==="failed"&&c.error?.startsWith("Schema incompatible with existing upload")===!0?`
138
+ Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";_(c.status==="succeeded",`${c.error??`Dataset upload ${c.id} failed.`}${h}`);let u=`Uploaded ${c.result.itemsIngested} rows to dataset ${s.name}.`,f=[],m,g;try{f=(await e.datasets.getInferredFields({datasetId:o})).fields,m=AT(f)}catch(y){g=`Upload succeeded, but inferred fields could not be fetched: ${y instanceof Error?y.message:String(y)}`}return{datasetId:o,rowsUploaded:c.result.itemsIngested,inferredFields:f,output:m===void 0?u:`${u}
139
+ ${m}`,...g===void 0?{}:{warning:g}}}async function Fy(e,t){let r=await wd(e,t,!1),n=await e.datasets.getInferredFields({datasetId:r.datasetId}),i=n.fields.filter((o)=>o.depth===1),s=Mg(i.map(({name:o,jsonSchema:a})=>({name:o,jsonSchema:a})));return{datasetId:r.datasetId,inferredFields:n.fields,declarations:s,output:i.length===0?`Dataset ${r.name} has no inferred fields yet.`:s}}async function Ty(e,t){let r=await Cy(e,t.projectId);if(r.length===0)return{output:"This project has no datasets."};return{output:r.map((n)=>`${n.name} ${n.id}`).join(`
140
+ `)}}var MT=async(e)=>{let t=await e.fetch(e.downloadUrl);_(t.ok,`Dataset export download failed with HTTP ${t.status}.`);let r=await t.text(),n;try{n=JSON.parse(r)}catch(s){throw Error(`Dataset export ${e.exportId} is not valid JSON.`,{cause:s})}_(Array.isArray(n),`Dataset export ${e.exportId} is not a JSON array.`);let i=[];for(let[s,o]of n.entries())_(vd(o),`Dataset export ${e.exportId} row ${s} is not a JSON object.`),i.push(o);return i};async function Ay(e,t){let r=await wd(e,t,!1),n=[];for await(let l of e.datasets.listAllFields({datasetId:r.datasetId})){if(l.internal||l.name===jy)continue;n.push(l.name)}_(n.length>0,`Dataset ${r.name} has no fields to export.`);let i=await e.datasets.startExport({datasetId:r.datasetId,fields:n}),s;try{s=await e.waitFor({type:"datasetExport",exportId:i.id},t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs})}catch(l){throw _(!(l instanceof te&&l.code==="wait_timeout"),`Stopped waiting for dataset export ${i.id}; raise --timeout to wait longer.`),l}_(s.result.downloadUrl,`Dataset export ${s.id} succeeded without a download URL.`);let o=await MT({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 Br.mkdir(Yn.dirname(t.outPath),{recursive:!0}),await Br.writeFile(t.outPath,a.length===0?"":`${a.map((l)=>JSON.stringify(l)).join(`
141
141
  `)}
142
- `),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function by(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 iT=["emacs","vim"],nT=new Set(iT);function sT(e){return nT.has(e)}function Py(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(sT)))}var Qi=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",As=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var yc=(e)=>e.name==="backspace";var _c=(e)=>"1234567890".includes(e.name),bc=(e)=>e.name==="enter"||e.name==="return";class Pc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class vc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Ds extends Error{name="ExitPromptError"}class wc extends Error{name="HookError"}class Yi extends Error{name="ValidationError"}var Ey=require("async_hooks");var Ns=require("async_hooks");var vy=new Ns.AsyncLocalStorage;function oT(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function wy(e,t){let r=oT(e);return vy.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function er(){let e=vy.getStore();if(!e)throw new wc("[Inquirer] Hook functions can only be called from within a prompt");return e}function $c(){return er().rl}function Ec(e){let t=(...r)=>{let i=er(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Ns.AsyncResource.bind(t)}function Gr(e){let t=er(),{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 $y(){er().handleChange()}var tr={queue(e){let t=er(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e($c());if(i!=null&&typeof i!=="function")throw new Yi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=er();Ec(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=er();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function aT(e){return typeof e==="function"}function st(e){return Gr((t)=>{let r=Ey.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),$y()});if(t.initialized)return[t.get(),r];let i=aT(e)?e():e;return t.set(i),[i,r]})}function rr(e,t){Gr((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))tr.queue(e);r.set(t)})}var Ne=require("util");var De=Ce(require("process"));function lT(){if(!De.default.platform.startsWith("win"))return De.default.env.TERM!=="linux";return Boolean(De.default.env.CI)||Boolean(De.default.env.WT_SESSION)||Boolean(De.default.env.TERMINUS_SUBLIME)||De.default.env.ConEmuTask==="{cmd::Cmder}"||De.default.env.TERM_PROGRAM==="Terminus-Sublime"||De.default.env.TERM_PROGRAM==="vscode"||De.default.env.TERM==="xterm-256color"||De.default.env.TERM==="alacritty"||De.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Iy={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"},Sy={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"},cT={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"},dT={...Iy,...Sy},uT={...Iy,...cT},pT=lT(),fT=pT?dT:uT,Vr=fT,jU=Object.entries(Sy);var mT={prefix:{idle:Ne.styleText("blue","?"),done:Ne.styleText("green",Vr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>Ne.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>Ne.styleText("cyan",e),message:(e)=>Ne.styleText("bold",e),error:(e)=>Ne.styleText("red",`> ${e}`),defaultAnswer:(e)=>Ne.styleText("dim",`(${e})`),help:(e)=>Ne.styleText("dim",e),highlight:(e)=>Ne.styleText("cyan",e),key:(e)=>Ne.styleText("cyan",Ne.styleText("bold",`<${e}>`))}};function xy(){return{...mT,keybindings:Py()}}function Ry(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 Cy(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Ry(s)&&Ry(n)?Cy(s,n):n}return t}function Xi(...e){let t=[xy(),...e.filter((r)=>r!=null)];return Cy(...t)}function Ic({status:e="idle",theme:t}){let[r,i]=st(!1),[n,s]=st(0),{prefix:o,spinner:a}=Xi(t);if(rr(()=>{if(e==="loading"){let u,l=-1,c=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(c),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Zi(e,t){return Gr((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 ir(e){return st({current:e})[0]}function Sc(e){let t=ir(e);t.current=e,rr((r)=>{let i=!1,n=Ec((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var Wy=Ce(jy(),1);var Fy=(()=>{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,ky=(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 yT=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,_T=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ay=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,bT=/\t{1,1000}/y,Dy=/[\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,PT=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,vT=/\p{M}+/gu,wT={limit:1/0,ellipsis:""},Ny=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?Ny(n,wT,r).width:0),o=0,a=r.controlWidth??0,d=r.tabWidth??8,u=r.emojiWidth??2,l=2,c=r.regularWidth??1,p=r.wideWidth??2,f=[[PT,c],[yT,0],[_T,a],[bT,d],[Dy,u],[Ay,p]],m=0,h=0,g=e.length,_=0,b=!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);_=0;for(let V of R.replaceAll(vT,"")){let J=V.codePointAt(0)||0;if(Ty(J))T=2;else if(ky(J))T=p;else T=c;if(x+T>w)v=Math.min(v,Math.max(I,m)+_);if(x+T>i){b=!0;break e}_+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,Z]=f[R];if(J.lastIndex=h,J.test(e)){if(_=J===Ay?Fy(e.slice(h,J.lastIndex)):J===Dy?1:J.lastIndex-h,T=_*Z,x+T>w)v=Math.min(v,h+Math.floor((w-x)/Z));if(x+T>i){b=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:b?w:x,index:b?v:g,truncated:b,ellipsed:b&&i>=s}},Ly=Ny;var $T={limit:1/0,ellipsis:"",ellipsisWidth:0},ET=(e,t={})=>Ly(e,$T,t).width,_t=ET;var Ls="\x1B",Gy="\x9B",IT=39,Rc="\x07",Vy="[",ST="]",Ky="m",Cc=`${ST}8;;`,qy=new RegExp(`(?:\\${Vy}(?<code>\\d+)m|\\${Cc}(?<uri>.*)${Rc})`,"y"),My=(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},Uy=(e)=>`${Ls}${Vy}${e}${Ky}`,By=(e)=>`${Ls}${Cc}${e}${Rc}`,xc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:_t(o),d=i.next(),u=i.next(),l=0;while(!d.done){let c=d.value,p=_t(c);if(a+p<=r)e[e.length-1]+=c;else e.push(c),a=0;if(c===Ls||c===Gy)n=!0,s=t.startsWith(Cc,l+1);if(n){if(s){if(c===Rc)n=!1,s=!1}else if(c===Ky)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;d=u,u=i.next(),l+=c.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},xT=(e)=>{let t=e.split(" "),r=t.length;while(r){if(_t(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},RT=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],d=0;for(let c=0;c<o.length;c++){let p=o[c];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,d=_t(h)}if(c!==0){if(d>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),d=0;if(d||r.trim===!1)a[a.length-1]+=" ",d++}let f=_t(p);if(r.hard&&f>t){let m=t-d,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");xc(a,p,t),d=_t(a.at(-1)??"");continue}if(d+f>t&&d&&f){if(r.wordWrap===!1&&d<t){xc(a,p,t),d=_t(a.at(-1)??"");continue}a.push(""),d=0}if(d+f>t&&r.wordWrap===!1){xc(a,p,t),d=_t(a.at(-1)??"");continue}a[a.length-1]+=p,d+=f}if(r.trim!==!1)a=a.map((c)=>xT(c));let u=a.join(`
143
- `),l=!1;for(let c=0;c<u.length;c++){let p=u[c];if(i+=p,!l){if(l=p>="\uD800"&&p<="\uDBFF",l)continue}else l=!1;if(p===Ls||p===Gy){qy.lastIndex=c+1;let m=qy.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);n=h===IT?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(u[c+1]===`
144
- `){if(s)i+=By("");let f=n?My(n):void 0;if(n&&f)i+=Uy(f)}else if(p===`
145
- `){if(n&&My(n))i+=Uy(n);if(s)i+=By(s)}}return i},CT=/\r?\n/;function zy(e,t,r){return String(e).normalize().split(CT).map((i)=>RT(i,t,r)).join(`
146
- `)}function en(e,t){return e.split(`
147
- `).flatMap((r)=>zy(r,t,{trim:!1,wordWrap:!1}).split(`
148
- `).map((i)=>i.trimEnd())).join(`
149
- `)}function qs(){return Wy.default({defaultWidth:80,output:$c().output})}function OT({active:e,renderedItems:t,pageSize:r,loop:i}){let n=ir({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:o}=n.current,a=Math.floor(r/2),d=t.reduce((c,p)=>c+p.length,0),u=t.slice(0,e).reduce((c,p)=>c+p.length,0),l=u;if(d>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 c=t.slice(e).reduce((p,f)=>p+f.length,0);l=c<r-a?r-c:Math.min(u,a)}return n.current.lastPointer=l,n.current.lastActive=e,l}function Oc({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let s=qs(),o=(_)=>(_%e.length+e.length)%e.length,a=e.map((_,b)=>{if(_==null)return[];return en(r({item:_,index:b,isActive:b===t}),s).split(`
150
- `)}),d=a.reduce((_,b)=>_+b.length,0),u=(_)=>a[_]??[],l=OT({active:t,renderedItems:a,pageSize:i,loop:n}),c=u(t).slice(0,i),p=l+c.length<=i?l:i-c.length,f=Array.from({length:i});f.splice(p,c.length,...c);let m=new Set([t]),h=p+c.length,g=o(t+1);while(h<i&&!m.has(g)&&(n&&d>i?g!==t:g>t)){let b=u(g).slice(0,i-h);f.splice(h,b.length,...b),m.add(g),h+=b.length,g=o(g+1)}h=p-1,g=o(t-1);while(h>=0&&!m.has(g)&&(n&&d>i?g!==t:g<t)){let _=u(g),b=_.slice(Math.max(0,_.length-h-1));f.splice(h-b.length+1,b.length,...b),m.add(g),h-=b.length,g=o(g-1)}return f.filter((_)=>typeof _==="string").join(`
151
- `)}var o_=Ce(require("readline")),a_=require("async_hooks"),l_=Ce(Qy(),1);var nr=[];nr.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")nr.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")nr.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Ms=(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",jc=Symbol.for("signal-exit emitter"),Fc=globalThis,FT=Object.defineProperty.bind(Object);class Yy{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Fc[jc])return Fc[jc];FT(Fc,jc,{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 kc{}var TT=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class Xy extends kc{onExit(){return()=>{}}load(){}unload(){}}class Zy extends kc{#r=Tc.platform==="win32"?"SIGINT":"SIGHUP";#t=new Yy;#e;#s;#o;#n={};#i=!1;constructor(e){super();this.#e=e,this.#n={};for(let t of nr)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(!Ms(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 nr)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,nr.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(!Ms(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"&&Ms(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 Tc=globalThis.process,{onExit:e_,load:fB,unload:mB}=TT(Ms(Tc)?new Zy(Tc):new Xy);var s_=require("util");var Ac="\x1B[G",r_="\x1B[?25l",i_="\x1B[?25h",Dc=(e=1)=>e>0?`\x1B[${e}A`:"",Nc=(e=1)=>e>0?`\x1B[${e}B`:"",Lc=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},t_="\x1B[2K",qc=(e)=>e>0?(t_+Dc(1)).repeat(e-1)+t_+Ac:"";var n_=(e)=>e.split(`
152
- `).length,kT=(e)=>e.split(`
153
- `).pop()??"";class Us{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=kT(e),i=s_.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=qs();if(e=en(e,s),t=en(t,s),i.length%s===0)e+=`
142
+ `),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function ky(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 LT=["qwen3-4b","qwen3-8b","qwen3-32b","qwen3-235b"],Xn=(e)=>{let t=e.reduce((r,n)=>n.map((i,s)=>Math.max(r[s]??0,i.length)),[]);return e.map((r)=>r.map((n,i)=>n.padEnd(t[i]??n.length)).join(" ").trimEnd()).join(`
143
+ `)},er=(e,t,r,n)=>{e.stdout(t?JSON.stringify(r,null,2):n)},qT=(e)=>Xn([["ID",e.id],["Name",e.displayName],["Provider",e.provider],["Upstream model",e.upstreamModel],["Upstream revision",e.upstreamRevision]]),Dy=(e)=>Xn([["ID",e.id],["Project",e.projectId],["Name",e.name],["Base model",e.baseModelId],["Description",e.description??"-"],["Archived at",e.archivedAt??"-"],["Created at",e.createdAt],["Updated at",e.updatedAt]]),$d=(e)=>{let t=LT.find((r)=>r===e);return _(t,`Unknown base model ${e}.`),t},Id=async(e,t,r)=>{if(r.startsWith("mdl."))return e.models.get({projectId:t,modelId:r});let n=[];for await(let i of e.models.listAll({projectId:t,limit:100}))if(i.name===r)n.push(i);return _(n.length===1,`Model ${r} was not found or is ambiguous.`),n[0]},Ny=async(e,t,r)=>{let n=await e.baseModels.list();er(r,t.json,n,n.length===0?"No base models found.":Xn([["ID","NAME","PROVIDER","UPSTREAM MODEL"],...n.map((i)=>[i.id,i.displayName,i.provider,i.upstreamModel])]))},My=async(e,t,r)=>{let n=await e.baseModels.get({id:t.id});er(r,t.json,n,qT(n))},Ly=async(e,t,r)=>{let n=await e.models.listPage({projectId:t.projectId,limit:100,offset:0});er(r,t.json,n.models,n.models.length===0?"No models found.":Xn([["ID","NAME","BASE MODEL"],...n.models.map((i)=>[i.id,i.name,i.baseModelId])]))},qy=async(e,t,r)=>{let n=await Id(e,t.projectId,t.nameOrId);er(r,t.json,n,Dy(n))},Uy=async(e,t,r)=>{let n=await Id(e,t.projectId,t.nameOrId),i=[];for await(let s of e.models.listAllVersions({projectId:t.projectId,modelId:n.id,limit:100}))i.push(s);er(r,t.json,i,i.length===0?"No Model Versions found.":Xn([["VERSION","ID","CREATED AT"],...i.map((s)=>[s.version,s.id,s.createdAt])]))},By=async(e,t,r)=>{let{json:n,...i}=t,s=await e.models.create(i);er(r,n,s,Dy(s))},Gy=async(e,t,r)=>{let n=await Id(e,t.projectId,t.nameOrId),i=await e.models.archive({projectId:t.projectId,modelId:n.id});er(r,t.json,i,`Archived Model ${i.id}.`)};var UT=["emacs","vim"],BT=new Set(UT);function GT(e){return BT.has(e)}function Vy(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(GT)))}var Zn=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",Ls=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var Ed=(e)=>e.name==="backspace";var Sd=(e)=>"1234567890".includes(e.name),xd=(e)=>e.name==="enter"||e.name==="return";class jd extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class Rd extends Error{name="CancelPromptError";message="Prompt was canceled"}class qs extends Error{name="ExitPromptError"}class Cd extends Error{name="HookError"}class ei extends Error{name="ValidationError"}var Hy=require("async_hooks");var Us=require("async_hooks");var zy=new Us.AsyncLocalStorage;function VT(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Ky(e,t){let r=VT(e);return zy.run(r,()=>{function n(i){r.handleChange=()=>{r.index=0,i()},r.handleChange()}return t(n)})}function tr(){let e=zy.getStore();if(!e)throw new Cd("[Inquirer] Hook functions can only be called from within a prompt");return e}function Od(){return tr().rl}function Fd(e){let t=(...r)=>{let n=tr(),i=!1,s=n.handleChange;n.handleChange=()=>{i=!0};let o=e(...r);if(i)s();return n.handleChange=s,o};return Us.AsyncResource.bind(t)}function Gr(e){let t=tr(),{index:r}=t,n={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},i=e(n);return t.index++,i}function Wy(){tr().handleChange()}var rr={queue(e){let t=tr(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(Od());if(n!=null&&typeof n!=="function")throw new ei("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=tr();Fd(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=tr();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function zT(e){return typeof e==="function"}function ot(e){return Gr((t)=>{let r=Hy.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),Wy()});if(t.initialized)return[t.get(),r];let n=zT(e)?e():e;return t.set(n),[n,r]})}function nr(e,t){Gr((r)=>{let n=r.get();if(!Array.isArray(n)||t.some((s,o)=>!Object.is(s,n[o])))rr.queue(e);r.set(t)})}var Ne=require("util");var De=Re(require("process"));function KT(){if(!De.default.platform.startsWith("win"))return De.default.env.TERM!=="linux";return Boolean(De.default.env.CI)||Boolean(De.default.env.WT_SESSION)||Boolean(De.default.env.TERMINUS_SUBLIME)||De.default.env.ConEmuTask==="{cmd::Cmder}"||De.default.env.TERM_PROGRAM==="Terminus-Sublime"||De.default.env.TERM_PROGRAM==="vscode"||De.default.env.TERM==="xterm-256color"||De.default.env.TERM==="alacritty"||De.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Jy={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"},Qy={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"},WT={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"},HT={...Jy,...Qy},JT={...Jy,...WT},QT=KT(),YT=QT?HT:JT,Vr=YT,yB=Object.entries(Qy);var XT={prefix:{idle:Ne.styleText("blue","?"),done:Ne.styleText("green",Vr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>Ne.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>Ne.styleText("cyan",e),message:(e)=>Ne.styleText("bold",e),error:(e)=>Ne.styleText("red",`> ${e}`),defaultAnswer:(e)=>Ne.styleText("dim",`(${e})`),help:(e)=>Ne.styleText("dim",e),highlight:(e)=>Ne.styleText("cyan",e),key:(e)=>Ne.styleText("cyan",Ne.styleText("bold",`<${e}>`))}};function Yy(){return{...XT,keybindings:Vy()}}function Xy(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 Zy(...e){let t={};for(let r of e)for(let[n,i]of Object.entries(r)){let s=t[n];t[n]=Xy(s)&&Xy(i)?Zy(s,i):i}return t}function ti(...e){let t=[Yy(),...e.filter((r)=>r!=null)];return Zy(...t)}function Td({status:e="idle",theme:t}){let[r,n]=ot(!1),[i,s]=ot(0),{prefix:o,spinner:a}=ti(t);if(nr(()=>{if(e==="loading"){let d,c=-1,p=setTimeout(()=>{n(!0),d=setInterval(()=>{c=c+1,s(c%a.frames.length)},a.interval)},300);return()=>{clearTimeout(p),clearInterval(d)}}else n(!1)},[e]),r)return a.frames[i];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function ri(e,t){return Gr((r)=>{let n=r.get();if(!n||n.dependencies.length!==t.length||n.dependencies.some((i,s)=>i!==t[s])){let i=e();return r.set({value:i,dependencies:t}),i}return n.value})}function ir(e){return ot({current:e})[0]}function Ad(e){let t=ir(e);t.current=e,nr((r)=>{let n=!1,i=Fd((s,o)=>{if(n)return;t.current(o,r)});return r.input.on("keypress",i),()=>{n=!0,r.input.removeListener("keypress",i)}},[])}var y_=Re(t_(),1);var r_=(()=>{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}})(),n_=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,i_=(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 tA=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,rA=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,s_=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,nA=/\t{1,1000}/y,o_=/[\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,iA=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,sA=/\p{M}+/gu,oA={limit:1/0,ellipsis:""},a_=(e,t={},r={})=>{let n=t.limit??1/0,i=t.ellipsis??"",s=t?.ellipsisWidth??(i?a_(i,oA,r).width:0),o=0,a=r.controlWidth??0,l=r.tabWidth??8,d=r.emojiWidth??2,c=2,p=r.regularWidth??1,h=r.wideWidth??2,u=[[iA,p],[tA,0],[rA,a],[nA,l],[o_,d],[s_,h]],f=0,m=0,g=e.length,y=0,b=!1,v=g,I=Math.max(0,n-s),E=0,w=0,x=0,T=0;e:while(!0){if(w>E||m>=g&&m>f){let R=e.slice(E,w)||e.slice(f,m);y=0;for(let V of R.replaceAll(sA,"")){let Q=V.codePointAt(0)||0;if(n_(Q))T=2;else if(i_(Q))T=h;else T=p;if(x+T>I)v=Math.min(v,Math.max(E,f)+y);if(x+T>n){b=!0;break e}y+=V.length,x+=T}E=w=0}if(m>=g)break e;for(let R=0,V=u.length;R<V;R++){let[Q,ee]=u[R];if(Q.lastIndex=m,Q.test(e)){if(y=Q===s_?r_(e.slice(m,Q.lastIndex)):Q===o_?1:Q.lastIndex-m,T=y*ee,x+T>I)v=Math.min(v,m+Math.floor((I-x)/ee));if(x+T>n){b=!0;break e}x+=T,E=f,w=m,m=f=Q.lastIndex;continue e}}m+=1}return{width:b?I:x,index:b?v:g,truncated:b,ellipsed:b&&n>=s}},l_=a_;var aA={limit:1/0,ellipsis:"",ellipsisWidth:0},lA=(e,t={})=>l_(e,aA,t).width,bt=lA;var Bs="\x1B",f_="\x9B",dA=39,Dd="\x07",m_="[",cA="]",h_="m",Nd=`${cA}8;;`,d_=new RegExp(`(?:\\${m_}(?<code>\\d+)m|\\${Nd}(?<uri>.*)${Dd})`,"y"),c_=(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},u_=(e)=>`${Bs}${m_}${e}${h_}`,p_=(e)=>`${Bs}${Nd}${e}${Dd}`,kd=(e,t,r)=>{let n=t[Symbol.iterator](),i=!1,s=!1,o=e.at(-1),a=o===void 0?0:bt(o),l=n.next(),d=n.next(),c=0;while(!l.done){let p=l.value,h=bt(p);if(a+h<=r)e[e.length-1]+=p;else e.push(p),a=0;if(p===Bs||p===f_)i=!0,s=t.startsWith(Nd,c+1);if(i){if(s){if(p===Dd)i=!1,s=!1}else if(p===h_)i=!1}else if(a+=h,a===r&&!d.done)e.push(""),a=0;l=d,d=n.next(),c+=p.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},uA=(e)=>{let t=e.split(" "),r=t.length;while(r){if(bt(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},pA=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",i,s,o=e.split(" "),a=[""],l=0;for(let p=0;p<o.length;p++){let h=o[p];if(r.trim!==!1){let f=a.at(-1)??"",m=f.trimStart();if(f.length!==m.length)a[a.length-1]=m,l=bt(m)}if(p!==0){if(l>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),l=0;if(l||r.trim===!1)a[a.length-1]+=" ",l++}let u=bt(h);if(r.hard&&u>t){let f=t-l,m=1+Math.floor((u-f-1)/t);if(Math.floor((u-1)/t)<m)a.push("");kd(a,h,t),l=bt(a.at(-1)??"");continue}if(l+u>t&&l&&u){if(r.wordWrap===!1&&l<t){kd(a,h,t),l=bt(a.at(-1)??"");continue}a.push(""),l=0}if(l+u>t&&r.wordWrap===!1){kd(a,h,t),l=bt(a.at(-1)??"");continue}a[a.length-1]+=h,l+=u}if(r.trim!==!1)a=a.map((p)=>uA(p));let d=a.join(`
144
+ `),c=!1;for(let p=0;p<d.length;p++){let h=d[p];if(n+=h,!c){if(c=h>="\uD800"&&h<="\uDBFF",c)continue}else c=!1;if(h===Bs||h===f_){d_.lastIndex=p+1;let f=d_.exec(d)?.groups;if(f?.code!==void 0){let m=Number.parseFloat(f.code);i=m===dA?void 0:m}else if(f?.uri!==void 0)s=f.uri.length===0?void 0:f.uri}if(d[p+1]===`
145
+ `){if(s)n+=p_("");let u=i?c_(i):void 0;if(i&&u)n+=u_(u)}else if(h===`
146
+ `){if(i&&c_(i))n+=u_(i);if(s)n+=p_(s)}}return n},fA=/\r?\n/;function g_(e,t,r){return String(e).normalize().split(fA).map((n)=>pA(n,t,r)).join(`
147
+ `)}function ni(e,t){return e.split(`
148
+ `).flatMap((r)=>g_(r,t,{trim:!1,wordWrap:!1}).split(`
149
+ `).map((n)=>n.trimEnd())).join(`
150
+ `)}function Gs(){return y_.default({defaultWidth:80,output:Od().output})}function mA({active:e,renderedItems:t,pageSize:r,loop:n}){let i=ir({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:o}=i.current,a=Math.floor(r/2),l=t.reduce((p,h)=>p+h.length,0),d=t.slice(0,e).reduce((p,h)=>p+h.length,0),c=d;if(l>r)if(n){if(c=s,o!=null&&o<e&&e-o<r)c=Math.min(a,Math.abs(e-o)===1?Math.min(s+(t[o]?.length??0),Math.max(d,s)):s+e-o)}else{let p=t.slice(e).reduce((h,u)=>h+u.length,0);c=p<r-a?r-p:Math.min(d,a)}return i.current.lastPointer=c,i.current.lastActive=e,c}function Md({items:e,active:t,renderItem:r,pageSize:n,loop:i=!0}){let s=Gs(),o=(y)=>(y%e.length+e.length)%e.length,a=e.map((y,b)=>{if(y==null)return[];return ni(r({item:y,index:b,isActive:b===t}),s).split(`
151
+ `)}),l=a.reduce((y,b)=>y+b.length,0),d=(y)=>a[y]??[],c=mA({active:t,renderedItems:a,pageSize:n,loop:i}),p=d(t).slice(0,n),h=c+p.length<=n?c:n-p.length,u=Array.from({length:n});u.splice(h,p.length,...p);let f=new Set([t]),m=h+p.length,g=o(t+1);while(m<n&&!f.has(g)&&(i&&l>n?g!==t:g>t)){let b=d(g).slice(0,n-m);u.splice(m,b.length,...b),f.add(g),m+=b.length,g=o(g+1)}m=h-1,g=o(t-1);while(m>=0&&!f.has(g)&&(i&&l>n?g!==t:g<t)){let y=d(g),b=y.slice(Math.max(0,y.length-m-1));u.splice(m-b.length+1,b.length,...b),f.add(g),m-=b.length,g=o(g-1)}return u.filter((y)=>typeof y==="string").join(`
152
+ `)}var C_=Re(require("readline")),O_=require("async_hooks"),F_=Re(P_(),1);var sr=[];sr.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")sr.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")sr.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Vs=(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",Ld=Symbol.for("signal-exit emitter"),qd=globalThis,gA=Object.defineProperty.bind(Object);class v_{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(qd[Ld])return qd[Ld];gA(qd,Ld,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],n=r.indexOf(t);if(n===-1)return;if(n===0&&r.length===1)r.length=0;else r.splice(n,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let i of this.listeners[e])n=i(t,r)===!0||n;if(e==="exit")n=this.emit("afterExit",t,r)||n;return n}}class Bd{}var yA=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class w_ extends Bd{onExit(){return()=>{}}load(){}unload(){}}class $_ extends Bd{#r=Ud.platform==="win32"?"SIGINT":"SIGHUP";#t=new v_;#e;#s;#o;#i={};#n=!1;constructor(e){super();this.#e=e,this.#i={};for(let t of sr)this.#i[t]=()=>{let r=this.#e.listeners(t),{count:n}=this.#t,i=e;if(typeof i.__signal_exit_emitter__==="object"&&typeof i.__signal_exit_emitter__.count==="number")n+=i.__signal_exit_emitter__.count;if(r.length===n){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(!Vs(this.#e))return()=>{};if(this.#n===!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.#n)return;this.#n=!0,this.#t.count+=1;for(let e of sr)try{let t=this.#i[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.#n)return;this.#n=!1,sr.forEach((e)=>{let t=this.#i[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(!Vs(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"&&Vs(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let n=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),n}else return r.call(this.#e,e,...t)}}var Ud=globalThis.process,{onExit:I_,load:ZB,unload:e2}=yA(Vs(Ud)?new $_(Ud):new w_);var R_=require("util");var Gd="\x1B[G",S_="\x1B[?25l",x_="\x1B[?25h",Vd=(e=1)=>e>0?`\x1B[${e}A`:"",zd=(e=1)=>e>0?`\x1B[${e}B`:"",Kd=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},E_="\x1B[2K",Wd=(e)=>e>0?(E_+Vd(1)).repeat(e-1)+E_+Gd:"";var j_=(e)=>e.split(`
153
+ `).length,_A=(e)=>e.split(`
154
+ `).pop()??"";class zs{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=_A(e),n=R_.stripVTControlCharacters(r),i=n;if(this.rl.line.length>0)i=i.slice(0,-this.rl.line.length);this.rl.setPrompt(i),this.cursorPos=this.rl.getCursorPos();let s=Gs();if(e=ni(e,s),t=ni(t,s),n.length%s===0)e+=`
154
155
  `;let o=e+(t?`
155
- `+t:""),d=Math.floor(i.length/s)-this.cursorPos.rows+(t?n_(t):0);if(d>0)o+=Dc(d);o+=Lc(this.cursorPos.cols),this.write(Nc(this.extraLinesUnderPrompt)+qc(this.height)+o),this.extraLinesUnderPrompt=d,this.height=n_(o)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write(Lc(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=Nc(this.extraLinesUnderPrompt);t+=e?qc(this.height):`
156
- `,t+=Ac,t+=i_,this.write(t),this.rl.close()}}class Mc extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,n)=>{e=i,t=n}),resolve:e,reject:t}}}var c_=Ce(require("path")),AT=globalThis.setImmediate;function DT(){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 Uc(e){let t=DT();return(i,n={})=>{let{input:s=process.stdin,signal:o}=n,a=new Set,d=new l_.default;d.pipe(n.output??process.stdout);let u=o_.createInterface({terminal:!0,input:s,output:d});d.mute();let l=new Us(u),{promise:c,resolve:p,reject:f}=Mc.withResolver(),m=()=>f(new vc);if(o){let g=()=>f(new Pc({cause:o.reason}));if(o.aborted)return g(),Object.assign(c,{cancel:m});o.addEventListener("abort",g),a.add(()=>o.removeEventListener("abort",g))}a.add(e_((g,_)=>{f(new Ds(`User force closed the prompt with ${g} ${_}`))}));let h=()=>f(new Ds("User force closed the prompt with SIGINT"));return u.on("SIGINT",h),a.add(()=>u.removeListener("SIGINT",h)),wy(u,(g)=>{let _=a_.AsyncResource.bind(()=>tr.clearAll());u.on("close",_),a.add(()=>u.removeListener("close",_));let b=()=>{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=c_.default.resolve(R);throw Error(`Prompt functions must return a string.
157
- at ${R}`)}let[x,T]=typeof E==="string"?[E]:E;l.render(x,T),tr.run()}catch(E){f(E)}if(I=!0,w!==null){let{value:E}=w;w=null,p(E)}})};if("readableFlowing"in s)AT(b);else b();return Object.assign(c.then((v)=>(tr.clearAll(),v),(v)=>{throw tr.clearAll(),v}).finally(()=>{a.forEach((v)=>v()),l.done({clearContent:Boolean(n.clearPromptOnDone)}),d.end()}).then(()=>c),{cancel:m})})}}var d_=require("util");class ot{separator=d_.styleText("dim",Array.from({length:15}).join(Vr.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 Kr=require("util");var NT={icon:{cursor:Vr.pointer},style:{disabled:(e)=>Kr.styleText("dim",e),description:(e)=>Kr.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Kr.styleText("bold",t)} ${Kr.styleText("dim",r)}`).join(Kr.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function Bc(e){return!ot.isSeparator(e)&&!e.disabled}function Gc(e){return!ot.isSeparator(e)}function LT(e){return e.map((t)=>{if(ot.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 u_=Uc((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=Xi(NT,e.theme),{keybindings:s}=n,[o,a]=st("idle"),d=Ic({status:o,theme:n}),u=ir(),l=!s.includes("vim"),c=Zi(()=>LT(e.choices),[e.choices]),p=Zi(()=>{let R=c.findIndex(Gc),V=c.findLastIndex(Gc);if(R===-1)throw new Yi("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:V}},[c]),f=Zi(()=>{if(!("default"in e))return-1;return c.findIndex((R)=>Bc(R)&&R.value===e.default)},[e.default,c]),[m,h]=st(f===-1?p.first:f),g=c[m];if(g==null||ot.isSeparator(g))throw Error("Active index does not point to a choice");let[_,b]=st();Sc((R,V)=>{if(clearTimeout(u.current),_)b(void 0);if(bc(R))if(g.disabled)b(n.i18n.disabledError);else a("done"),t(g.value);else if(Qi(R,s)||As(R,s)){if(V.clearLine(0),r||Qi(R,s)&&m!==p.first||As(R,s)&&m!==p.last){let J=Qi(R,s)?-1:1,Z=m;do Z=(Z+J+c.length)%c.length;while(!Gc(c[Z]));h(Z)}}else if(_c(R)&&!Number.isNaN(Number(V.line))){let J=Number(V.line)-1,Z=-1,Re=c.findIndex((Jr)=>{if(ot.isSeparator(Jr))return!1;return Z++,Z===J}),Hr=c[Re];if(Hr!=null&&Bc(Hr))h(Re);u.current=setTimeout(()=>{V.clearLine(0)},700)}else if(yc(R))V.clearLine(0);else if(l){let J=V.line.toLowerCase(),Z=c.findIndex((Re)=>{if(ot.isSeparator(Re)||!Bc(Re))return!1;return Re.name.toLowerCase().startsWith(J)});if(Z!==-1)h(Z);u.current=setTimeout(()=>{V.clearLine(0)},700)}}),rr(()=>()=>{clearTimeout(u.current)},[]);let v=n.style.message(e.message,o),w=n.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),I=0,E=Oc({items:c,active:m,renderItem({item:R,isActive:V,index:J}){if(ot.isSeparator(R))return I++,` ${R.separator}`;let Z=V?n.icon.cursor:" ",Re=n.indexMode==="number"?`${J+1-I}. `:"";if(R.disabled){let Jr=typeof R.disabled==="string"?R.disabled:"(disabled)",j_=V?n.icon.cursor:"-";return n.style.disabled(`${j_} ${Re}${R.name} ${Jr}`)}return(V?n.style.highlight:(Jr)=>Jr)(`${Z} ${Re}${R.name}`)},pageSize:i,loop:r});if(o==="done")return[d,v,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:x}=g;return`${[[d,v].filter(Boolean).join(" "),E," ",x?n.style.description(x):"",_?n.style.error(_):"",w].filter(Boolean).join(`
158
- `).trimEnd()}${r_}`});var qT="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",MT=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},UT=(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},BT=(e,t)=>{let r=t.get(e.id);return{pipelineId:e.id,name:e.name,...r===void 0?{}:{sourceDirectory:r}}},zr=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,GT=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(zr).join(", ")}.`;async function f_(e){return u_({message:"This project tracks several pipelines. Select one",choices:e})}async function m_(e){let t=await h_(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(`
159
- `)}}var h_=async(e,t,r)=>{let i=await MT(e.pipelines.listAll({projectId:t})),n=UT(t,r);return i.map((s)=>BT(s,n)).toSorted((s,o)=>{let a=s.name.localeCompare(o.name);return a===0?s.pipelineId.localeCompare(o.pipelineId):a})},Bs=(e,t,r)=>{if(y(e.length<=1,t),e.length!==1)return;let[i]=e;return y(i,r),i},p_=(e,t)=>{let r=GT(t),i=Bs(t.filter((u)=>u.pipelineId===e),r,r);if(i!==void 0)return i;let n=t.filter((u)=>u.name===e),s=Bs(n,`Multiple pipelines are named ${e}: ${n.map(zr).join(", ")}.`,r);if(s!==void 0)return s;let o=Bs(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}),d=Bs(a,`Multiple pipelines match ${e}: ${a.map(zr).join(", ")}.`,r);if(d!==void 0)return d;y(!1,r)};async function tn(e){let t=await h_(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return p_(e.pipeline,t);if(y(t.length>0,"This project has no pipelines."),t.length>1&&e.select!==void 0){let r=await e.select(t.map((i)=>({name:zr(i),value:i.pipelineId})));return p_(r,t)}if(t.length===1){let[r]=t;y(r,"This project has no pipelines."),y(!1,`Pass a pipeline name. This project has: ${zr(r)}.`)}y(!1,`This project tracks several pipelines, so name one: ${t.map(zr).join(", ")}.`)}var g_=(e)=>`run ${e.id} is ${e.status}`,y_=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function __(e,t){let r=await tn({client:e,...t}),i=await e.runs.start({pipelineId:r.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${g_(i)} for ${r.name}.`,`Follow it with toloka pipeline status ${r.pipelineId}, or re-run with --wait.`].join(`
160
- `)};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=y_(n);return{outcome:s,output:s==="failed"?[`Run ${n.id} failed.`,`Inspect items with toloka pipeline results ${n.id} --failed.`].join(`
161
- `):`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(`
162
- `)};throw n}}async function b_(e,t){let r=await tn({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(`
163
- `)}}async function P_(e,t){let r=await tn({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,d=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),d+=1,d>=o)break;let u=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([l],[c])=>l.localeCompare(c)).map(([l,c])=>` ${l.padEnd(12)} ${c}`);return{outcome:y_(s),output:[`Latest ${g_(s)} (started ${n.createdAt}).`,d>=o?`Items (first ${o}):`:"Items:",...u].join(`
164
- `)}}async function v_(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 VT=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
165
- ${qT}`;return e.state.error===null?t:`${t}
166
- ${e.state.error}`};async function w_(e,t){let r=t.limit??20,i=t.itemScanLimit??Math.max(500,r),n=[],s=0;for await(let d of e.runs.listAllItems({runId:t.runId})){if(s+=1,t.failedOnly!==!0||d.state.status==="failed")n.push(d);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(VT)].join(`
167
- `)}}var $_=(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},KT=(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(" "))},E_=(e,t)=>{let i=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let n of e.subLines??[])if($_(n))i.push(...E_(n,t+1));return i},zT=(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($_(n))t.push(...E_(n,1));continue}r.push(i.kind==="validation-errors"?` ${i.nodeNameDisplay} skipped (validation errors)`:` ${i.nodeNameDisplay} not billed`)}return{billed:t,unpriced:r}},WT=(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},HT=(e,t)=>{let{billed:r,unpriced:i}=zT(e.nodes),n=WT(e.total),s=KT([["Item","Expected","Maximum"],...r,...n]),o=s.slice(0,1+r.length),a=s.slice(1+r.length),d=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...o];if(r.length===0)d.push(" (no billed nodes)");if(d.push("",...a),i.length>0)d.push("","Not billed",...i);if(e.isInternalPricing===!0)d.push("","Internal-team pricing.");return d.push("",e.disclaimer),d.join(`
168
- `)};async function I_(e,t){let r=await tn({client:e,...t}),i=await e.pipelines.estimateCost({pipelineId:r.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:HT(i,r.name)}}var S_=require("crypto"),Vc=require("fs"),Gs=require("fs/promises"),We=require("path"),JT=262144,QT=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),YT=async(e,t)=>{let r=We.relative(t,e);if(r===""||r===".."||r.startsWith(`..${We.sep}`)||We.isAbsolute(r))return;let i=r.split(We.sep);for(let n=1;n<i.length;n+=1){let s=We.join(t,...i.slice(0,n)),o=await Gs.lstat(s);y(!o.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${s}; select a path that does not traverse symbolic links.`)}},XT=async(e,t,r)=>{let i=We.resolve(r,e);await YT(i,t);let n;try{n=await Gs.open(i,Vc.constants.O_RDONLY|Vc.constants.O_NOFOLLOW)}catch(s){throw y(!(s instanceof Error&&("code"in s)&&s.code==="ELOOP"),`Report file ${i} is a symbolic link; select the file it points to directly.`),s}try{let s=await n.stat();return y(s.isFile(),`Report file ${i} is not a regular file.`),y(s.size>0,`Report file ${i} is empty.`),y(s.size<=JT,`Report file ${i} is ${s.size} bytes; the limit is 256 KiB.`),{handle:n,absolutePath:i,size:s.size}}catch(s){throw await n.close(),s}},ZT=async(e,t,r)=>{let i=await XT(e,t,r);try{let n=await i.handle.readFile();y(n.byteLength===i.size,`${i.absolutePath} changed while it was being read.`);try{return QT.decode(n)}catch{throw Error(`Report file ${i.absolutePath} is not valid UTF-8.`)}}finally{await i.handle.close()}},ek=async(e,t)=>{if(t)return!0;if(e.prompt===void 0)return!1;let r=(await e.prompt("Send this report to Toloka? [y/N] ")).trim().toLowerCase();return r==="y"||r==="yes"};async function x_(e){let{analytics:t,io:r}=e;y(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.");let i=await ZT(e.path,e.sourceRoot,e.cwd);if(r.stdout("Issue report preview:"),r.stdout(""),r.stdout(i.replace(/(?![\t\n])(?!\r\n)(?:\p{Cc}|\p{Bidi_Control})/gu,(s)=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`)),r.stdout(""),r.stdout(`Authored by: ${e.authoredBy}`),r.stdout(`Platform: ${e.platform}`),r.stdout(""),!await ek(r,e.confirm))return r.stderr("Refusing to submit without confirmation in a non-interactive environment. Pass --confirm after reviewing the preview above."),1;let n=S_.randomUUID();return await t.submitIssueReport({reportId:n,reportText:i,authoredBy:e.authoredBy,platform:e.platform}),r.stdout(`Submitted issue report: ${n}`),0}var tk=["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 ${Vt}.`].join(`
169
- `),rk=(e)=>{if(e!=="human"&&e!=="agent")throw new lt('Expected "human" or "agent".');return e},Wr=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new lt("Expected a positive integer.");return t},Kc=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},kt=async(e,t)=>{if(e.sourceRoot!==void 0)return nn.resolve(e.sourceRoot);let r=process.cwd(),i=await ry(r);if(i===void 0||i===r)return r;return t.stderr(`Using project root ${i} (found from ${r}).`),i},R_=(e)=>e.sourceRoot===void 0?process.cwd():nn.resolve(e.sourceRoot),Wc=async(e,t)=>{let{found:r,warning:i}=await Si(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(i!==void 0)t.io.stderr(i);return r?.credentials},rn=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},X=async(e,t)=>{let r=await kt(e,t.io),i=await Ie(r),n=await Wc(e,t),s=ul(e,i,t.environment,n),o=t.injectedClient??ct({apiKey:s.apiKey,baseUrl:s.baseUrl});return await rn(o,t.analytics),{sourceRoot:r,client:o,baseUrl:s.baseUrl,state:i,stored:n,...s.projectId===void 0?{}:{projectId:s.projectId}}},zc=(e,t,r,i)=>Ri({flags:e,environment:t.environment,stored:r,...i===void 0?{}:{state:i}});function ik(e){let t=new sr("toloka"),r={value:0},i=!1;t.description("Preview. Build and operate Toloka pipeline projects from TypeScript source. The public API may change.").version(Ve,"-v, --version","output the current version").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",`
170
- ${tk}`).configureOutput({writeOut:(c)=>e.io.stdout(c.replace(/\n$/u,"")),writeErr:(c)=>e.io.stderr(c.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(c,p)=>{if(i)return;let f=[];for(let g=p;g!==null;g=g.parent)f.push(g.name());if(f.includes("init")||f.includes("help")||f.includes("report")||f.includes("url")||f.includes("version"))return;let m=await kt(n(),e.io),h=await ug(m).catch(()=>{return});if(h===void 0)return;i=!0,e.io.stderr(h)}),t.command("version").description("print the current CLI version").action(()=>e.io.stdout(Ve)),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let c=await nm({...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(c.output);try{let p=await zf(e.environment);if(p===void 0)return;let f=e.injectedClient??ct(p);await rn(f,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let c=await sm(e.environment);e.io.stdout(c.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(c)=>{let p=n(),f=await Si(e.environment,p.apiKey??e.environment.POTATO_API_KEY),m=f.found?.credentials,h=await kt(p,e.io),g=await Ie(h),_=zc(p,e,m,g),b=e.injectedClient,v=await am({environment:e.environment,showToken:c.showToken,credentialLookup:f,...p.apiKey===void 0?{}:{flagApiKey:p.apiKey},...p.baseUrl===void 0?{}:{flagBaseUrl:p.baseUrl},...b===void 0?{}:{probe:()=>b},..._===void 0?{}:{project:_}});if(e.io.stdout(v.output),!v.authenticated){r.value=1;return}try{let w=ul(p,g,e.environment,m),I=e.injectedClient??ct({apiKey:w.apiKey,baseUrl:w.baseUrl});await rn(I,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 c=n(),{client:p,stored:f,state:m}=await X(c,e),h=zc(c,e,f,m);await Yf({client:p,io:e.io,...h===void 0?{}:{context:h}})}),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(c,p)=>{let f=n(),m=await Ot(e.environment),h=e.injectedClient??ct(m.credentials);await Xf({environment:e.environment,flags:f,client:h,io:e.io,afterPreflight:async()=>rn(h,e.analytics),...c===void 0?{}:{alias:c},...p===void 0?{}:{projectId:p}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(c)=>{await Zf({environment:e.environment,flags:n(),alias:c,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let c=n(),p=await Wc(c,e),f=await kt(c,e.io),m=await Ie(f);if(tm({flags:c,environment:e.environment,stored:p,...m===void 0?{}:{state:m},io:e.io}).project===void 0)r.value=1}),s.command("url").description("print the current project URL").action(async()=>{let{baseUrl:c,client:p,projectId:f}=await X(n(),e);y(f,de);let m=await p.projects.get({projectId:f}),h=new URL(`/teams/${encodeURIComponent(m.teamId)}/projects/${encodeURIComponent(m.id)}`,c);e.io.stdout(h.href)}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(c)=>{await em({environment:e.environment,flags:n(),alias:c,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(c,p)=>{let f=n(),m=await Ot(e.environment),h=e.injectedClient??ct(m.credentials),g=await kt(f,e.io);await rm({environment:e.environment,flags:f,client:h,io:e.io,sourceRoot:g,afterPreflight:async()=>rn(h,e.analytics),...c===void 0?{}:{alias:c},...p.name===void 0?{}:{name:p.name},...p.teamId===void 0?{}:{teamId:p.teamId}})}),t.command("init").description("initialize this project directory and install the agent bootstrap").action(async()=>{let c=n(),p=R_(c),f=await Wc(c,e),m=await Ie(p),h=zc(c,e,f,m),g=await dg(p,h===void 0?{}:{projectId:h.id});if(e.io.stdout(g.output),g.warning!==void 0)e.io.stderr(g.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(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=c??h;y(g,de);let _=await oy(m,{sourceRoot:f,projectId:g,...p?.force===!0?{force:!0}:{}});e.io.stdout(_.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await ay(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await dy(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});if(e.io.stdout(m.output),!m.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e),m=await cy(p,{sourceRoot:c,...f===void 0?{}:{projectId:f}});e.io.stdout(m.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(c,p)=>{let{client:f,projectId:m}=await X(n(),e);y(m,de);let h=p.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[p.fromEnv];y(h!==void 0,`Missing secret value. Set ${p.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let g=await by(f,{projectId:m,name:c,value:h});e.io.stdout(g.output)}catch{e.io.stderr(`Failed to set secret ${c}.`),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:c,projectId:p}=await X(n(),e);y(p,de);let f=await yy(c,{projectId:p});e.io.stdout(f.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(c)=>{let{sourceRoot:p,client:f,projectId:m}=await X(n(),e),h=await gy(f,{sourceRoot:p,datasetName:c,...m===void 0?{}:{projectId:m}});e.io.stdout(h.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",Wr).option("--timeout <ms>","how long to wait for the export",Wr).description("download live dataset rows into a JSONL file").action(async(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=await _y(m,{sourceRoot:f,datasetName:c,outPath:nn.resolve(p.out),...h===void 0?{}:{projectId:h},...p.limit===void 0?{}:{limit:p.limit},...p.timeout===void 0?{}:{timeoutMs:p.timeout}});e.io.stdout(g.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(c,p)=>{let{sourceRoot:f,client:m,projectId:h}=await X(n(),e),g=await hy(m,{sourceRoot:f,datasetName:c,filePath:nn.resolve(p),...h===void 0?{}:{projectId:h}});if(e.io.stdout(g.output),g.warning!==void 0)e.io.stderr(g.warning)});let d="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");u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:c,projectId:p,state:f}=await X(n(),e);y(p,de);let m=await m_({client:c,projectId:p,state:f});e.io.stdout(m.output)}),u.command("run").argument("[name]",d).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Wr).description("start a run on a deployed pipeline").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await __(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},wait:p.wait,...p.timeout===void 0?{}:{timeoutMs:p.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output),r.value=Kc(g.outcome)}),u.command("status").argument("[name]",d).description("report the latest run's state and item counts").action(async(c)=>{let{client:p,state:f,projectId:m}=await X(n(),e);y(m,de);let h=await P_(p,{projectId:m,state:f,...c===void 0?{}:{pipeline:c},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Kc(h.outcome)}),u.command("runs").argument("[name]",d).option("--limit <n>","how many runs to list",Wr).description("list recent runs").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await b_(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},...p.limit===void 0?{}:{limit:p.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output)}),u.command("cost").argument("[name]",d).option("--item-limit <n>","cap how many items to price",Wr).description("forecast what a run of this pipeline would bill").action(async(c,p)=>{let{client:f,state:m,projectId:h}=await X(n(),e);y(h,de);let g=await I_(f,{projectId:h,state:m,...c===void 0?{}:{pipeline:c},...p.itemLimit===void 0?{}:{itemLimit:p.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(g.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(c)=>{let{client:p}=await X(n(),e),f=await v_(p,{runId:c});e.io.stdout(f.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Wr).option("--failed","only report failed items",!1).description("report a run's items").action(async(c,p)=>{let{client:f}=await X(n(),e),m=await w_(f,{runId:c,failedOnly:p.failed,...p.limit===void 0?{}:{limit:p.limit}});e.io.stdout(m.output),r.value=Kc(m.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:c,client:p,projectId:f}=await X(n(),e);y(f,de);let m=await ly(p,{sourceRoot:c,projectId:f});e.io.stdout(m.output)}),t.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",rk,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(c,p)=>{y(e.analytics,"Issue reporting requires CLI analytics.");let f=R_(n()),m=n().baseUrl??e.environment.POTATO_BASE_URL??mt(e.environment)??Vt;r.value=await x_({path:c,authoredBy:p.authoredBy,platform:new URL(m).origin,confirm:p.confirm,sourceRoot:f,cwd:process.cwd(),analytics:e.analytics,io:e.io})});let l=t.command("skill").description("discover bundled agent skills and install them into .agents/skills");return l.command("list").option("--json","print Skill Descriptors with their status as JSON",!1).description("list bundled skills as not-installed, current, or stale").action(async(c)=>{let p=await kt(n(),e.io);await tg({sourceRoot:p,json:c.json,io:e.io})}),l.command("search").argument("<query>","text matched case-insensitively against id, name, description, and tags").option("--json","print matching Skill Descriptors with their status as JSON",!1).description("find bundled skills for a task").action(async(c,p)=>{let f=await kt(n(),e.io);await rg({sourceRoot:f,query:c,json:p.json,io:e.io})}),l.command("install").argument("<skillId>","skill id from toloka skill list").option("-f, --force","replace an existing .agents/skills/<skillId> directory",!1).description("copy one bundled skill into .agents/skills/<skillId>").action(async(c,p)=>{let f=await kt(n(),e.io);await ig({sourceRoot:f,skillId:c,force:p.force,io:e.io})}),{program:t,exitCode:r}}var nk=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},sk=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",d),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
171
- `)},d=()=>{a(),n(Error("Standard input closed before an API key was entered."))},u=(c)=>{a(),n(c)},l=(c)=>{for(let p of c){if(p==="\r"||p===`
172
- `){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",d),process.stdin.once("error",u);try{return await r}finally{o()}},ok=async(e,t={})=>{if(t.mask===!0)return sk(e);let r=C_.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await r.question(e)}finally{r.close()}},ak=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:nk,...process.stdin.isTTY?{prompt:ok,select:f_}:{}}),lk=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 at){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(Gi(n)),{code:1,outcome:"failed",error:n}}};async function O_(e,t=process.env,r=ak(),i,n=mg({environment:t})){let{program:s,exitCode:o}=ik({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),d=await lk(s,o,e,r);try{n.captureCommand({command:fg(e),durationMs:Date.now()-a,exitCode:d.code,outcome:d.outcome,...d.error===void 0?{}:{error:d.error}}),await n.shutdown()}catch{}return d.code}O_(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
156
+ `+t:""),l=Math.floor(n.length/s)-this.cursorPos.rows+(t?j_(t):0);if(l>0)o+=Vd(l);o+=Kd(this.cursorPos.cols),this.write(zd(this.extraLinesUnderPrompt)+Wd(this.height)+o),this.extraLinesUnderPrompt=l,this.height=j_(o)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write(Kd(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=zd(this.extraLinesUnderPrompt);t+=e?Wd(this.height):`
157
+ `,t+=Gd,t+=x_,this.write(t),this.rl.close()}}class Hd extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}}var T_=Re(require("path")),bA=globalThis.setImmediate;function PA(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,n)=>{let i=n.slice(1);return t=i,i},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function Jd(e){let t=PA();return(n,i={})=>{let{input:s=process.stdin,signal:o}=i,a=new Set,l=new F_.default;l.pipe(i.output??process.stdout);let d=C_.createInterface({terminal:!0,input:s,output:l});l.mute();let c=new zs(d),{promise:p,resolve:h,reject:u}=Hd.withResolver(),f=()=>u(new Rd);if(o){let g=()=>u(new jd({cause:o.reason}));if(o.aborted)return g(),Object.assign(p,{cancel:f});o.addEventListener("abort",g),a.add(()=>o.removeEventListener("abort",g))}a.add(I_((g,y)=>{u(new qs(`User force closed the prompt with ${g} ${y}`))}));let m=()=>u(new qs("User force closed the prompt with SIGINT"));return d.on("SIGINT",m),a.add(()=>d.removeListener("SIGINT",m)),Ky(d,(g)=>{let y=O_.AsyncResource.bind(()=>rr.clearAll());d.on("close",y),a.add(()=>d.removeListener("close",y));let b=()=>{let v=()=>c.checkCursorPos();d.input.on("keypress",v),a.add(()=>d.input.removeListener("keypress",v));let I=null;g(()=>{let E=!1;try{let w=e(n,(R)=>{if(E)h(R);else I={value:R}});if(w===void 0){let R=t[1]?.getFileName();if(R&&!R.startsWith("file://"))R=T_.default.resolve(R);throw Error(`Prompt functions must return a string.
158
+ at ${R}`)}let[x,T]=typeof w==="string"?[w]:w;c.render(x,T),rr.run()}catch(w){u(w)}if(E=!0,I!==null){let{value:w}=I;I=null,h(w)}})};if("readableFlowing"in s)bA(b);else b();return Object.assign(p.then((v)=>(rr.clearAll(),v),(v)=>{throw rr.clearAll(),v}).finally(()=>{a.forEach((v)=>v()),c.done({clearContent:Boolean(i.clearPromptOnDone)}),l.end()}).then(()=>p),{cancel:f})})}}var A_=require("util");class at{separator=A_.styleText("dim",Array.from({length:15}).join(Vr.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 zr=require("util");var vA={icon:{cursor:Vr.pointer},style:{disabled:(e)=>zr.styleText("dim",e),description:(e)=>zr.styleText("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${zr.styleText("bold",t)} ${zr.styleText("dim",r)}`).join(zr.styleText("dim"," \u2022 "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function Qd(e){return!at.isSeparator(e)&&!e.disabled}function Yd(e){return!at.isSeparator(e)}function wA(e){return e.map((t)=>{if(at.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let i=String(t);return{value:t,name:i,short:i,disabled:!1}}let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)n.description=t.description;return n})}var k_=Jd((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,i=ti(vA,e.theme),{keybindings:s}=i,[o,a]=ot("idle"),l=Td({status:o,theme:i}),d=ir(),c=!s.includes("vim"),p=ri(()=>wA(e.choices),[e.choices]),h=ri(()=>{let R=p.findIndex(Yd),V=p.findLastIndex(Yd);if(R===-1)throw new ei("[select prompt] No selectable choices. All choices are disabled.");return{first:R,last:V}},[p]),u=ri(()=>{if(!("default"in e))return-1;return p.findIndex((R)=>Qd(R)&&R.value===e.default)},[e.default,p]),[f,m]=ot(u===-1?h.first:u),g=p[f];if(g==null||at.isSeparator(g))throw Error("Active index does not point to a choice");let[y,b]=ot();Ad((R,V)=>{if(clearTimeout(d.current),y)b(void 0);if(xd(R))if(g.disabled)b(i.i18n.disabledError);else a("done"),t(g.value);else if(Zn(R,s)||Ls(R,s)){if(V.clearLine(0),r||Zn(R,s)&&f!==h.first||Ls(R,s)&&f!==h.last){let Q=Zn(R,s)?-1:1,ee=f;do ee=(ee+Q+p.length)%p.length;while(!Yd(p[ee]));m(ee)}}else if(Sd(R)&&!Number.isNaN(Number(V.line))){let Q=Number(V.line)-1,ee=-1,je=p.findIndex((Jr)=>{if(at.isSeparator(Jr))return!1;return ee++,ee===Q}),Hr=p[je];if(Hr!=null&&Qd(Hr))m(je);d.current=setTimeout(()=>{V.clearLine(0)},700)}else if(Ed(R))V.clearLine(0);else if(c){let Q=V.line.toLowerCase(),ee=p.findIndex((je)=>{if(at.isSeparator(je)||!Qd(je))return!1;return je.name.toLowerCase().startsWith(Q)});if(ee!==-1)m(ee);d.current=setTimeout(()=>{V.clearLine(0)},700)}}),nr(()=>()=>{clearTimeout(d.current)},[]);let v=i.style.message(e.message,o),I=i.style.keysHelpTip([["\u2191\u2193","navigate"],["\u23CE","select"]]),E=0,w=Md({items:p,active:f,renderItem({item:R,isActive:V,index:Q}){if(at.isSeparator(R))return E++,` ${R.separator}`;let ee=V?i.icon.cursor:" ",je=i.indexMode==="number"?`${Q+1-E}. `:"";if(R.disabled){let Jr=typeof R.disabled==="string"?R.disabled:"(disabled)",tb=V?i.icon.cursor:"-";return i.style.disabled(`${tb} ${je}${R.name} ${Jr}`)}return(V?i.style.highlight:(Jr)=>Jr)(`${ee} ${je}${R.name}`)},pageSize:n,loop:r});if(o==="done")return[l,v,i.style.answer(g.short)].filter(Boolean).join(" ");let{description:x}=g;return`${[[l,v].filter(Boolean).join(" "),w," ",x?i.style.description(x):"",y?i.style.error(y):"",I].filter(Boolean).join(`
159
+ `).trimEnd()}${S_}`});var $A="Failure details are withheld because this API key has read access only. A key with write access on the project sees them.",IA=async(e)=>{let t=[];for await(let r of e)t.push(r);return t},EA=(e,t)=>{if(t===void 0||t.projectId!==e)return new Map;let r=new Map;for(let[i,s]of Object.entries(t.pipelines)){let o=r.get(s.pipelineId)??[];o.push(i),r.set(s.pipelineId,o)}let n=new Map;for(let[i,s]of r){let[o,...a]=s;if(o!==void 0&&a.length===0)n.set(i,o)}return n},SA=(e,t)=>{let r=t.get(e.id);return{pipelineId:e.id,name:e.name,...r===void 0?{}:{sourceDirectory:r}}},Kr=(e)=>e.sourceDirectory===void 0?`${e.name} (${e.pipelineId})`:`${e.name} (${e.pipelineId}) ${e.sourceDirectory}`,xA=(e)=>e.length===0?"This project has no pipelines.":`Unknown pipeline. This project has: ${e.map(Kr).join(", ")}.`;async function N_(e){return k_({message:"This project tracks several pipelines. Select one",choices:e})}async function M_(e){let t=await L_(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(`
160
+ `)}}var L_=async(e,t,r)=>{let n=await IA(e.pipelines.listAll({projectId:t})),i=EA(t,r);return n.map((s)=>SA(s,i)).toSorted((s,o)=>{let a=s.name.localeCompare(o.name);return a===0?s.pipelineId.localeCompare(o.pipelineId):a})},Ks=(e,t,r)=>{if(_(e.length<=1,t),e.length!==1)return;let[n]=e;return _(n,r),n},D_=(e,t)=>{let r=xA(t),n=Ks(t.filter((d)=>d.pipelineId===e),r,r);if(n!==void 0)return n;let i=t.filter((d)=>d.name===e),s=Ks(i,`Multiple pipelines are named ${e}: ${i.map(Kr).join(", ")}.`,r);if(s!==void 0)return s;let o=Ks(t.filter((d)=>d.sourceDirectory===e),r,r);if(o!==void 0)return o;let a=t.filter((d)=>{if(d.sourceDirectory===void 0)return!1;let c=d.sourceDirectory.split("/");return c[c.length-1]===e}),l=Ks(a,`Multiple pipelines match ${e}: ${a.map(Kr).join(", ")}.`,r);if(l!==void 0)return l;_(!1,r)};async function ii(e){let t=await L_(e.client,e.projectId,e.state);if(e.pipeline!==void 0)return D_(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((n)=>({name:Kr(n),value:n.pipelineId})));return D_(r,t)}if(t.length===1){let[r]=t;_(r,"This project has no pipelines."),_(!1,`Pass a pipeline name. This project has: ${Kr(r)}.`)}_(!1,`This project tracks several pipelines, so name one: ${t.map(Kr).join(", ")}.`)}var q_=(e)=>`run ${e.id} is ${e.status}`,U_=(e)=>{if(e.status==="succeeded")return"succeeded";if(e.status==="failed")return"failed";return"started"};async function B_(e,t){let r=await ii({client:e,...t}),n=await e.runs.start({pipelineId:r.pipelineId});if(t.wait!==!0)return{outcome:"started",output:[`Started ${q_(n)} for ${r.name}.`,`Follow it with toloka pipeline status ${r.pipelineId}, or re-run with --wait.`].join(`
161
+ `)};try{let i=await e.waitFor({type:"pipelineRun",runId:n.id},{...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.intervalMs===void 0?{}:{intervalMs:t.intervalMs}}),s=U_(i);return{outcome:s,output:s==="failed"?[`Run ${i.id} failed.`,`Inspect items with toloka pipeline results ${i.id} --failed.`].join(`
162
+ `):`Run ${i.id} succeeded.`}}catch(i){if(i instanceof te&&i.code==="wait_timeout")return{outcome:"timedOut",output:[`Stopped waiting for run ${n.id}; it has not reached a terminal state yet and may still be running.`,`Check it with toloka pipeline status ${r.pipelineId}.`].join(`
163
+ `)};throw i}}async function G_(e,t){let r=await ii({client:e,...t}),n=await e.runs.listPage({pipelineId:r.pipelineId,limit:t.limit??10});if(n.runs.length===0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let i=[];for(let s of n.runs){let o=await e.runs.get({runId:s.id});i.push(` ${o.id} ${o.status.padEnd(9)} ${s.createdAt}`)}return{outcome:"reported",output:[`Runs for ${r.name} (${n.pagination.total} total):`,...i].join(`
164
+ `)}}async function V_(e,t){let r=await ii({client:e,...t}),i=(await e.runs.listPage({pipelineId:r.pipelineId,limit:1})).runs[0];if(i===void 0)return{outcome:"reported",output:`No runs yet for ${r.name}.`};let s=await e.runs.get({runId:i.id}),o=t.itemScanLimit??500,a=new Map,l=0;for await(let c of e.runs.listAllItems({runId:s.id}))if(a.set(c.state.status,(a.get(c.state.status)??0)+1),l+=1,l>=o)break;let d=a.size===0?[" no items yet"]:[...a.entries()].toSorted(([c],[p])=>c.localeCompare(p)).map(([c,p])=>` ${c.padEnd(12)} ${p}`);return{outcome:U_(s),output:[`Latest ${q_(s)} (started ${i.createdAt}).`,l>=o?`Items (first ${o}):`:"Items:",...d].join(`
165
+ `)}}async function z_(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 jA=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
166
+ ${$A}`;return e.state.error===null?t:`${t}
167
+ ${e.state.error}`};async function K_(e,t){let r=t.limit??20,n=t.itemScanLimit??Math.max(500,r),i=[],s=0;for await(let l of e.runs.listAllItems({runId:t.runId})){if(s+=1,t.failedOnly!==!0||l.state.status==="failed")i.push(l);if(i.length>=r||s>=n)break}if(i.length===0)return{outcome:"reported",output:t.failedOnly===!0&&s>=n?`No failed items in the first ${n} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[s>=n&&i.length<r?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${i.length} after scanning ${n}, limit ${r}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${i.length}, limit ${r}):`,...i.map(jA)].join(`
168
+ `)}}var W_=(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},RA=(e)=>{let t=[0,0,0];for(let r of e)for(let n=0;n<3;n+=1){let i=r[n];t[n]=Math.max(t[n]??0,i?.length??0)}return e.map((r)=>r.map((n,i)=>i===0?n.padEnd(t[0]??0):n.padStart(t[i]??0)).join(" "))},H_=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let i of e.subLines??[])if(W_(i))n.push(...H_(i,t+1));return n},CA=(e)=>{let t=[],r=[];for(let n of e){if(n.kind==="priced"){t.push([n.nodeNameDisplay,n.expectedTotal,n.maxTotal]);for(let i of n.displayBreakdown)if(W_(i))t.push(...H_(i,1));continue}r.push(n.kind==="validation-errors"?` ${n.nodeNameDisplay} skipped (validation errors)`:` ${n.nodeNameDisplay} not billed`)}return{billed:t,unpriced:r}},OA=(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},FA=(e,t)=>{let{billed:r,unpriced:n}=CA(e.nodes),i=OA(e.total),s=RA([["Item","Expected","Maximum"],...r,...i]),o=s.slice(0,1+r.length),a=s.slice(1+r.length),l=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...o];if(r.length===0)l.push(" (no billed nodes)");if(l.push("",...a),n.length>0)l.push("","Not billed",...n);if(e.isInternalPricing===!0)l.push("","Internal-team pricing.");return l.push("",e.disclaimer),l.join(`
169
+ `)};async function J_(e,t){let r=await ii({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:r.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:FA(n,r.name)}}var Q_=require("crypto"),Xd=require("fs"),Ws=require("fs/promises"),We=require("path"),TA=262144,AA=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),kA=async(e,t)=>{let r=We.relative(t,e);if(r===""||r===".."||r.startsWith(`..${We.sep}`)||We.isAbsolute(r))return;let n=r.split(We.sep);for(let i=1;i<n.length;i+=1){let s=We.join(t,...n.slice(0,i)),o=await Ws.lstat(s);_(!o.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${s}; select a path that does not traverse symbolic links.`)}},DA=async(e,t,r)=>{let n=We.resolve(r,e);await kA(n,t);let i;try{i=await Ws.open(n,Xd.constants.O_RDONLY|Xd.constants.O_NOFOLLOW)}catch(s){throw _(!(s instanceof Error&&("code"in s)&&s.code==="ELOOP"),`Report file ${n} is a symbolic link; select the file it points to directly.`),s}try{let s=await i.stat();return _(s.isFile(),`Report file ${n} is not a regular file.`),_(s.size>0,`Report file ${n} is empty.`),_(s.size<=TA,`Report file ${n} is ${s.size} bytes; the limit is 256 KiB.`),{handle:i,absolutePath:n,size:s.size}}catch(s){throw await i.close(),s}},NA=async(e,t,r)=>{let n=await DA(e,t,r);try{let i=await n.handle.readFile();_(i.byteLength===n.size,`${n.absolutePath} changed while it was being read.`);try{return AA.decode(i)}catch{throw Error(`Report file ${n.absolutePath} is not valid UTF-8.`)}}finally{await n.handle.close()}},MA=async(e,t)=>{if(t)return!0;if(e.prompt===void 0)return!1;let r=(await e.prompt("Send this report to Toloka? [y/N] ")).trim().toLowerCase();return r==="y"||r==="yes"};async function Y_(e){let{analytics:t,io:r}=e;_(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.");let n=await NA(e.path,e.sourceRoot,e.cwd);if(r.stdout("Issue report preview:"),r.stdout(""),r.stdout(n.replace(/(?![\t\n])(?!\r\n)(?:\p{Cc}|\p{Bidi_Control})/gu,(s)=>`\\u${s.charCodeAt(0).toString(16).padStart(4,"0")}`)),r.stdout(""),r.stdout(`Authored by: ${e.authoredBy}`),r.stdout(`Platform: ${e.platform}`),r.stdout(""),!await MA(r,e.confirm))return r.stderr("Refusing to submit without confirmation in a non-interactive environment. Pass --confirm after reviewing the preview above."),1;let i=Q_.randomUUID();return await t.submitIssueReport({reportId:i,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),r.stdout(`Submitted issue report: ${i}`),0}var LA=["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 ${Vt}.`].join(`
170
+ `),qA=(e)=>{if(e!=="human"&&e!=="agent")throw new dt('Expected "human" or "agent".');return e},Wr=(e)=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new dt("Expected a positive integer.");return t},Zd=(e)=>{if(e==="failed")return 1;if(e==="timedOut")return 2;return 0},At=async(e,t)=>{if(e.sourceRoot!==void 0)return oi.resolve(e.sourceRoot);let r=process.cwd(),n=await yy(r);if(n===void 0||n===r)return r;return t.stderr(`Using project root ${n} (found from ${r}).`),n},X_=(e)=>e.sourceRoot===void 0?process.cwd():oi.resolve(e.sourceRoot),tc=async(e,t)=>{let{found:r,warning:n}=await xn(t.environment,e.apiKey??t.environment.POTATO_API_KEY);if(n!==void 0)t.io.stderr(n);return r?.credentials},si=async(e,t)=>{if(t?.shouldIdentify!==!0)return;try{t.identifyCurrentUser(await e.me())}catch{}},z=async(e,t)=>{let r=await At(e,t.io),n=await Ee(r),i=await tc(e,t),s=yl(e,n,t.environment,i),o=t.injectedClient??ct({apiKey:s.apiKey,baseUrl:s.baseUrl});return await si(o,t.analytics),{sourceRoot:r,client:o,baseUrl:s.baseUrl,state:n,stored:i,...s.projectId===void 0?{}:{projectId:s.projectId}}},ec=(e,t,r,n)=>Rn({flags:e,environment:t.environment,stored:r,...n===void 0?{}:{state:n}});function UA(e){let t=new or("toloka"),r={value:0},n=!1;t.description("Preview. Build and operate Toloka pipeline projects from TypeScript source. The public API may change.").version(Ve,"-v, --version","output the current version").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",`
171
+ ${LA}`).configureOutput({writeOut:(u)=>e.io.stdout(u.replace(/\n$/u,"")),writeErr:(u)=>e.io.stderr(u.replace(/\n$/u,""))}).exitOverride();let i=()=>t.opts();t.hook("postAction",async(u,f)=>{if(n)return;let m=[];for(let b=f;b!==null;b=b.parent)m.push(b.name());if(m.includes("init")||m.includes("help")||m.includes("report")||m.includes("url")||m.includes("version"))return;let g=await At(i(),e.io),y=await Sg(g).catch(()=>{return});if(y===void 0)return;n=!0,e.io.stderr(y)}),t.command("version").description("print the current CLI version").action(()=>e.io.stdout(Ve)),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let u=await bm({...i().apiKey===void 0?{}:{apiKey:i().apiKey},...i().baseUrl===void 0?{}:{baseUrl:i().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(u.output);try{let f=await am(e.environment);if(f===void 0)return;let m=e.injectedClient??ct(f);await si(m,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let u=await Pm(e.environment);e.io.stdout(u.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(u)=>{let f=i(),m=await xn(e.environment,f.apiKey??e.environment.POTATO_API_KEY),g=m.found?.credentials,y=await At(f,e.io),b=await Ee(y),v=ec(f,e,g,b),I=e.injectedClient,E=await wm({environment:e.environment,showToken:u.showToken,credentialLookup:m,...f.apiKey===void 0?{}:{flagApiKey:f.apiKey},...f.baseUrl===void 0?{}:{flagBaseUrl:f.baseUrl},...I===void 0?{}:{probe:()=>I},...v===void 0?{}:{project:v}});if(e.io.stdout(E.output),!E.authenticated){r.value=1;return}try{let w=yl(f,b,e.environment,g),x=e.injectedClient??ct({apiKey:w.apiKey,baseUrl:w.baseUrl});await si(x,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 u=i(),{client:f,stored:m,state:g}=await z(u,e),y=ec(u,e,m,g);await pm({client:f,io:e.io,...y===void 0?{}:{context:y}})}),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(u,f)=>{let m=i(),g=await Ct(e.environment),y=e.injectedClient??ct(g.credentials);await fm({environment:e.environment,flags:m,client:y,io:e.io,afterPreflight:async()=>si(y,e.analytics),...u===void 0?{}:{alias:u},...f===void 0?{}:{projectId:f}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(u)=>{await mm({environment:e.environment,flags:i(),alias:u,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let u=i(),f=await tc(u,e),m=await At(u,e.io),g=await Ee(m);if(gm({flags:u,environment:e.environment,stored:f,...g===void 0?{}:{state:g},io:e.io}).project===void 0)r.value=1}),s.command("url").description("print the current project URL").action(async()=>{let{baseUrl:u,client:f,projectId:m}=await z(i(),e);_(m,X);let g=await f.projects.get({projectId:m}),y=new URL(`/teams/${encodeURIComponent(g.teamId)}/projects/${encodeURIComponent(g.id)}`,u);e.io.stdout(y.href)}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(u)=>{await hm({environment:e.environment,flags:i(),alias:u,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(u,f)=>{let m=i(),g=await Ct(e.environment),y=e.injectedClient??ct(g.credentials),b=await At(m,e.io);await ym({environment:e.environment,flags:m,client:y,io:e.io,sourceRoot:b,afterPreflight:async()=>si(y,e.analytics),...u===void 0?{}:{alias:u},...f.name===void 0?{}:{name:f.name},...f.teamId===void 0?{}:{teamId:f.teamId}})}),t.command("init").description("initialize this project directory and install the agent bootstrap").action(async()=>{let u=i(),f=X_(u),m=await tc(u,e),g=await Ee(f),y=ec(u,e,m,g),b=await Eg(f,y===void 0?{}:{projectId:y.id});if(e.io.stdout(b.output),b.warning!==void 0)e.io.stderr(b.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(u,f)=>{let{sourceRoot:m,client:g,projectId:y}=await z(i(),e),b=u??y;_(b,X);let v=await vy(g,{sourceRoot:m,projectId:b,...f?.force===!0?{force:!0}:{}});e.io.stdout(v.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:u,client:f,projectId:m}=await z(i(),e),g=await wy(f,{sourceRoot:u,...m===void 0?{}:{projectId:m}});e.io.stdout(g.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:u,client:f,projectId:m}=await z(i(),e),g=await Ey(f,{sourceRoot:u,...m===void 0?{}:{projectId:m}});if(e.io.stdout(g.output),!g.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:u,client:f,projectId:m}=await z(i(),e),g=await Iy(f,{sourceRoot:u,...m===void 0?{}:{projectId:m}});e.io.stdout(g.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(u,f)=>{let{client:m,projectId:g}=await z(i(),e);_(g,X);let y=f.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[f.fromEnv];_(y!==void 0,`Missing secret value. Set ${f.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let b=await ky(m,{projectId:g,name:u,value:y});e.io.stdout(b.output)}catch{e.io.stderr(`Failed to set secret ${u}.`),r.value=1}});let a=t.command("base-model").description("inspect the global base model catalog");a.command("list").option("--json","print JSON",!1).description("list base models").action(async(u)=>{let{client:f}=await z(i(),e);await Ny(f,{json:u.json},e.io)}),a.command("get").argument("<id>","base model ID").option("--json","print JSON",!1).description("show one base model").action(async(u,f)=>{let{client:m}=await z(i(),e);await My(m,{id:$d(u),json:f.json},e.io)});let l=t.command("model").description("manage project Models and immutable versions");l.command("list").option("--json","print JSON",!1).description("list Models owned by the selected project").action(async(u)=>{let{client:f,projectId:m}=await z(i(),e);_(m,X),await Ly(f,{projectId:m,json:u.json},e.io)}),l.command("get").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("show one project Model").action(async(u,f)=>{let{client:m,projectId:g}=await z(i(),e);_(g,X),await qy(m,{projectId:g,nameOrId:u,json:f.json},e.io)}),l.command("versions").argument("<name-or-id>","project Model name or ID").option("--json","print JSON",!1).description("list immutable versions of a model").action(async(u,f)=>{let{client:m,projectId:g}=await z(i(),e);_(g,X),await Uy(m,{projectId:g,nameOrId:u,json:f.json},e.io)}),l.command("create").argument("<name>","new Model name").requiredOption("--base <id>","base model ID").option("--description <text>","Model description").option("--json","print JSON",!1).description("create project Model metadata without a Model Version").action(async(u,f)=>{let{client:m,projectId:g}=await z(i(),e);_(g,X),await By(m,{projectId:g,name:u,description:f.description,baseModelId:$d(f.base),json:f.json},e.io)}),l.command("archive").option("--json","print JSON",!1).argument("<name-or-id>","project Model name or ID").description("archive a project Model").action(async(u,f)=>{let{client:m,projectId:g}=await z(i(),e);_(g,X),await Gy(m,{projectId:g,nameOrId:u,json:f.json},e.io)});let d=t.command("dataset").description("inspect and move dataset catalog and rows");d.command("list").description("list live datasets in the selected project").action(async()=>{let{client:u,projectId:f}=await z(i(),e);_(f,X);let m=await Ty(u,{projectId:f});e.io.stdout(m.output)}),d.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(u)=>{let{sourceRoot:f,client:m,projectId:g}=await z(i(),e),y=await Fy(m,{sourceRoot:f,datasetName:u,...g===void 0?{}:{projectId:g}});e.io.stdout(y.output)}),d.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",Wr).option("--timeout <ms>","how long to wait for the export",Wr).description("download live dataset rows into a JSONL file").action(async(u,f)=>{let{sourceRoot:m,client:g,projectId:y}=await z(i(),e),b=await Ay(g,{sourceRoot:m,datasetName:u,outPath:oi.resolve(f.out),...y===void 0?{}:{projectId:y},...f.limit===void 0?{}:{limit:f.limit},...f.timeout===void 0?{}:{timeoutMs:f.timeout}});e.io.stdout(b.output)}),d.command("upload").argument("<name>","dataset name or id").argument("<file>","JSON array, JSONL, or CSV file").description("append rows to a dataset").action(async(u,f)=>{let{sourceRoot:m,client:g,projectId:y}=await z(i(),e),b=await Oy(g,{sourceRoot:m,datasetName:u,filePath:oi.resolve(f),...y===void 0?{}:{projectId:y}});if(e.io.stdout(b.output),b.warning!==void 0)e.io.stderr(b.warning)});let c="pipeline name or id; required unless a TTY picker can choose among several",p=t.command("pipeline").description("operate on a live pipeline in the selected project");p.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:u,projectId:f,state:m}=await z(i(),e);_(f,X);let g=await M_({client:u,projectId:f,state:m});e.io.stdout(g.output)}),p.command("run").argument("[name]",c).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Wr).description("start a run on a deployed pipeline").action(async(u,f)=>{let{client:m,state:g,projectId:y}=await z(i(),e);_(y,X);let b=await B_(m,{projectId:y,state:g,...u===void 0?{}:{pipeline:u},wait:f.wait,...f.timeout===void 0?{}:{timeoutMs:f.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(b.output),r.value=Zd(b.outcome)}),p.command("status").argument("[name]",c).description("report the latest run's state and item counts").action(async(u)=>{let{client:f,state:m,projectId:g}=await z(i(),e);_(g,X);let y=await V_(f,{projectId:g,state:m,...u===void 0?{}:{pipeline:u},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(y.output),r.value=Zd(y.outcome)}),p.command("runs").argument("[name]",c).option("--limit <n>","how many runs to list",Wr).description("list recent runs").action(async(u,f)=>{let{client:m,state:g,projectId:y}=await z(i(),e);_(y,X);let b=await G_(m,{projectId:y,state:g,...u===void 0?{}:{pipeline:u},...f.limit===void 0?{}:{limit:f.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(b.output)}),p.command("cost").argument("[name]",c).option("--item-limit <n>","cap how many items to price",Wr).description("forecast what a run of this pipeline would bill").action(async(u,f)=>{let{client:m,state:g,projectId:y}=await z(i(),e);_(y,X);let b=await J_(m,{projectId:y,state:g,...u===void 0?{}:{pipeline:u},...f.itemLimit===void 0?{}:{itemLimit:f.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(b.output)}),p.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(u)=>{let{client:f}=await z(i(),e),m=await z_(f,{runId:u});e.io.stdout(m.output)}),p.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Wr).option("--failed","only report failed items",!1).description("report a run's items").action(async(u,f)=>{let{client:m}=await z(i(),e),g=await K_(m,{runId:u,failedOnly:f.failed,...f.limit===void 0?{}:{limit:f.limit}});e.io.stdout(g.output),r.value=Zd(g.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:u,client:f,projectId:m}=await z(i(),e);_(m,X);let g=await $y(f,{sourceRoot:u,projectId:m});e.io.stdout(g.output)}),t.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",qA,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(u,f)=>{_(e.analytics,"Issue reporting requires CLI analytics.");let m=X_(i()),g=i().baseUrl??e.environment.POTATO_BASE_URL??ht(e.environment)??Vt;r.value=await Y_({path:u,authoredBy:f.authoredBy,platform:new URL(g).origin,confirm:f.confirm,sourceRoot:m,cwd:process.cwd(),analytics:e.analytics,io:e.io})});let h=t.command("skill").description("discover bundled agent skills and install them into .agents/skills");return h.command("list").option("--json","print Skill Descriptors with their status as JSON",!1).description("list bundled skills as not-installed, current, or stale").action(async(u)=>{let f=await At(i(),e.io);await gg({sourceRoot:f,json:u.json,io:e.io})}),h.command("search").argument("<query>","text matched case-insensitively against id, name, description, and tags").option("--json","print matching Skill Descriptors with their status as JSON",!1).description("find bundled skills for a task").action(async(u,f)=>{let m=await At(i(),e.io);await yg({sourceRoot:m,query:u,json:f.json,io:e.io})}),h.command("install").argument("<skillId>","skill id from toloka skill list").option("-f, --force","replace an existing .agents/skills/<skillId> directory",!1).description("copy one bundled skill into .agents/skills/<skillId>").action(async(u,f)=>{let m=await At(i(),e.io);await _g({sourceRoot:m,skillId:u,force:f.force,io:e.io})}),{program:t,exitCode:r}}var BA=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},GA=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:n,reject:i}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",c),process.stdin.off("end",l),process.stdin.off("error",d),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
172
+ `)},l=()=>{a(),i(Error("Standard input closed before an API key was entered."))},d=(p)=>{a(),i(p)},c=(p)=>{for(let h of p){if(h==="\r"||h===`
173
+ `){a(),n(s);return}if(h==="\x03"||h==="\x04"){a(),i(Error(h==="\x03"?"Canceled.":"Standard input closed before an API key was entered."));return}if(h==="\x7F"||h==="\b"){if(s.length>0)s=s.slice(0,-1),process.stdout.write("\b \b");continue}s+=h,process.stdout.write("*")}};process.stdin.on("data",c),process.stdin.once("end",l),process.stdin.once("error",d);try{return await r}finally{o()}},VA=async(e,t={})=>{if(t.mask===!0)return GA(e);let r=Z_.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await r.question(e)}finally{r.close()}},zA=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:BA,...process.stdin.isTTY?{prompt:VA,select:N_}:{}}),KA=async(e,t,r,n)=>{try{await e.parseAsync([...r],{from:"user"});let i=t.value;return{code:i,outcome:i===0?"succeeded":"failed"}}catch(i){if(i instanceof lt){let s=i.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:i}}return n.stderr(Vn(i)),{code:1,outcome:"failed",error:i}}};async function eb(e,t=process.env,r=zA(),n,i=Rg({environment:t})){let{program:s,exitCode:o}=UA({environment:t,io:r,analytics:i,...n===void 0?{}:{injectedClient:n}}),a=Date.now(),l=await KA(s,o,e,r);try{i.captureCommand({command:jg(e),durationMs:Date.now()-a,exitCode:l.code,outcome:l.outcome,...l.error===void 0?{}:{error:l.error}}),await i.shutdown()}catch{}return l.code}eb(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})