@toloka-platform/sdk 0.1.0-preview.4 → 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.
- package/README.md +1 -1
- package/dist/cli/toloka.js +132 -126
- package/dist/cli/toloka.js.jsc +0 -0
- package/dist/cli/toloka.js.jsc.sha256 +1 -1
- package/dist/cli/toloka.js.sha256 +1 -1
- package/docs/cli-v2.md +4 -0
- package/docs/cli.md +82 -6
- package/docs/datasets.md +8 -9
- package/docs/getting-started.md +2 -2
- package/docs/limitations.md +5 -8
- package/docs/troubleshooting.md +0 -11
- package/openapi/gen/api.ts +782 -876
- package/openapi/gen/models/baseModel.ts +9 -0
- package/openapi/gen/models/baseModelId.ts +2 -0
- package/openapi/gen/models/baseModelIdProperty.ts +2 -0
- package/openapi/gen/models/createDatasetBody.ts +2 -0
- package/openapi/gen/models/createDatasetBodyProfile.ts +2 -0
- package/openapi/gen/models/createDatasetUploadBodyFormat.ts +1 -1
- package/openapi/gen/models/createProjectModelBody.ts +8 -0
- package/openapi/gen/models/createProjectModelBodyDescription.ts +2 -0
- package/openapi/gen/models/dataset.ts +2 -0
- package/openapi/gen/models/datasetProfile.ts +3 -0
- package/openapi/gen/models/datasetProfileStamp.ts +6 -0
- package/openapi/gen/models/datasetProfileStampName.ts +2 -0
- package/openapi/gen/models/generationNodeSettingsAudienceAndPricingOneOfOneone.ts +1 -0
- package/openapi/gen/models/index.ts +21 -0
- package/openapi/gen/models/listBaseModels200.ts +5 -0
- package/openapi/gen/models/listModelVersions200.ts +7 -0
- package/openapi/gen/models/listModelVersionsParams.ts +5 -0
- package/openapi/gen/models/listProjectModels200.ts +7 -0
- package/openapi/gen/models/listProjectModelsParams.ts +5 -0
- package/openapi/gen/models/model.ts +16 -0
- package/openapi/gen/models/modelArchivedAt.ts +2 -0
- package/openapi/gen/models/modelDescription.ts +2 -0
- package/openapi/gen/models/modelId.ts +2 -0
- package/openapi/gen/models/modelVersion.ts +9 -0
- package/openapi/gen/models/modelVersionId.ts +2 -0
- package/openapi/gen/models/pipelineGraphSnapshotGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneone.ts +1 -0
- package/openapi/gen/models/runCost.ts +7 -0
- package/openapi/gen/models/validatePipelineGraphBodyGraphNodesItemOneOfThreeoneSettingsAudienceAndPricingOneOfOneone.ts +1 -0
- package/package.json +2 -1
- package/skills/catalog.json +22 -0
- package/skills/{SKILL.md → toloka-build/SKILL.md} +2 -2
- package/skills/{references → toloka-build/references}/workflow-and-cli.md +26 -5
- package/skills/toloka-report-issue/SKILL.md +25 -0
- package/skills/toloka-report-issue/references/report-template.md +34 -0
- package/src/cli/analytics.ts +53 -1
- package/src/cli/data.ts +148 -25
- package/src/cli/file-system.ts +34 -0
- package/src/cli/format-error.ts +19 -0
- package/src/cli/init.ts +149 -194
- package/src/cli/models.ts +188 -0
- package/src/cli/program.ts +202 -22
- package/src/cli/report.ts +144 -0
- package/src/cli/skill.ts +363 -0
- package/src/client.ts +109 -35
- package/src/errors.ts +25 -10
- package/src/pipeline-graph-v1.contract.json +5 -1
- package/src/transport.ts +16 -13
- /package/skills/{references → toloka-build/references}/node-semantics.md +0 -0
package/dist/cli/toloka.js
CHANGED
|
@@ -1,167 +1,173 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun @bytecode @bun-cjs
|
|
3
|
-
(function(exports, require, module, __filename, __dirname) {var Yy=Object.create;var{getPrototypeOf:Xy,defineProperty:ks,getOwnPropertyNames:Zy}=Object;var e_=Object.prototype.hasOwnProperty;function t_(e){return this[e]}var r_,i_,xe=(e,t,r)=>{var i=e!=null&&typeof e==="object";if(i){var n=t?r_??=new WeakMap:i_??=new WeakMap,s=n.get(e);if(s)return s}r=e!=null?Yy(Xy(e)):{};let o=t||!e||!e.__esModule?ks(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Zy(e))if(!e_.call(o,a))ks(o,a,{get:t_.bind(e,a),enumerable:!0})}if(i)n.set(e,o);return o};var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var n_=(e)=>e;function s_(e,t){this[e]=n_.bind(null,t)}var o_=(e,t)=>{for(var r in t)ks(e,r,{get:t[r],enumerable:!0,configurable:!0,set:s_.bind(t,r)})};var Kr=b(function(M){Object.defineProperty(M,"__esModule",{value:!0});M.regexpCode=M.getEsmExportName=M.getProperty=M.safeStringify=M.stringify=M.strConcat=M.addCodeArg=M.str=M._=M.nil=M._Code=M.Name=M.IDENTIFIER=M._CodeOrName=void 0;class en{}M._CodeOrName=en;M.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class tr extends en{constructor(e){super();if(!M.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}M.Name=tr;class De extends en{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof tr)t[r.str]=(t[r.str]||0)+1;return t},{})}}M._Code=De;M.nil=new De("");function _d(e,...t){let r=[e[0]],i=0;while(i<t.length)Zs(r,t[i]),r.push(e[++i]);return new De(r)}M._=_d;var Xs=new De("+");function Pd(e,...t){let r=[Vr(e[0])],i=0;while(i<t.length)r.push(Xs),Zs(r,t[i]),r.push(Xs,Vr(e[++i]));return gv(r),new De(r)}M.str=Pd;function Zs(e,t){if(t instanceof De)e.push(...t._items);else if(t instanceof tr)e.push(t);else e.push(Pv(t))}M.addCodeArg=Zs;function gv(e){let t=1;while(t<e.length-1){if(e[t]===Xs){let r=yv(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function yv(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof tr||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof tr))return`"${e}${t.slice(1)}`;return}function _v(e,t){return t.emptyStr()?e:e.emptyStr()?t:Pd`${e}${t}`}M.strConcat=_v;function Pv(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Vr(Array.isArray(e)?e.join(","):e)}function bv(e){return new De(Vr(e))}M.stringify=bv;function Vr(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}M.safeStringify=Vr;function vv(e){return typeof e=="string"&&M.IDENTIFIER.test(e)?new De(`.${e}`):_d`[${e}]`}M.getProperty=vv;function wv(e){if(typeof e=="string"&&M.IDENTIFIER.test(e))return new De(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}M.getEsmExportName=wv;function $v(e){return new De(e.toString())}M.regexpCode=$v});var ro=b(function(_e){Object.defineProperty(_e,"__esModule",{value:!0});_e.ValueScope=_e.ValueScopeName=_e.Scope=_e.varKinds=_e.UsedValueState=void 0;var ye=Kr();class bd extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var tn;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(tn||(_e.UsedValueState=tn={}));_e.varKinds={const:new ye.Name("const"),let:new ye.Name("let"),var:new ye.Name("var")};class eo{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ye.Name?e:this.name(e)}name(e){return new ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}_e.Scope=eo;class to extends ye.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=ye._`.${new ye.Name(t)}[${r}]`}}_e.ValueScopeName=to;var Ev=ye._`\n`;class vd extends eo{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Ev:ye.nil}}get(){return this._scope}name(e){return new to(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:n}=i,s=(r=t.key)!==null&&r!==void 0?r:t.ref,o=this._values[n];if(o){let u=o.get(s);if(u)return u}else o=this._values[n]=new Map;o.set(s,i);let a=this._scope[n]||(this._scope[n]=[]),c=a.length;return a[c]=t.ref,i.setValue(t,{property:n,itemIndex:c}),i}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return ye._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(i)=>{if(i.value===void 0)throw Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,r)}_reduceValues(e,t,r={},i){let n=ye.nil;for(let s in e){let o=e[s];if(!o)continue;let a=r[s]=r[s]||new Map;o.forEach((c)=>{if(a.has(c))return;a.set(c,tn.Started);let u=t(c);if(u){let l=this.opts.es5?_e.varKinds.var:_e.varKinds.const;n=ye._`${n}${l} ${c} = ${u};${this.opts._n}`}else if(u=i===null||i===void 0?void 0:i(c))n=ye._`${n}${u}${this.opts._n}`;else throw new bd(c);a.set(c,tn.Completed)})}return n}}_e.ValueScope=vd});var F=b(function(A){Object.defineProperty(A,"__esModule",{value:!0});A.or=A.and=A.not=A.CodeGen=A.operators=A.varKinds=A.ValueScopeName=A.ValueScope=A.Scope=A.Name=A.regexpCode=A.stringify=A.getProperty=A.nil=A.strConcat=A.str=A._=void 0;var N=Kr(),Ne=ro(),ht=Kr();Object.defineProperty(A,"_",{enumerable:!0,get:function(){return ht._}});Object.defineProperty(A,"str",{enumerable:!0,get:function(){return ht.str}});Object.defineProperty(A,"strConcat",{enumerable:!0,get:function(){return ht.strConcat}});Object.defineProperty(A,"nil",{enumerable:!0,get:function(){return ht.nil}});Object.defineProperty(A,"getProperty",{enumerable:!0,get:function(){return ht.getProperty}});Object.defineProperty(A,"stringify",{enumerable:!0,get:function(){return ht.stringify}});Object.defineProperty(A,"regexpCode",{enumerable:!0,get:function(){return ht.regexpCode}});Object.defineProperty(A,"Name",{enumerable:!0,get:function(){return ht.Name}});var ln=ro();Object.defineProperty(A,"Scope",{enumerable:!0,get:function(){return ln.Scope}});Object.defineProperty(A,"ValueScope",{enumerable:!0,get:function(){return ln.ValueScope}});Object.defineProperty(A,"ValueScopeName",{enumerable:!0,get:function(){return ln.ValueScopeName}});Object.defineProperty(A,"varKinds",{enumerable:!0,get:function(){return ln.varKinds}});A.operators={GT:new N._Code(">"),GTE:new N._Code(">="),LT:new N._Code("<"),LTE:new N._Code("<="),EQ:new N._Code("==="),NEQ:new N._Code("!=="),NOT:new N._Code("!"),OR:new N._Code("||"),AND:new N._Code("&&"),ADD:new N._Code("+")};class gt{optimizeNodes(){return this}optimizeNames(e,t){return this}}class wd extends gt{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?Ne.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ir(this.rhs,e,t);return this}get names(){return this.rhs instanceof N._CodeOrName?this.rhs.names:{}}}class so extends gt{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof N.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ir(this.rhs,e,t),this}get names(){let e=this.lhs instanceof N.Name?{}:{...this.lhs.names};return an(e,this.rhs)}}class $d extends so{constructor(e,t,r,i){super(e,r,i);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class Ed extends gt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class Id extends gt{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class Sd extends gt{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class xd extends gt{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ir(this.code,e,t),this}get names(){return this.code instanceof N._CodeOrName?this.code.names:{}}}class cn extends gt{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,i=r.length;while(i--){let n=r[i];if(n.optimizeNames(e,t))continue;Iv(e,n.names),r.splice(i,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Ct(e,t.names),{})}}class yt extends cn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class Rd extends cn{}class zr extends yt{}zr.kind="else";class nt extends yt{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new zr(r):r}if(t){if(e===!1)return t instanceof nt?t:t.nodes;if(this.nodes.length)return this;return new nt(Td(e),t instanceof nt?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ir(this.condition,e,t),this}get names(){let e=super.names;if(an(e,this.condition),this.else)Ct(e,this.else.names);return e}}nt.kind="if";class rr extends yt{}rr.kind="for";class Cd extends rr{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ir(this.iteration,e,t),this}get names(){return Ct(super.names,this.iteration.names)}}class jd extends rr{constructor(e,t,r,i){super();this.varKind=e,this.name=t,this.from=r,this.to=i}render(e){let t=e.es5?Ne.varKinds.var:this.varKind,{name:r,from:i,to:n}=this;return`for(${t} ${r}=${i}; ${r}<${n}; ${r}++)`+super.render(e)}get names(){let e=an(super.names,this.from);return an(e,this.to)}}class io extends rr{constructor(e,t,r,i){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ir(this.iterable,e,t),this}get names(){return Ct(super.names,this.iterable.names)}}class rn extends yt{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}rn.kind="func";class nn extends cn{render(e){return"return "+super.render(e)}}nn.kind="return";class Fd extends yt{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,i;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)Ct(e,this.catch.names);if(this.finally)Ct(e,this.finally.names);return e}}class sn extends yt{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}sn.kind="catch";class on extends yt{render(e){return"finally"+super.render(e)}}on.kind="finally";class Od{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
4
|
-
`:""},this._extScope=e,this._scope=new Ne.Scope({parent:e}),this._nodes=[new Rd]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,i){let n=this._scope.toName(t);if(r!==void 0&&i)this._constants[n.str]=r;return this._leafNode(new wd(e,n,r)),n}const(e,t,r){return this._def(Ne.varKinds.const,e,t,r)}let(e,t,r){return this._def(Ne.varKinds.let,e,t,r)}var(e,t,r){return this._def(Ne.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new so(e,t,r))}add(e,t){return this._leafNode(new $d(e,A.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==N.nil)this._leafNode(new xd(e));return this}object(...e){let t=["{"];for(let[r,i]of e){if(t.length>1)t.push(",");if(t.push(r),r!==i||this.opts.es5)t.push(":"),(0,N.addCodeArg)(t,i)}return t.push("}"),new N._Code(t)}if(e,t,r){if(this._blockNode(new nt(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new nt(e))}else(){return this._elseNode(new zr)}endIf(){return this._endBlockNode(nt,zr)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new Cd(e),t)}forRange(e,t,r,i,n=this.opts.es5?Ne.varKinds.var:Ne.varKinds.let){let s=this._scope.toName(e);return this._for(new jd(n,s,t,r),()=>i(s))}forOf(e,t,r,i=Ne.varKinds.const){let n=this._scope.toName(e);if(this.opts.es5){let s=t instanceof N.Name?t:this.var("_arr",t);return this.forRange("_i",0,N._`${s}.length`,(o)=>{this.var(n,N._`${s}[${o}]`),r(n)})}return this._for(new io("of",i,n,t),()=>r(n))}forIn(e,t,r,i=this.opts.es5?Ne.varKinds.var:Ne.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,N._`Object.keys(${t})`,r);let n=this._scope.toName(e);return this._for(new io("in",i,n,t),()=>r(n))}endFor(){return this._endBlockNode(rr)}label(e){return this._leafNode(new Ed(e))}break(e){return this._leafNode(new Id(e))}return(e){let t=new nn;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(nn)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let i=new Fd;if(this._blockNode(i),this.code(e),t){let n=this.name("e");this._currNode=i.catch=new sn(n),t(n)}if(r)this._currNode=i.finally=new on,this.code(r);return this._endBlockNode(sn,on)}throw(e){return this._leafNode(new Sd(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=N.nil,r,i){if(this._blockNode(new rn(e,t,r)),i)this.code(i).endFunc();return this}endFunc(){return this._endBlockNode(rn)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof nt))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}A.CodeGen=Od;function Ct(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function an(e,t){return t instanceof N._CodeOrName?Ct(e,t.names):e}function ir(e,t,r){if(e instanceof N.Name)return i(e);if(!n(e))return e;return new N._Code(e._items.reduce((s,o)=>{if(o instanceof N.Name)o=i(o);if(o instanceof N._Code)s.push(...o._items);else s.push(o);return s},[]));function i(s){let o=r[s.str];if(o===void 0||t[s.str]!==1)return s;return delete t[s.str],o}function n(s){return s instanceof N._Code&&s._items.some((o)=>o instanceof N.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function Iv(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Td(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:N._`!${no(e)}`}A.not=Td;var Sv=Ad(A.operators.AND);function xv(...e){return e.reduce(Sv)}A.and=xv;var Rv=Ad(A.operators.OR);function Cv(...e){return e.reduce(Rv)}A.or=Cv;function Ad(e){return(t,r)=>t===N.nil?r:r===N.nil?t:N._`${no(t)} ${e} ${no(r)}`}function no(e){return e instanceof N.Name?e:N._`(${e})`}});var D=b(function(k){Object.defineProperty(k,"__esModule",{value:!0});k.checkStrictMode=k.getErrorPath=k.Type=k.useFunc=k.setEvaluated=k.evaluatedPropsToName=k.mergeEvaluated=k.eachItem=k.unescapeJsonPointer=k.escapeJsonPointer=k.escapeFragment=k.unescapeFragment=k.schemaRefOrVal=k.schemaHasRulesButRef=k.schemaHasRules=k.checkUnknownRules=k.alwaysValidSchema=k.toHash=void 0;var G=F(),jv=Kr();function Fv(e){let t={};for(let r of e)t[r]=!0;return t}k.toHash=Fv;function Ov(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Nd(e,t),!Ld(t,e.self.RULES.all)}k.alwaysValidSchema=Ov;function Nd(e,t=e.schema){let{opts:r,self:i}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let n=i.RULES.keywords;for(let s in t)if(!n[s])Ud(e,`unknown keyword: "${s}"`)}k.checkUnknownRules=Nd;function Ld(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}k.schemaHasRules=Ld;function Tv(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}k.schemaHasRulesButRef=Tv;function Av({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return G._`${r}`}return G._`${e}${t}${(0,G.getProperty)(i)}`}k.schemaRefOrVal=Av;function kv(e){return qd(decodeURIComponent(e))}k.unescapeFragment=kv;function Dv(e){return encodeURIComponent(ao(e))}k.escapeFragment=Dv;function ao(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}k.escapeJsonPointer=ao;function qd(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}k.unescapeJsonPointer=qd;function Nv(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}k.eachItem=Nv;function kd({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,s,o,a)=>{let c=o===void 0?s:o instanceof G.Name?(s instanceof G.Name?e(n,s,o):t(n,s,o),o):s instanceof G.Name?(t(n,o,s),s):r(s,o);return a===G.Name&&!(c instanceof G.Name)?i(n,c):c}}k.mergeEvaluated={props:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>{e.if(G._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,G._`${r} || {}`).code(G._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,G._`${r} || {}`),lo(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Md}),items:kd({mergeNames:(e,t,r)=>e.if(G._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,G._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(G._`${r} !== true`,()=>e.assign(r,t===!0?!0:G._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Md(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",G._`{}`);if(t!==void 0)lo(e,r,t);return r}k.evaluatedPropsToName=Md;function lo(e,t,r){Object.keys(r).forEach((i)=>e.assign(G._`${t}${(0,G.getProperty)(i)}`,!0))}k.setEvaluated=lo;var Dd={};function Lv(e,t){return e.scopeValue("func",{ref:t,code:Dd[t.code]||(Dd[t.code]=new jv._Code(t.code))})}k.useFunc=Lv;var oo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oo||(k.Type=oo={}));function qv(e,t,r){if(e instanceof G.Name){let i=t===oo.Num;return r?i?G._`"[" + ${e} + "]"`:G._`"['" + ${e} + "']"`:i?G._`"/" + ${e}`:G._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,G.getProperty)(e).toString():"/"+ao(e)}k.getErrorPath=qv;function Ud(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}k.checkStrictMode=Ud});var Re=b(function(co){Object.defineProperty(co,"__esModule",{value:!0});var ae=F(),Mv={data:new ae.Name("data"),valCxt:new ae.Name("valCxt"),instancePath:new ae.Name("instancePath"),parentData:new ae.Name("parentData"),parentDataProperty:new ae.Name("parentDataProperty"),rootData:new ae.Name("rootData"),dynamicAnchors:new ae.Name("dynamicAnchors"),vErrors:new ae.Name("vErrors"),errors:new ae.Name("errors"),this:new ae.Name("this"),self:new ae.Name("self"),scope:new ae.Name("scope"),json:new ae.Name("json"),jsonPos:new ae.Name("jsonPos"),jsonLen:new ae.Name("jsonLen"),jsonPart:new ae.Name("jsonPart")};co.default=Mv});var Wr=b(function(le){Object.defineProperty(le,"__esModule",{value:!0});le.extendErrors=le.resetErrorsCount=le.reportExtraError=le.reportError=le.keyword$DataError=le.keywordError=void 0;var L=F(),dn=D(),ue=Re();le.keywordError={message:({keyword:e})=>L.str`must pass "${e}" keyword validation`};le.keyword$DataError={message:({keyword:e,schemaType:t})=>t?L.str`"${e}" keyword must be ${t} ($data)`:L.str`"${e}" keyword is invalid ($data)`};function Uv(e,t=le.keywordError,r,i){let{it:n}=e,{gen:s,compositeRule:o,allErrors:a}=n,c=Vd(e,t,r);if(i!==null&&i!==void 0?i:o||a)Bd(s,c);else Gd(n,L._`[${c}]`)}le.reportError=Uv;function Bv(e,t=le.keywordError,r){let{it:i}=e,{gen:n,compositeRule:s,allErrors:o}=i,a=Vd(e,t,r);if(Bd(n,a),!(s||o))Gd(i,ue.default.vErrors)}le.reportExtraError=Bv;function Gv(e,t){e.assign(ue.default.errors,t),e.if(L._`${ue.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(L._`${ue.default.vErrors}.length`,t),()=>e.assign(ue.default.vErrors,null)))}le.resetErrorsCount=Gv;function Vv({gen:e,keyword:t,schemaValue:r,data:i,errsCount:n,it:s}){if(n===void 0)throw Error("ajv implementation error");let o=e.name("err");e.forRange("i",n,ue.default.errors,(a)=>{if(e.const(o,L._`${ue.default.vErrors}[${a}]`),e.if(L._`${o}.instancePath === undefined`,()=>e.assign(L._`${o}.instancePath`,(0,L.strConcat)(ue.default.instancePath,s.errorPath))),e.assign(L._`${o}.schemaPath`,L.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(L._`${o}.schema`,r),e.assign(L._`${o}.data`,i)})}le.extendErrors=Vv;function Bd(e,t){let r=e.const("err",t);e.if(L._`${ue.default.vErrors} === null`,()=>e.assign(ue.default.vErrors,L._`[${r}]`),L._`${ue.default.vErrors}.push(${r})`),e.code(L._`${ue.default.errors}++`)}function Gd(e,t){let{gen:r,validateName:i,schemaEnv:n}=e;if(n.$async)r.throw(L._`new ${e.ValidationError}(${t})`);else r.assign(L._`${i}.errors`,t),r.return(!1)}var jt={keyword:new L.Name("keyword"),schemaPath:new L.Name("schemaPath"),params:new L.Name("params"),propertyName:new L.Name("propertyName"),message:new L.Name("message"),schema:new L.Name("schema"),parentSchema:new L.Name("parentSchema")};function Vd(e,t,r){let{createErrors:i}=e.it;if(i===!1)return L._`{}`;return Kv(e,t,r)}function Kv(e,t,r={}){let{gen:i,it:n}=e,s=[zv(n,r),Wv(e,r)];return Hv(e,t,s),i.object(...s)}function zv({errorPath:e},{instancePath:t}){let r=t?L.str`${e}${(0,dn.getErrorPath)(t,dn.Type.Str)}`:e;return[ue.default.instancePath,(0,L.strConcat)(ue.default.instancePath,r)]}function Wv({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:i}){let n=i?t:L.str`${t}/${e}`;if(r)n=L.str`${n}${(0,dn.getErrorPath)(r,dn.Type.Str)}`;return[jt.schemaPath,n]}function Hv(e,{params:t,message:r},i){let{keyword:n,data:s,schemaValue:o,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;if(i.push([jt.keyword,n],[jt.params,typeof t=="function"?t(e):t||L._`{}`]),c.messages)i.push([jt.message,typeof r=="function"?r(e):r]);if(c.verbose)i.push([jt.schema,o],[jt.parentSchema,L._`${l}${d}`],[ue.default.data,s]);if(u)i.push([jt.propertyName,u])}});var zd=b(function(nr){Object.defineProperty(nr,"__esModule",{value:!0});nr.boolOrEmptySchema=nr.topBoolOrEmptySchema=void 0;var Jv=Wr(),Qv=F(),Yv=Re(),Xv={message:"boolean schema is false"};function Zv(e){let{gen:t,schema:r,validateName:i}=e;if(r===!1)Kd(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(Yv.default.data);else t.assign(Qv._`${i}.errors`,null),t.return(!0)}nr.topBoolOrEmptySchema=Zv;function ew(e,t){let{gen:r,schema:i}=e;if(i===!1)r.var(t,!1),Kd(e);else r.var(t,!0)}nr.boolOrEmptySchema=ew;function Kd(e,t){let{gen:r,data:i}=e,n={gen:r,keyword:"false schema",data:i,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Jv.reportError)(n,Xv,void 0,t)}});var uo=b(function(sr){Object.defineProperty(sr,"__esModule",{value:!0});sr.getRules=sr.isJSONType=void 0;var tw=["string","number","integer","boolean","null","object","array"],rw=new Set(tw);function iw(e){return typeof e=="string"&&rw.has(e)}sr.isJSONType=iw;function nw(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}sr.getRules=nw});var po=b(function(_t){Object.defineProperty(_t,"__esModule",{value:!0});_t.shouldUseRule=_t.shouldUseGroup=_t.schemaHasRulesForType=void 0;function sw({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&Wd(e,i)}_t.schemaHasRulesForType=sw;function Wd(e,t){return t.rules.some((r)=>Hd(e,r))}_t.shouldUseGroup=Wd;function Hd(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((i)=>e[i]!==void 0))}_t.shouldUseRule=Hd});var Hr=b(function(ce){Object.defineProperty(ce,"__esModule",{value:!0});ce.reportTypeError=ce.checkDataTypes=ce.checkDataType=ce.coerceAndCheckDataType=ce.getJSONTypes=ce.getSchemaTypes=ce.DataType=void 0;var ow=uo(),aw=po(),lw=Wr(),O=F(),Jd=D(),or;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(or||(ce.DataType=or={}));function cw(e){let t=Qd(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}ce.getSchemaTypes=cw;function Qd(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(ow.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ce.getJSONTypes=Qd;function dw(e,t){let{gen:r,data:i,opts:n}=e,s=uw(t,n.coerceTypes),o=t.length>0&&!(s.length===0&&t.length===1&&(0,aw.schemaHasRulesForType)(e,t[0]));if(o){let a=mo(t,i,n.strictNumbers,or.Wrong);r.if(a,()=>{if(s.length)pw(e,t,s);else ho(e)})}return o}ce.coerceAndCheckDataType=dw;var Yd=new Set(["string","number","integer","boolean","null"]);function uw(e,t){return t?e.filter((r)=>Yd.has(r)||t==="array"&&r==="array"):[]}function pw(e,t,r){let{gen:i,data:n,opts:s}=e,o=i.let("dataType",O._`typeof ${n}`),a=i.let("coerced",O._`undefined`);if(s.coerceTypes==="array")i.if(O._`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,O._`${n}[0]`).assign(o,O._`typeof ${n}`).if(mo(t,n,s.strictNumbers),()=>i.assign(a,n)));i.if(O._`${a} !== undefined`);for(let u of r)if(Yd.has(u)||u==="array"&&s.coerceTypes==="array")c(u);i.else(),ho(e),i.endIf(),i.if(O._`${a} !== undefined`,()=>{i.assign(n,a),fw(e,a)});function c(u){switch(u){case"string":i.elseIf(O._`${o} == "number" || ${o} == "boolean"`).assign(a,O._`"" + ${n}`).elseIf(O._`${n} === null`).assign(a,O._`""`);return;case"number":i.elseIf(O._`${o} == "boolean" || ${n} === null
|
|
5
|
-
|| (${o} == "string" && ${
|
|
6
|
-
|| (${o} === "string" && ${
|
|
7
|
-
|| ${o} === "boolean" || ${n} === null`).assign(a,O._`[${n}]`)}}}function fw({gen:e,parentData:t,parentDataProperty:r},i){e.if(O._`${t} !== undefined`,()=>e.assign(O._`${t}[${r}]`,i))}function fo(e,t,r,i=or.Correct){let n=i===or.Correct?O.operators.EQ:O.operators.NEQ,s;switch(e){case"null":return O._`${t} ${n} null`;case"array":s=O._`Array.isArray(${t})`;break;case"object":s=O._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(O._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return O._`typeof ${t} ${n} ${e}`}return i===or.Correct?s:(0,O.not)(s);function o(a=O.nil){return(0,O.and)(O._`typeof ${t} == "number"`,a,r?O._`isFinite(${t})`:O.nil)}}ce.checkDataType=fo;function mo(e,t,r,i){if(e.length===1)return fo(e[0],t,r,i);let n,s=(0,Jd.toHash)(e);if(s.array&&s.object){let o=O._`typeof ${t} != "object"`;n=s.null?o:O._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else n=O.nil;if(s.number)delete s.integer;for(let o in s)n=(0,O.and)(n,fo(o,t,r,i));return n}ce.checkDataTypes=mo;var mw={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?O._`{type: ${e}}`:O._`{type: ${t}}`};function ho(e){let t=hw(e);(0,lw.reportError)(t,mw)}ce.reportTypeError=ho;function hw(e){let{gen:t,data:r,schema:i}=e,n=(0,Jd.schemaRefOrVal)(e,i,"type");return{gen:t,keyword:"type",data:r,schema:i.type,schemaCode:n,schemaValue:n,parentSchema:i,params:{},it:e}}});var Zd=b(function(un){Object.defineProperty(un,"__esModule",{value:!0});un.assignDefaults=void 0;var ar=F(),gw=D();function yw(e,t){let{properties:r,items:i}=e.schema;if(t==="object"&&r)for(let n in r)Xd(e,n,r[n].default);else if(t==="array"&&Array.isArray(i))i.forEach((n,s)=>Xd(e,s,n.default))}un.assignDefaults=yw;function Xd(e,t,r){let{gen:i,compositeRule:n,data:s,opts:o}=e;if(r===void 0)return;let a=ar._`${s}${(0,ar.getProperty)(t)}`;if(n){(0,gw.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=ar._`${a} === undefined`;if(o.useDefaults==="empty")c=ar._`${c} || ${a} === null || ${a} === ""`;i.if(c,ar._`${a} = ${(0,ar.stringify)(r)}`)}});var Ce=b(function(B){Object.defineProperty(B,"__esModule",{value:!0});B.validateUnion=B.validateArray=B.usePattern=B.callValidateCode=B.schemaProperties=B.allSchemaProperties=B.noPropertyInData=B.propertyInData=B.isOwnProperty=B.hasPropFunc=B.reportMissingProp=B.checkMissingProp=B.checkReportMissingProp=void 0;var K=F(),go=D(),Pt=Re(),_w=D();function Pw(e,t){let{gen:r,data:i,it:n}=e;r.if(_o(r,i,t,n.opts.ownProperties),()=>{e.setParams({missingProperty:K._`${t}`},!0),e.error()})}B.checkReportMissingProp=Pw;function bw({gen:e,data:t,it:{opts:r}},i,n){return(0,K.or)(...i.map((s)=>(0,K.and)(_o(e,t,s,r.ownProperties),K._`${n} = ${s}`)))}B.checkMissingProp=bw;function vw(e,t){e.setParams({missingProperty:t},!0),e.error()}B.reportMissingProp=vw;function eu(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:K._`Object.prototype.hasOwnProperty`})}B.hasPropFunc=eu;function yo(e,t,r){return K._`${eu(e)}.call(${t}, ${r})`}B.isOwnProperty=yo;function ww(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} !== undefined`;return i?K._`${n} && ${yo(e,t,r)}`:n}B.propertyInData=ww;function _o(e,t,r,i){let n=K._`${t}${(0,K.getProperty)(r)} === undefined`;return i?(0,K.or)(n,(0,K.not)(yo(e,t,r))):n}B.noPropertyInData=_o;function tu(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}B.allSchemaProperties=tu;function $w(e,t){return tu(t).filter((r)=>!(0,go.alwaysValidSchema)(e,t[r]))}B.schemaProperties=$w;function Ew({schemaCode:e,data:t,it:{gen:r,topSchemaRef:i,schemaPath:n,errorPath:s},it:o},a,c,u){let l=u?K._`${e}, ${t}, ${i}${n}`:t,d=[[Pt.default.instancePath,(0,K.strConcat)(Pt.default.instancePath,s)],[Pt.default.parentData,o.parentData],[Pt.default.parentDataProperty,o.parentDataProperty],[Pt.default.rootData,Pt.default.rootData]];if(o.opts.dynamicRef)d.push([Pt.default.dynamicAnchors,Pt.default.dynamicAnchors]);let p=K._`${l}, ${r.object(...d)}`;return c!==K.nil?K._`${a}.call(${c}, ${p})`:K._`${a}(${p})`}B.callValidateCode=Ew;var Iw=K._`new RegExp`;function Sw({gen:e,it:{opts:t}},r){let i=t.unicodeRegExp?"u":"",{regExp:n}=t.code,s=n(r,i);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:K._`${n.code==="new RegExp"?Iw:(0,_w.useFunc)(e,n)}(${r}, ${i})`})}B.usePattern=Sw;function xw(e){let{gen:t,data:r,keyword:i,it:n}=e,s=t.name("valid");if(n.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",K._`${r}.length`);t.forRange("i",0,c,(u)=>{e.subschema({keyword:i,dataProp:u,dataPropType:go.Type.Num},s),t.if((0,K.not)(s),a)})}}B.validateArray=xw;function Rw(e){let{gen:t,schema:r,keyword:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>(0,go.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:i,schemaProp:u,compositeRule:!0},a);if(t.assign(o,K._`${o} || ${a}`),!e.mergeValidEvaluated(l,a))t.if((0,K.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}B.validateUnion=Rw});var nu=b(function(Ve){Object.defineProperty(Ve,"__esModule",{value:!0});Ve.validateKeywordUsage=Ve.validSchemaType=Ve.funcKeywordCode=Ve.macroKeywordCode=void 0;var pe=F(),Ft=Re(),Cw=Ce(),jw=Wr();function Fw(e,t){let{gen:r,keyword:i,schema:n,parentSchema:s,it:o}=e,a=t.macro.call(o.self,n,s,o),c=iu(r,i,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:pe.nil,errSchemaPath:`${o.errSchemaPath}/${i}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ve.macroKeywordCode=Fw;function Ow(e,t){var r;let{gen:i,keyword:n,schema:s,parentSchema:o,$data:a,it:c}=e;Aw(c,t);let u=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,l=iu(i,n,u),d=i.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1){if(h(),t.modifying)ru(e);g(()=>e.error())}else{let y=t.async?f():m();if(t.modifying)ru(e);g(()=>Tw(e,y))}}function f(){let y=i.let("ruleErrs",null);return i.try(()=>h(pe._`await `),(P)=>i.assign(d,!1).if(pe._`${P} instanceof ${c.ValidationError}`,()=>i.assign(y,pe._`${P}.errors`),()=>i.throw(P))),y}function m(){let y=pe._`${l}.errors`;return i.assign(y,null),h(pe.nil),y}function h(y=t.async?pe._`await `:pe.nil){let P=c.opts.passContext?Ft.default.this:Ft.default.self,v=!(("compile"in t)&&!a||t.schema===!1);i.assign(d,pe._`${y}${(0,Cw.callValidateCode)(e,l,P,v)}`,t.modifying)}function g(y){var P;i.if((0,pe.not)((P=t.valid)!==null&&P!==void 0?P:d),y)}}Ve.funcKeywordCode=Ow;function ru(e){let{gen:t,data:r,it:i}=e;t.if(i.parentData,()=>t.assign(r,pe._`${i.parentData}[${i.parentDataProperty}]`))}function Tw(e,t){let{gen:r}=e;r.if(pe._`Array.isArray(${t})`,()=>{r.assign(Ft.default.vErrors,pe._`${Ft.default.vErrors} === null ? ${t} : ${Ft.default.vErrors}.concat(${t})`).assign(Ft.default.errors,pe._`${Ft.default.vErrors}.length`),(0,jw.extendErrors)(e)},()=>e.error())}function Aw({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function iu(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,pe.stringify)(r)})}function kw(e,t,r=!1){return!t.length||t.some((i)=>i==="array"?Array.isArray(e):i==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==i||r&&typeof e>"u")}Ve.validSchemaType=kw;function Dw({schema:e,opts:t,self:r,errSchemaPath:i},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw Error("ajv implementation error");let o=n.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema){if(!n.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${i}": `+r.errorsText(n.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}Ve.validateKeywordUsage=Dw});var ou=b(function(bt){Object.defineProperty(bt,"__esModule",{value:!0});bt.extendSubschemaMode=bt.extendSubschemaData=bt.getSubschema=void 0;var Ke=F(),su=D();function Nw(e,{keyword:t,schemaProp:r,schema:i,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&i!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Ke._`${e.schemaPath}${(0,Ke.getProperty)(t)}${(0,Ke.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,su.escapeFragment)(r)}`}}if(i!==void 0){if(n===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:i,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}bt.getSubschema=Nw;function Lw(e,t,{dataProp:r,dataPropType:i,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=t,p=a.let("data",Ke._`${t.data}${(0,Ke.getProperty)(r)}`,!0);c(p),e.errorPath=Ke.str`${u}${(0,su.getErrorPath)(r,i,d.jsPropertySyntax)}`,e.parentDataProperty=Ke._`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(n!==void 0){let u=n instanceof Ke.Name?n:a.let("data",n,!0);if(c(u),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}bt.extendSubschemaData=Lw;function qw(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:i,createErrors:n,allErrors:s}){if(i!==void 0)e.compositeRule=i;if(n!==void 0)e.createErrors=n;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}bt.extendSubschemaMode=qw});var Po=b(function(yA,au){au.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var i,n,s;if(Array.isArray(t)){if(i=t.length,i!=r.length)return!1;for(n=i;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),i=s.length,i!==Object.keys(r).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=i;n--!==0;){var o=s[n];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var cu=b(function(_A,lu){var vt=lu.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var i=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};pn(t,i,n,e,"",e)};vt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function pn(e,t,r,i,n,s,o,a,c,u){if(i&&typeof i=="object"&&!Array.isArray(i)){t(i,n,s,o,a,c,u);for(var l in i){var d=i[l];if(Array.isArray(d)){if(l in vt.arrayKeywords)for(var p=0;p<d.length;p++)pn(e,t,r,d[p],n+"/"+l+"/"+p,s,n,l,i,p)}else if(l in vt.propsKeywords){if(d&&typeof d=="object")for(var f in d)pn(e,t,r,d[f],n+"/"+l+"/"+Mw(f),s,n,l,i,f)}else if(l in vt.keywords||e.allKeys&&!(l in vt.skipKeywords))pn(e,t,r,d,n+"/"+l,s,n,l,i)}r(i,n,s,o,a,c,u)}}function Mw(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Jr=b(function(Pe){Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getSchemaRefs=Pe.resolveUrl=Pe.normalizeId=Pe._getFullPath=Pe.getFullPath=Pe.inlineRef=void 0;var Uw=D(),Bw=Po(),Gw=cu(),Vw=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Kw(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!bo(e);if(!t)return!1;return du(e)<=t}Pe.inlineRef=Kw;var zw=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bo(e){for(let t in e){if(zw.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(bo))return!0;if(typeof r=="object"&&bo(r))return!0}return!1}function du(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,Vw.has(r))continue;if(typeof e[r]=="object")(0,Uw.eachItem)(e[r],(i)=>t+=du(i));if(t===1/0)return 1/0}return t}function uu(e,t="",r){if(r!==!1)t=lr(t);let i=e.parse(t);return pu(e,i)}Pe.getFullPath=uu;function pu(e,t){return e.serialize(t).split("#")[0]+"#"}Pe._getFullPath=pu;var Ww=/#\/?$/;function lr(e){return e?e.replace(Ww,""):""}Pe.normalizeId=lr;function Hw(e,t,r){return r=lr(r),e.resolve(t,r)}Pe.resolveUrl=Hw;var Jw=/^[a-z_][-a-z0-9._]*$/i;function Qw(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:i}=this.opts,n=lr(e[r]||t),s={"":n},o=uu(i,n,!1),a={},c=new Set;return Gw(e,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];if(typeof d[r]=="string")g=y.call(this,d[r]);P.call(this,d.$anchor),P.call(this,d.$dynamicAnchor),s[p]=g;function y(v){let w=this.opts.uriResolver.resolve;if(v=lr(g?w(g,v):v),c.has(v))throw l(v);c.add(v);let I=this.refs[v];if(typeof I=="string")I=this.refs[I];if(typeof I=="object")u(d,I.schema,v);else if(v!==lr(h))if(v[0]==="#")u(d,a[v],v),a[v]=d;else this.refs[v]=h;return v}function P(v){if(typeof v=="string"){if(!Jw.test(v))throw Error(`invalid anchor "${v}"`);y.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Bw(d,p))throw l(f)}function l(d){return Error(`reference "${d}" resolves to more than one schema`)}}Pe.getSchemaRefs=Qw});var cr=b(function(wt){Object.defineProperty(wt,"__esModule",{value:!0});wt.getData=wt.KeywordCxt=wt.validateFunctionCode=void 0;var yu=zd(),fu=Hr(),wo=po(),fn=Hr(),Yw=Zd(),Yr=nu(),vo=ou(),S=F(),j=Re(),Xw=Jr(),st=D(),Qr=Wr();function Zw(e){if(bu(e)){if(vu(e),Pu(e)){r$(e);return}}_u(e,()=>(0,yu.topBoolOrEmptySchema)(e))}wt.validateFunctionCode=Zw;function _u({gen:e,validateName:t,schema:r,schemaEnv:i,opts:n},s){if(n.code.es5)e.func(t,S._`${j.default.data}, ${j.default.valCxt}`,i.$async,()=>{e.code(S._`"use strict"; ${mu(r,n)}`),t$(e,n),e.code(s)});else e.func(t,S._`${j.default.data}, ${e$(n)}`,i.$async,()=>e.code(mu(r,n)).code(s))}function e$(e){return S._`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?S._`, ${j.default.dynamicAnchors}={}`:S.nil}}={}`}function t$(e,t){e.if(j.default.valCxt,()=>{if(e.var(j.default.instancePath,S._`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,S._`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,S._`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,S._`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{if(e.var(j.default.instancePath,S._`""`),e.var(j.default.parentData,S._`undefined`),e.var(j.default.parentDataProperty,S._`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef)e.var(j.default.dynamicAnchors,S._`{}`)})}function r$(e){let{schema:t,opts:r,gen:i}=e;_u(e,()=>{if(r.$comment&&t.$comment)$u(e);if(a$(e),i.let(j.default.vErrors,null),i.let(j.default.errors,0),r.unevaluated)i$(e);wu(e),d$(e)});return}function i$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",S._`${r}.evaluated`),t.if(S._`${e.evaluated}.dynamicProps`,()=>t.assign(S._`${e.evaluated}.props`,S._`undefined`)),t.if(S._`${e.evaluated}.dynamicItems`,()=>t.assign(S._`${e.evaluated}.items`,S._`undefined`))}function mu(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?S._`/*# sourceURL=${r} */`:S.nil}function n$(e,t){if(bu(e)){if(vu(e),Pu(e)){s$(e,t);return}}(0,yu.boolOrEmptySchema)(e,t)}function Pu({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function bu(e){return typeof e.schema!="boolean"}function s$(e,t){let{schema:r,gen:i,opts:n}=e;if(n.$comment&&r.$comment)$u(e);l$(e),c$(e);let s=i.const("_errs",j.default.errors);wu(e,s),i.var(t,S._`${s} === ${j.default.errors}`)}function vu(e){(0,st.checkUnknownRules)(e),o$(e)}function wu(e,t){if(e.opts.jtd)return hu(e,[],!1,t);let r=(0,fu.getSchemaTypes)(e.schema),i=(0,fu.coerceAndCheckDataType)(e,r);hu(e,r,!i,t)}function o$(e){let{schema:t,errSchemaPath:r,opts:i,self:n}=e;if(t.$ref&&i.ignoreKeywordsWithRef&&(0,st.schemaHasRulesButRef)(t,n.RULES))n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function a$(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,st.checkStrictMode)(e,"default is ignored in the schema root")}function l$(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,Xw.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function c$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function $u({gen:e,schemaEnv:t,schema:r,errSchemaPath:i,opts:n}){let s=r.$comment;if(n.$comment===!0)e.code(S._`${j.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){let o=S.str`${i}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(S._`${j.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function d$(e){let{gen:t,schemaEnv:r,validateName:i,ValidationError:n,opts:s}=e;if(r.$async)t.if(S._`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw(S._`new ${n}(${j.default.vErrors})`));else{if(t.assign(S._`${i}.errors`,j.default.vErrors),s.unevaluated)u$(e);t.return(S._`${j.default.errors} === 0`)}}function u$({gen:e,evaluated:t,props:r,items:i}){if(r instanceof S.Name)e.assign(S._`${t}.props`,r);if(i instanceof S.Name)e.assign(S._`${t}.items`,i)}function hu(e,t,r,i){let{gen:n,schema:s,data:o,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,st.schemaHasRulesButRef)(s,l))){n.block(()=>Iu(e,"$ref",l.all.$ref.definition));return}if(!c.jtd)p$(e,t);n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){if(!(0,wo.shouldUseGroup)(s,p))return;if(p.type){if(n.if((0,fn.checkDataType)(p.type,o,c.strictNumbers)),gu(e,p),t.length===1&&t[0]===p.type&&r)n.else(),(0,fn.reportTypeError)(e);n.endIf()}else gu(e,p);if(!a)n.if(S._`${j.default.errors} === ${i||0}`)}}function gu(e,t){let{gen:r,schema:i,opts:{useDefaults:n}}=e;if(n)(0,Yw.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,wo.shouldUseRule)(i,s))Iu(e,s.keyword,s.definition,t.type)})}function p$(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(f$(e,t),!e.opts.allowUnionTypes)m$(e,t);h$(e,e.dataTypes)}function f$(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!Eu(e.dataTypes,r))$o(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),y$(e,t)}function m$(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))$o(e,"use allowUnionTypes to allow union type keyword")}function h$(e,t){let r=e.self.RULES.all;for(let i in r){let n=r[i];if(typeof n=="object"&&(0,wo.shouldUseRule)(e.schema,n)){let{type:s}=n.definition;if(s.length&&!s.some((o)=>g$(t,o)))$o(e,`missing type "${s.join(",")}" for keyword "${i}"`)}}}function g$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Eu(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function y$(e,t){let r=[];for(let i of e.dataTypes)if(Eu(t,i))r.push(i);else if(t.includes("integer")&&i==="number")r.push("integer");e.dataTypes=r}function $o(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,st.checkStrictMode)(e,t,e.opts.strictTypes)}class Eo{constructor(e,t,r){if((0,Yr.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,st.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Su(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Yr.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",j.default.errors)}result(e,t,r){this.failResult((0,S.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,S.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(S._`${t} !== undefined && (${(0,S.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?Qr.reportExtraError:Qr.reportError)(this,this.def.error,t)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Qr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=S.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=S.nil,t=S.nil){if(!this.$data)return;let{gen:r,schemaCode:i,schemaType:n,def:s}=this;if(r.if((0,S.or)(S._`${i} === undefined`,t)),e!==S.nil)r.assign(e,!0);if(n.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==S.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:i,it:n}=this;return(0,S.or)(s(),o());function s(){if(r.length){if(!(t instanceof S.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return S._`${(0,fn.checkDataTypes)(a,t,n.opts.strictNumbers,fn.DataType.Wrong)}`}return S.nil}function o(){if(i.validateSchema){let a=e.scopeValue("validate$data",{ref:i.validateSchema});return S._`!${a}(${t})`}return S.nil}}subschema(e,t){let r=(0,vo.getSubschema)(this.it,e);(0,vo.extendSubschemaData)(r,this.it,e),(0,vo.extendSubschemaMode)(r,e);let i={...this.it,...r,items:void 0,props:void 0};return n$(i,t),i}mergeEvaluated(e,t){let{it:r,gen:i}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=st.mergeEvaluated.props(i,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=st.mergeEvaluated.items(i,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:i}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,S.Name)),!0}}wt.KeywordCxt=Eo;function Iu(e,t,r,i){let n=new Eo(e,r,t);if("code"in r)r.code(n,i);else if(n.$data&&r.validate)(0,Yr.funcKeywordCode)(n,r);else if("macro"in r)(0,Yr.macroKeywordCode)(n,r);else if(r.compile||r.validate)(0,Yr.funcKeywordCode)(n,r)}var _$=/^\/(?:[^~]|~0|~1)*$/,P$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Su(e,{dataLevel:t,dataNames:r,dataPathArr:i}){let n,s;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!_$.test(e))throw Error(`Invalid JSON-pointer: ${e}`);n=e,s=j.default.rootData}else{let u=P$.exec(e);if(!u)throw Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=t)throw Error(c("property/index",l));return i[t-l]}if(l>t)throw Error(c("data",l));if(s=r[t-l],!n)return s}let o=s,a=n.split("/");for(let u of a)if(u)s=S._`${s}${(0,S.getProperty)((0,st.unescapeJsonPointer)(u))}`,o=S._`${o} && ${s}`;return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}wt.getData=Su});var Xr=b(function(Io){Object.defineProperty(Io,"__esModule",{value:!0});class xu extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Io.default=xu});var dr=b(function(xo){Object.defineProperty(xo,"__esModule",{value:!0});var So=Jr();class Ru extends Error{constructor(e,t,r,i){super(i||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,So.resolveUrl)(e,t,r),this.missingSchema=(0,So.normalizeId)((0,So.getFullPath)(e,this.missingRef))}}xo.default=Ru});var ei=b(function(je){Object.defineProperty(je,"__esModule",{value:!0});je.resolveSchema=je.getCompilingSchema=je.resolveRef=je.compileSchema=je.SchemaEnv=void 0;var Le=F(),b$=Xr(),Ot=Re(),qe=Jr(),Cu=D(),v$=cr();class Zr{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,qe.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}je.SchemaEnv=Zr;function Co(e){let t=ju.call(this,e);if(t)return t;let r=(0,qe.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:i,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Le.CodeGen(this.scope,{es5:i,lines:n,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:b$.default,code:Le._`require("ajv/dist/runtime/validation_error").default`});let c=o.scopeName("validate");e.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Ot.default.data,parentData:Ot.default.parentData,parentDataProperty:Ot.default.parentDataProperty,dataNames:[Ot.default.data],dataPathArr:[Le.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Le.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Le.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:Le._`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,v$.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();if(l=`${o.scopeRefs(Ot.default.scope)}return ${d}`,this.opts.code.process)l=this.opts.code.process(l,e);let f=Function(`${Ot.default.self}`,`${Ot.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:c,validateCode:d,scopeValues:o._values};if(this.opts.unevaluated){let{props:m,items:h}=u;if(f.evaluated={props:m instanceof Le.Name?void 0:m,items:h instanceof Le.Name?void 0:h,dynamicProps:m instanceof Le.Name,dynamicItems:h instanceof Le.Name},f.source)f.source.evaluated=(0,Le.stringify)(f.evaluated)}return e.validate=f,e}catch(d){if(delete e.validate,delete e.validateName,l)this.logger.error("Error compiling schema, function code:",l);throw d}finally{this._compilations.delete(e)}}je.compileSchema=Co;function w$(e,t,r){var i;r=(0,qe.resolveUrl)(this.opts.uriResolver,t,r);let n=e.refs[r];if(n)return n;let s=I$.call(this,e,r);if(s===void 0){let o=(i=e.localRefs)===null||i===void 0?void 0:i[r],{schemaId:a}=this.opts;if(o)s=new Zr({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=$$.call(this,s)}je.resolveRef=w$;function $$(e){if((0,qe.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Co.call(this,e)}function ju(e){for(let t of this._compilations)if(E$(t,e))return t}je.getCompilingSchema=ju;function E$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function I$(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||mn.call(this,e,t)}function mn(e,t){let r=this.opts.uriResolver.parse(t),i=(0,qe._getFullPath)(this.opts.uriResolver,r),n=(0,qe.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&i===n)return Ro.call(this,r,e);let s=(0,qe.normalizeId)(i),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=mn.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Ro.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Co.call(this,o);if(s===(0,qe.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];if(u)n=(0,qe.resolveUrl)(this.opts.uriResolver,n,u);return new Zr({schema:a,schemaId:c,root:e,baseId:n})}return Ro.call(this,r,o)}je.resolveSchema=mn;var S$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ro(e,{baseId:t,schema:r,root:i}){var n;if(((n=e.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[(0,Cu.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r==="object"&&r[this.opts.schemaId];if(!S$.has(a)&&u)t=(0,qe.resolveUrl)(this.opts.uriResolver,t,u)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cu.schemaHasRulesButRef)(r,this.RULES)){let a=(0,qe.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=mn.call(this,i,a)}let{schemaId:o}=this.opts;if(s=s||new Zr({schema:r,schemaId:o,root:i,baseId:t}),s.schema!==s.root.schema)return s;return}});var Fu=b(function(EA,x$){x$.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Fo=b(function(IA,ku){var R$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function jo(e){let t="",r=0,i=0;for(i=0;i<e.length;i++){if(r=e[i].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i];break}for(i+=1;i<e.length;i++){if(r=e[i].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[i]}return t}var C$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ou(e){return e.length=0,!0}function j$(e,t,r){if(e.length){let i=jo(e);if(i!=="")t.push(i);else return r.error=!0,!1;e.length=0}return!0}function F$(e){let t=0,r={error:!1,address:"",zone:""},i=[],n=[],s=!1,o=!1,a=j$;for(let c=0;c<e.length;c++){let u=e[c];if(u==="["||u==="]")continue;if(u===":"){if(s===!0)o=!0;if(!a(n,i,r))break;if(++t>7){r.error=!0;break}if(c>0&&e[c-1]===":")s=!0;i.push(":");continue}else if(u==="%"){if(!a(n,i,r))break;a=Ou}else{n.push(u);continue}}if(n.length)if(a===Ou)r.zone=n.join("");else if(o)i.push(n.join(""));else i.push(jo(n));return r.address=i.join(""),r}function Au(e){if(O$(e,":")<2)return{host:e,isIPV6:!1};let t=F$(e);if(!t.error){let{address:r,address:i}=t;if(t.zone)r+="%"+t.zone,i+="%25"+t.zone;return{host:r,isIPV6:!0,escapedHost:i}}else return{host:e,isIPV6:!1}}function O$(e,t){let r=0;for(let i=0;i<e.length;i++)if(e[i]===t)r++;return r}function T$(e){let t=e,r=[],i=-1,n=0;while(n=t.length){if(n===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(n===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(n===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((i=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,i)),t=t.slice(i)}return r.join("")}function A$(e,t){let r=t!==!0?escape:unescape;if(e.scheme!==void 0)e.scheme=r(e.scheme);if(e.userinfo!==void 0)e.userinfo=r(e.userinfo);if(e.host!==void 0)e.host=r(e.host);if(e.path!==void 0)e.path=r(e.path);if(e.query!==void 0)e.query=r(e.query);if(e.fragment!==void 0)e.fragment=r(e.fragment);return e}function k$(e){let t=[];if(e.userinfo!==void 0)t.push(e.userinfo),t.push("@");if(e.host!==void 0){let r=unescape(e.host);if(!Tu(r)){let i=Au(r);if(i.isIPV6===!0)r=`[${i.escapedHost}]`;else r=e.host}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string")t.push(":"),t.push(String(e.port));return t.length?t.join(""):void 0}ku.exports={nonSimpleDomain:C$,recomposeAuthority:k$,normalizeComponentEncoding:A$,removeDotSegments:T$,isIPv4:Tu,isUUID:R$,normalizeIPv6:Au,stringArrayToHexStripped:jo}});var Mu=b(function(SA,qu){var{isUUID:D$}=Fo(),N$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,L$=["http","https","ws","wss","urn","urn:uuid"];function q$(e){return L$.indexOf(e)!==-1}function Oo(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function Du(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function Nu(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function M$(e){return e.secure=Oo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function U$(e){if(e.port===(Oo(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function B$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(N$);if(r){let i=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let n=`${i}:${t.nid||e.nid}`,s=To(n);if(e.path=void 0,s)e=s.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function G$(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",i=e.nid.toLowerCase(),n=`${r}:${t.nid||i}`,s=To(n);if(s)e=s.serialize(e,t);let o=e,a=e.nss;return o.path=`${i||t.nid}:${a}`,t.skipEscape=!0,o}function V$(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!D$(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function K$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Lu={scheme:"http",domainHost:!0,parse:Du,serialize:Nu},z$={scheme:"https",domainHost:Lu.domainHost,parse:Du,serialize:Nu},hn={scheme:"ws",domainHost:!0,parse:M$,serialize:U$},W$={scheme:"wss",domainHost:hn.domainHost,parse:hn.parse,serialize:hn.serialize},H$={scheme:"urn",parse:B$,serialize:G$,skipNormalize:!0},J$={scheme:"urn:uuid",parse:V$,serialize:K$,skipNormalize:!0},gn={http:Lu,https:z$,ws:hn,wss:W$,urn:H$,"urn:uuid":J$};Object.setPrototypeOf(gn,null);function To(e){return e&&(gn[e]||gn[e.toLowerCase()])||void 0}qu.exports={wsIsSecure:Oo,SCHEMES:gn,isValidSchemeName:q$,getSchemeHandler:To}});var Gu=b(function(xA,_n){var{normalizeIPv6:Q$,removeDotSegments:ti,recomposeAuthority:Y$,normalizeComponentEncoding:yn,isIPv4:X$,nonSimpleDomain:Z$}=Fo(),{SCHEMES:eE,getSchemeHandler:Uu}=Mu();function tE(e,t){if(typeof e==="string")e=ze(ot(e,t),t);else if(typeof e==="object")e=ot(ze(e,t),t);return e}function rE(e,t,r){let i=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=Bu(ot(e,i),ot(t,i),i,!0);return i.skipEscape=!0,ze(n,i)}function Bu(e,t,r,i){let n={};if(!i)e=ot(ze(e,r),r),t=ot(ze(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=ti(t.path||""),n.query=t.query;else{if(!t.path)if(n.path=e.path,t.query!==void 0)n.query=t.query;else n.query=e.query;else{if(t.path[0]==="/")n.path=ti(t.path);else{if((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path)n.path="/"+t.path;else if(!e.path)n.path=t.path;else n.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;n.path=ti(n.path)}n.query=t.query}n.userinfo=e.userinfo,n.host=e.host,n.port=e.port}n.scheme=e.scheme}return n.fragment=t.fragment,n}function iE(e,t,r){if(typeof e==="string")e=unescape(e),e=ze(yn(ot(e,r),!0),{...r,skipEscape:!0});else if(typeof e==="object")e=ze(yn(e,!0),{...r,skipEscape:!0});if(typeof t==="string")t=unescape(t),t=ze(yn(ot(t,r),!0),{...r,skipEscape:!0});else if(typeof t==="object")t=ze(yn(t,!0),{...r,skipEscape:!0});return e.toLowerCase()===t.toLowerCase()}function ze(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},i=Object.assign({},t),n=[],s=Uu(i.scheme||r.scheme);if(s&&s.serialize)s.serialize(r,i);if(r.path!==void 0)if(!i.skipEscape){if(r.path=escape(r.path),r.scheme!==void 0)r.path=r.path.split("%3A").join(":")}else r.path=unescape(r.path);if(i.reference!=="suffix"&&r.scheme)n.push(r.scheme,":");let o=Y$(r);if(o!==void 0){if(i.reference!=="suffix")n.push("//");if(n.push(o),r.path&&r.path[0]!=="/")n.push("/")}if(r.path!==void 0){let a=r.path;if(!i.absolutePath&&(!s||!s.absolutePath))a=ti(a);if(o===void 0&&a[0]==="/"&&a[1]==="/")a="/%2F"+a.slice(2);n.push(a)}if(r.query!==void 0)n.push("?",r.query);if(r.fragment!==void 0)n.push("#",r.fragment);return n.join("")}var nE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ot(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let s=e.match(nE);if(s){if(i.scheme=s[1],i.userinfo=s[3],i.host=s[4],i.port=parseInt(s[5],10),i.path=s[6]||"",i.query=s[7],i.fragment=s[8],isNaN(i.port))i.port=s[5];if(i.host)if(X$(i.host)===!1){let c=Q$(i.host);i.host=c.host.toLowerCase(),n=c.isIPV6}else n=!0;if(i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path)i.reference="same-document";else if(i.scheme===void 0)i.reference="relative";else if(i.fragment===void 0)i.reference="absolute";else i.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==i.reference)i.error=i.error||"URI is not a "+r.reference+" reference.";let o=Uu(r.scheme||i.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)){if(i.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&Z$(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(a){i.error=i.error||"Host's domain name can not be converted to ASCII: "+a}}if(!o||o&&!o.skipNormalize){if(e.indexOf("%")!==-1){if(i.scheme!==void 0)i.scheme=unescape(i.scheme);if(i.host!==void 0)i.host=unescape(i.host)}if(i.path)i.path=escape(unescape(i.path));if(i.fragment)i.fragment=encodeURI(decodeURIComponent(i.fragment))}if(o&&o.parse)o.parse(i,r)}else i.error=i.error||"URI can not be parsed.";return i}var Ao={SCHEMES:eE,normalize:tE,resolve:rE,resolveComponent:Bu,equal:iE,serialize:ze,parse:ot};_n.exports=Ao;_n.exports.default=Ao;_n.exports.fastUri=Ao});var Ku=b(function(ko){Object.defineProperty(ko,"__esModule",{value:!0});var Vu=Gu();Vu.code='require("ajv/dist/runtime/uri").default';ko.default=Vu});var Lo=b(function(ie){Object.defineProperty(ie,"__esModule",{value:!0});ie.CodeGen=ie.Name=ie.nil=ie.stringify=ie.str=ie._=ie.KeywordCxt=void 0;var sE=cr();Object.defineProperty(ie,"KeywordCxt",{enumerable:!0,get:function(){return sE.KeywordCxt}});var ur=F();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return ur._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return ur.str}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return ur.stringify}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return ur.nil}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return ur.Name}});Object.defineProperty(ie,"CodeGen",{enumerable:!0,get:function(){return ur.CodeGen}});var oE=Xr(),Qu=dr(),aE=uo(),ri=ei(),lE=F(),ii=Jr(),Pn=Hr(),No=D(),zu=Fu(),cE=Ku(),Yu=(e,t)=>new RegExp(e,t);Yu.code="new RegExp";var dE=["removeAdditional","useDefaults","coerceTypes"],uE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),pE={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},fE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wu=200;function mE(e){var t,r,i,n,s,o,a,c,u,l,d,p,f,m,h,g,y,P,v,w,I,E,x,T,R;let V=e.strict,J=(t=e.code)===null||t===void 0?void 0:t.optimize,X=J===!0||J===void 0?1:J||0,Se=(i=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&i!==void 0?i:Yu,qr=(n=e.uriResolver)!==null&&n!==void 0?n:cE.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:V)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:V)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:V)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:X,regExp:Se}:{optimize:X,regExp:Se},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:Wu,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:Wu,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(P=e.messages)!==null&&P!==void 0?P:!0,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(I=e.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(x=e.validateFormats)!==null&&x!==void 0?x:!0,unicodeRegExp:(T=e.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(R=e.int32range)!==null&&R!==void 0?R:!0,uriResolver:qr}}class bn{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...mE(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new lE.ValueScope({scope:{},prefixes:uE,es5:t,lines:r}),this.logger=bE(e.logger);let i=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,aE.getRules)(),Hu.call(this,pE,e,"NOT SUPPORTED"),Hu.call(this,fE,e,"DEPRECATED","warn"),this._metaOpts=_E.call(this),e.formats)gE.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)yE.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);hE.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,i=zu;if(r==="id")i={...zu},i.id=i.$id,delete i.$id;if(t&&e)this.addMetaSchema(i,i[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let i=r(t);if(!("$async"in r))this.errors=r.errors;return i}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return i.call(this,e,t);async function i(u,l){await n.call(this,u.$schema);let d=this._addSchema(u,l);return d.validate||s.call(this,d)}async function n(u){if(u&&!this.getSchema(u))await i.call(this,{$ref:u},!0)}async function s(u){try{return this._compileSchemaEnv(u)}catch(l){if(!(l instanceof Qu.default))throw l;return o.call(this,l),await a.call(this,l.missingSchema),s.call(this,u)}}function o({missingSchema:u,missingRef:l}){if(this.refs[u])throw Error(`AnySchema ${u} is loaded but ${l} cannot be resolved`)}async function a(u){let l=await c.call(this,u);if(!this.refs[u])await n.call(this,l.$schema);if(!this.refs[u])this.addSchema(l,u,t)}async function c(u){let l=this._loading[u];if(l)return l;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,t,r,i=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,i);return this}let n;if(typeof e==="object"){let{schemaId:s}=this.opts;if(n=e[s],n!==void 0&&typeof n!="string")throw Error(`schema ${s} must be string`)}return t=(0,ii.normalizeId)(t||n),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,i,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(r,e);if(!i&&t){let n="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(n);else throw Error(n)}return i}getSchema(e){let t;while(typeof(t=Ju.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,i=new ri.SchemaEnv({schema:{},schemaId:r});if(t=ri.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Ju.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=(0,ii.normalizeId)(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(wE.call(this,r,t),!t)return(0,No.eachItem)(r,(n)=>Do.call(this,n)),this;EE.call(this,t);let i={...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)};return(0,No.eachItem)(r,i.type.length===0?(n)=>Do.call(this,n,i):(n)=>i.type.forEach((s)=>Do.call(this,n,i,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let i=r.rules.findIndex((n)=>n.keyword===e);if(i>=0)r.rules.splice(i,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((i)=>`${r}${i.instancePath} ${i.message}`).reduce((i,n)=>i+t+n)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let n=i.split("/").slice(1),s=e;for(let o of n)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:c}=a.definition,u=s[o];if(c&&u)s[o]=Xu(u)}}return e}_removeAllSchemas(e,t){for(let r in e){let i=e[r];if(!t||t.test(r)){if(typeof i=="string")delete e[r];else if(i&&!i.meta)this._cache.delete(i.schema),delete e[r]}}}_addSchema(e,t,r,i=this.opts.validateSchema,n=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=(0,ii.normalizeId)(s||r);let c=ii.getSchemaRefs.call(this,e,r);if(a=new ri.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),n&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(i)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else ri.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{ri.compileSchema.call(this,e)}finally{this.opts=t}}}bn.ValidationError=oE.default;bn.MissingRefError=Qu.default;ie.default=bn;function Hu(e,t,r,i="error"){for(let n in e){let s=n;if(s in t)this.logger[i](`${r}: option ${n}. ${e[s]}`)}}function Ju(e){return e=(0,ii.normalizeId)(e),this.schemas[e]||this.refs[e]}function hE(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function gE(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function yE(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function _E(){let e={...this.opts};for(let t of dE)delete e[t];return e}var PE={log(){},warn(){},error(){}};function bE(e){if(e===!1)return PE;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var vE=/^[a-z_$][a-z0-9_$:-]*$/i;function wE(e,t){let{RULES:r}=this;if((0,No.eachItem)(e,(i)=>{if(r.keywords[i])throw Error(`Keyword ${i} is already defined`);if(!vE.test(i))throw Error(`Keyword ${i} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function Do(e,t,r){var i;let n=t===null||t===void 0?void 0:t.post;if(r&&n)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=n?s.post:s.rules.find(({type:c})=>c===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Pn.getJSONTypes)(t.type),schemaType:(0,Pn.getJSONTypes)(t.schemaType)}};if(t.before)$E.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(i=t.implements)===null||i===void 0||i.forEach((c)=>this.addKeyword(c))}function $E(e,t,r){let i=e.rules.findIndex((n)=>n.keyword===r);if(i>=0)e.rules.splice(i,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function EE(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=Xu(t);e.validateSchema=this.compile(t,!0)}var IE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xu(e){return{anyOf:[e,IE]}}});var Zu=b(function(qo){Object.defineProperty(qo,"__esModule",{value:!0});var SE={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qo.default=SE});var $n=b(function(Tt){Object.defineProperty(Tt,"__esModule",{value:!0});Tt.callRef=Tt.getValidate=void 0;var xE=dr(),ep=Ce(),be=F(),pr=Re(),tp=ei(),vn=D(),RE={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:i}=e,{baseId:n,schemaEnv:s,validateName:o,opts:a,self:c}=i,{root:u}=s;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=tp.resolveRef.call(c,u,n,r);if(l===void 0)throw new xE.default(i.opts.uriResolver,n,r);if(l instanceof tp.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return wn(e,o,s,s.$async);let m=t.scopeValue("root",{ref:u});return wn(e,be._`${m}.validate`,u,u.$async)}function p(m){let h=rp(e,m);wn(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,be.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:be.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function rp(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):be._`${r.scopeValue("wrapper",{ref:t})}.validate`}Tt.getValidate=rp;function wn(e,t,r,i){let{gen:n,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,u=c.passContext?pr.default.this:be.nil;if(i)l();else d();function l(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=n.let("valid");n.try(()=>{if(n.code(be._`await ${(0,ep.callValidateCode)(e,t,u)}`),f(t),!o)n.assign(m,!0)},(h)=>{if(n.if(be._`!(${h} instanceof ${s.ValidationError})`,()=>n.throw(h)),p(h),!o)n.assign(m,!1)}),e.ok(m)}function d(){e.result((0,ep.callValidateCode)(e,t,u),()=>f(t),()=>p(t))}function p(m){let h=be._`${m}.errors`;n.assign(pr.default.vErrors,be._`${pr.default.vErrors} === null ? ${h} : ${pr.default.vErrors}.concat(${h})`),n.assign(pr.default.errors,be._`${pr.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)s.props=vn.mergeEvaluated.props(n,g.props,s.props)}else{let y=n.var("props",be._`${m}.evaluated.props`);s.props=vn.mergeEvaluated.props(n,y,s.props,be.Name)}if(s.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)s.items=vn.mergeEvaluated.items(n,g.items,s.items)}else{let y=n.var("items",be._`${m}.evaluated.items`);s.items=vn.mergeEvaluated.items(n,y,s.items,be.Name)}}}Tt.callRef=wn;Tt.default=RE});var Uo=b(function(Mo){Object.defineProperty(Mo,"__esModule",{value:!0});var CE=Zu(),jE=$n(),FE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CE.default,jE.default];Mo.default=FE});var ip=b(function(Bo){Object.defineProperty(Bo,"__esModule",{value:!0});var En=F(),$t=En.operators,In={maximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},minimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},exclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},exclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},OE={message:({keyword:e,schemaCode:t})=>En.str`must be ${In[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>En._`{comparison: ${In[e].okStr}, limit: ${t}}`},TE={keyword:Object.keys(In),type:"number",schemaType:"number",$data:!0,error:OE,code(e){let{keyword:t,data:r,schemaCode:i}=e;e.fail$data(En._`${r} ${In[t].fail} ${i} || isNaN(${r})`)}};Bo.default=TE});var np=b(function(Go){Object.defineProperty(Go,"__esModule",{value:!0});var ni=F(),AE={message:({schemaCode:e})=>ni.str`must be multiple of ${e}`,params:({schemaCode:e})=>ni._`{multipleOf: ${e}}`},kE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AE,code(e){let{gen:t,data:r,schemaCode:i,it:n}=e,s=n.opts.multipleOfPrecision,o=t.let("res"),a=s?ni._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:ni._`${o} !== parseInt(${o})`;e.fail$data(ni._`(${i} === 0 || (${o} = ${r}/${i}, ${a}))`)}};Go.default=kE});var op=b(function(Vo){Object.defineProperty(Vo,"__esModule",{value:!0});function sp(e){let t=e.length,r=0,i=0,n;while(i<t)if(r++,n=e.charCodeAt(i++),n>=55296&&n<=56319&&i<t){if(n=e.charCodeAt(i),(n&64512)===56320)i++}return r}Vo.default=sp;sp.code='require("ajv/dist/runtime/ucs2length").default'});var ap=b(function(Ko){Object.defineProperty(Ko,"__esModule",{value:!0});var At=F(),DE=D(),NE=op(),LE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return At.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>At._`{limit: ${e}}`},qE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LE,code(e){let{keyword:t,data:r,schemaCode:i,it:n}=e,s=t==="maxLength"?At.operators.GT:At.operators.LT,o=n.opts.unicode===!1?At._`${r}.length`:At._`${(0,DE.useFunc)(e.gen,NE.default)}(${r})`;e.fail$data(At._`${o} ${s} ${i}`)}};Ko.default=qE});var lp=b(function(zo){Object.defineProperty(zo,"__esModule",{value:!0});var ME=Ce(),Sn=F(),UE={message:({schemaCode:e})=>Sn.str`must match pattern "${e}"`,params:({schemaCode:e})=>Sn._`{pattern: ${e}}`},BE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UE,code(e){let{data:t,$data:r,schema:i,schemaCode:n,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?Sn._`(new RegExp(${n}, ${o}))`:(0,ME.usePattern)(e,i);e.fail$data(Sn._`!${a}.test(${t})`)}};zo.default=BE});var cp=b(function(Wo){Object.defineProperty(Wo,"__esModule",{value:!0});var si=F(),GE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return si.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>si._`{limit: ${e}}`},VE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxProperties"?si.operators.GT:si.operators.LT;e.fail$data(si._`Object.keys(${r}).length ${n} ${i}`)}};Wo.default=VE});var dp=b(function(Ho){Object.defineProperty(Ho,"__esModule",{value:!0});var oi=Ce(),ai=F(),KE=D(),zE={message:({params:{missingProperty:e}})=>ai.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>ai._`{missingProperty: ${e}}`},WE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:zE,code(e){let{gen:t,schema:r,schemaCode:i,data:n,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors)u();else l();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,KE.checkStrictMode)(o,y,o.opts.strictRequired)}}function u(){if(c||s)e.block$data(ai.nil,d);else for(let f of r)(0,oi.checkReportMissingProp)(e,f)}function l(){let f=t.let("missing");if(c||s){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if((0,oi.checkMissingProp)(e,r,f)),(0,oi.reportMissingProp)(e,f),t.else()}function d(){t.forOf("prop",i,(f)=>{e.setParams({missingProperty:f}),t.if((0,oi.noPropertyInData)(t,n,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,i,()=>{t.assign(m,(0,oi.propertyInData)(t,n,f,a.ownProperties)),t.if((0,ai.not)(m),()=>{e.error(),t.break()})},ai.nil)}}};Ho.default=WE});var up=b(function(Jo){Object.defineProperty(Jo,"__esModule",{value:!0});var li=F(),HE={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return li.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>li._`{limit: ${e}}`},JE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:HE,code(e){let{keyword:t,data:r,schemaCode:i}=e,n=t==="maxItems"?li.operators.GT:li.operators.LT;e.fail$data(li._`${r}.length ${n} ${i}`)}};Jo.default=JE});var xn=b(function(Qo){Object.defineProperty(Qo,"__esModule",{value:!0});var pp=Po();pp.code='require("ajv/dist/runtime/equal").default';Qo.default=pp});var fp=b(function(Xo){Object.defineProperty(Xo,"__esModule",{value:!0});var Yo=Hr(),ne=F(),QE=D(),YE=xn(),XE={message:({params:{i:e,j:t}})=>ne.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>ne._`{i: ${e}, j: ${t}}`},ZE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XE,code(e){let{gen:t,data:r,$data:i,schema:n,parentSchema:s,schemaCode:o,it:a}=e;if(!i&&!n)return;let c=t.let("valid"),u=s.items?(0,Yo.getSchemaTypes)(s.items):[];e.block$data(c,l,ne._`${o} === false`),e.ok(c);function l(){let m=t.let("i",ne._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if(ne._`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),y=(0,Yo.checkDataTypes)(u,g,a.opts.strictNumbers,Yo.DataType.Wrong),P=t.const("indices",ne._`{}`);t.for(ne._`;${m}--;`,()=>{if(t.let(g,ne._`${r}[${m}]`),t.if(y,ne._`continue`),u.length>1)t.if(ne._`typeof ${g} == "string"`,ne._`${g} += "_"`);t.if(ne._`typeof ${P}[${g}] == "number"`,()=>{t.assign(h,ne._`${P}[${g}]`),e.error(),t.assign(c,!1).break()}).code(ne._`${P}[${g}] = ${m}`)})}function f(m,h){let g=(0,QE.useFunc)(t,YE.default),y=t.name("outer");t.label(y).for(ne._`;${m}--;`,()=>t.for(ne._`${h} = ${m}; ${h}--;`,()=>t.if(ne._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};Xo.default=ZE});var mp=b(function(ea){Object.defineProperty(ea,"__esModule",{value:!0});var Zo=F(),eI=D(),tI=xn(),rI={message:"must be equal to constant",params:({schemaCode:e})=>Zo._`{allowedValue: ${e}}`},iI={keyword:"const",$data:!0,error:rI,code(e){let{gen:t,data:r,$data:i,schemaCode:n,schema:s}=e;if(i||s&&typeof s=="object")e.fail$data(Zo._`!${(0,eI.useFunc)(t,tI.default)}(${r}, ${n})`);else e.fail(Zo._`${s} !== ${r}`)}};ea.default=iI});var hp=b(function(ta){Object.defineProperty(ta,"__esModule",{value:!0});var ci=F(),nI=D(),sI=xn(),oI={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>ci._`{allowedValues: ${e}}`},aI={keyword:"enum",schemaType:"array",$data:!0,error:oI,code(e){let{gen:t,data:r,$data:i,schema:n,schemaCode:s,it:o}=e;if(!i&&n.length===0)throw Error("enum must have non-empty array");let a=n.length>=o.opts.loopEnum,c,u=()=>c!==null&&c!==void 0?c:c=(0,nI.useFunc)(t,sI.default),l;if(a||i)l=t.let("valid"),e.block$data(l,d);else{if(!Array.isArray(n))throw Error("ajv implementation error");let f=t.const("vSchema",s);l=(0,ci.or)(...n.map((m,h)=>p(f,h)))}e.pass(l);function d(){t.assign(l,!1),t.forOf("v",s,(f)=>t.if(ci._`${u()}(${r}, ${f})`,()=>t.assign(l,!0).break()))}function p(f,m){let h=n[m];return typeof h==="object"&&h!==null?ci._`${u()}(${r}, ${f}[${m}])`:ci._`${r} === ${h}`}}};ta.default=aI});var ia=b(function(ra){Object.defineProperty(ra,"__esModule",{value:!0});var lI=ip(),cI=np(),dI=ap(),uI=lp(),pI=cp(),fI=dp(),mI=up(),hI=fp(),gI=mp(),yI=hp(),_I=[lI.default,cI.default,dI.default,uI.default,pI.default,fI.default,mI.default,hI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},gI.default,yI.default];ra.default=_I});var sa=b(function(di){Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var kt=F(),na=D(),PI={message:({params:{len:e}})=>kt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>kt._`{limit: ${e}}`},bI={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PI,code(e){let{parentSchema:t,it:r}=e,{items:i}=t;if(!Array.isArray(i)){(0,na.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gp(e,i)}};function gp(e,t){let{gen:r,schema:i,data:n,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",kt._`${n}.length`);if(i===!1)e.setParams({len:t.length}),e.pass(kt._`${a} <= ${t.length}`);else if(typeof i=="object"&&!(0,na.alwaysValidSchema)(o,i)){let u=r.var("valid",kt._`${a} <= ${t.length}`);r.if((0,kt.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,(l)=>{if(e.subschema({keyword:s,dataProp:l,dataPropType:na.Type.Num},u),!o.allErrors)r.if((0,kt.not)(u),()=>r.break())})}}di.validateAdditionalItems=gp;di.default=bI});var oa=b(function(ui){Object.defineProperty(ui,"__esModule",{value:!0});ui.validateTuple=void 0;var yp=F(),Rn=D(),vI=Ce(),wI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return _p(e,"additionalItems",t);if(r.items=!0,(0,Rn.alwaysValidSchema)(r,t))return;e.ok((0,vI.validateArray)(e))}};function _p(e,t,r=e.schema){let{gen:i,parentSchema:n,data:s,keyword:o,it:a}=e;if(l(n),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=Rn.mergeEvaluated.items(i,r.length,a.items);let c=i.name("valid"),u=i.const("len",yp._`${s}.length`);r.forEach((d,p)=>{if((0,Rn.alwaysValidSchema)(a,d))return;i.if(yp._`${u} > ${p}`,()=>e.subschema({keyword:o,schemaProp:p,dataProp:p},c)),e.ok(c)});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0,Rn.checkStrictMode)(a,g,p.strictTuples)}}}ui.validateTuple=_p;ui.default=wI});var Pp=b(function(aa){Object.defineProperty(aa,"__esModule",{value:!0});var $I=oa(),EI={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,$I.validateTuple)(e,"items")};aa.default=EI});var vp=b(function(la){Object.defineProperty(la,"__esModule",{value:!0});var bp=F(),II=D(),SI=Ce(),xI=sa(),RI={message:({params:{len:e}})=>bp.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>bp._`{limit: ${e}}`},CI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RI,code(e){let{schema:t,parentSchema:r,it:i}=e,{prefixItems:n}=r;if(i.items=!0,(0,II.alwaysValidSchema)(i,t))return;if(n)(0,xI.validateAdditionalItems)(e,n);else e.ok((0,SI.validateArray)(e))}};la.default=CI});var wp=b(function(ca){Object.defineProperty(ca,"__esModule",{value:!0});var Fe=F(),Cn=D(),jI={message:({params:{min:e,max:t}})=>t===void 0?Fe.str`must contain at least ${e} valid item(s)`:Fe.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?Fe._`{minContains: ${e}}`:Fe._`{minContains: ${e}, maxContains: ${t}}`},FI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e,o,a,{minContains:c,maxContains:u}=i;if(s.opts.next)o=c===void 0?1:c,a=u;else o=1;let l=t.const("len",Fe._`${n}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,Cn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Cn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Cn.alwaysValidSchema)(s,r)){let h=Fe._`${l} >= ${o}`;if(a!==void 0)h=Fe._`${h} && ${l} <= ${a}`;e.pass(h);return}s.items=!0;let d=t.name("valid");if(a===void 0&&o===1)f(d,()=>t.if(d,()=>t.break()));else if(o===0){if(t.let(d,!0),a!==void 0)t.if(Fe._`${n}.length > 0`,p)}else t.let(d,!1),p();e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,l,(y)=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Cn.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(Fe._`${h}++`),a===void 0)t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0).break());else if(t.if(Fe._`${h} > ${a}`,()=>t.assign(d,!1).break()),o===1)t.assign(d,!0);else t.if(Fe._`${h} >= ${o}`,()=>t.assign(d,!0))}}};ca.default=FI});var jn=b(function(We){Object.defineProperty(We,"__esModule",{value:!0});We.validateSchemaDeps=We.validatePropertyDeps=We.error=void 0;var da=F(),OI=D(),pi=Ce();We.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let i=t===1?"property":"properties";return da.str`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:i}})=>da._`{property: ${e},
|
|
8
|
-
missingProperty: ${
|
|
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 TI={keyword:"dependencies",type:"object",schemaType:"object",error:We.error,code(e){let[t,r]=AI(e);$p(e,t),Ep(e,r)}};function AI({schema:e}){let t={},r={};for(let i in e){if(i==="__proto__")continue;let n=Array.isArray(e[i])?t:r;n[i]=e[i]}return[t,r]}function $p(e,t=e.schema){let{gen:r,data:i,it:n}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,pi.propertyInData)(r,i,o,n.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),n.allErrors)r.if(c,()=>{for(let u of a)(0,pi.checkReportMissingProp)(e,u)});else r.if(da._`${c} && (${(0,pi.checkMissingProp)(e,a,s)})`),(0,pi.reportMissingProp)(e,s),r.else()}}We.validatePropertyDeps=$p;function Ep(e,t=e.schema){let{gen:r,data:i,keyword:n,it:s}=e,o=r.name("valid");for(let a in t){if((0,OI.alwaysValidSchema)(s,t[a]))continue;r.if((0,pi.propertyInData)(r,i,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:n,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}We.validateSchemaDeps=Ep;We.default=TI});var Sp=b(function(ua){Object.defineProperty(ua,"__esModule",{value:!0});var Ip=F(),kI=D(),DI={message:"property name must be valid",params:({params:e})=>Ip._`{propertyName: ${e.propertyName}}`},NI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:DI,code(e){let{gen:t,schema:r,data:i,it:n}=e;if((0,kI.alwaysValidSchema)(n,r))return;let s=t.name("valid");t.forIn("key",i,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,Ip.not)(s),()=>{if(e.error(!0),!n.allErrors)t.break()})}),e.ok(s)}};ua.default=NI});var fa=b(function(pa){Object.defineProperty(pa,"__esModule",{value:!0});var Fn=Ce(),Me=F(),LI=Re(),On=D(),qI={message:"must NOT have additional properties",params:({params:e})=>Me._`{additionalProperty: ${e.additionalProperty}}`},MI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:qI,code(e){let{gen:t,schema:r,parentSchema:i,data:n,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,On.alwaysValidSchema)(o,r))return;let u=(0,Fn.allSchemaProperties)(i.properties),l=(0,Fn.allSchemaProperties)(i.patternProperties);d(),e.ok(Me._`${s} === ${LI.default.errors}`);function d(){t.forIn("key",n,(g)=>{if(!u.length&&!l.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let P=(0,On.schemaRefOrVal)(o,i.properties,"properties");y=(0,Fn.isOwnProperty)(t,P,g)}else if(u.length)y=(0,Me.or)(...u.map((P)=>Me._`${g} === ${P}`));else y=Me.nil;if(l.length)y=(0,Me.or)(y,...l.map((P)=>Me._`${(0,Fn.usePattern)(e,P)}.test(${g})`));return(0,Me.not)(y)}function f(g){t.code(Me._`delete ${n}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,On.alwaysValidSchema)(o,r)){let y=t.name("valid");if(c.removeAdditional==="failing")h(g,y,!1),t.if((0,Me.not)(y),()=>{e.reset(),f(g)});else if(h(g,y),!a)t.if((0,Me.not)(y),()=>t.break())}}function h(g,y,P){let v={keyword:"additionalProperties",dataProp:g,dataPropType:On.Type.Str};if(P===!1)Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(v,y)}}};pa.default=MI});var Cp=b(function(ha){Object.defineProperty(ha,"__esModule",{value:!0});var UI=cr(),xp=Ce(),ma=D(),Rp=fa(),BI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:i,data:n,it:s}=e;if(s.opts.removeAdditional==="all"&&i.additionalProperties===void 0)Rp.default.code(new UI.KeywordCxt(s,Rp.default,"additionalProperties"));let o=(0,xp.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=ma.mergeEvaluated.props(t,(0,ma.toHash)(o),s.props);let a=o.filter((d)=>!(0,ma.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a){if(u(d))l(d);else{if(t.if((0,xp.propertyInData)(t,n,d,s.opts.ownProperties)),l(d),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(d),e.ok(c)}function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};ha.default=BI});var Tp=b(function(ga){Object.defineProperty(ga,"__esModule",{value:!0});var jp=Ce(),Tn=F(),Fp=D(),Op=D(),GI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:i,parentSchema:n,it:s}=e,{opts:o}=s,a=(0,jp.allSchemaProperties)(r),c=a.filter((h)=>(0,Fp.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&n.properties,l=t.name("valid");if(s.props!==!0&&!(s.props instanceof Tn.Name))s.props=(0,Op.evaluatedPropsToName)(t,s.props);let{props:d}=s;p();function p(){for(let h of a){if(u)f(h);if(s.allErrors)m(h);else t.var(l,!0),m(h),t.if(l)}}function f(h){for(let g in u)if(new RegExp(h).test(g))(0,Fp.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",i,(g)=>{t.if(Tn._`${(0,jp.usePattern)(e,h)}.test(${g})`,()=>{let y=c.includes(h);if(!y)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Op.Type.Str},l);if(s.opts.unevaluated&&d!==!0)t.assign(Tn._`${d}[${g}]`,!0);else if(!y&&!s.allErrors)t.if((0,Tn.not)(l),()=>t.break())})})}}};ga.default=GI});var Ap=b(function(ya){Object.defineProperty(ya,"__esModule",{value:!0});var VI=D(),KI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:i}=e;if((0,VI.alwaysValidSchema)(i,r)){e.fail();return}let n=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),e.failResult(n,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ya.default=KI});var kp=b(function(_a){Object.defineProperty(_a,"__esModule",{value:!0});var zI=Ce(),WI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:zI.validateUnion,error:{message:"must match a schema in anyOf"}};_a.default=WI});var Dp=b(function(Pa){Object.defineProperty(Pa,"__esModule",{value:!0});var An=F(),HI=D(),JI={message:"must match exactly one schema in oneOf",params:({params:e})=>An._`{passingSchemas: ${e.passing}}`},QI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:JI,code(e){let{gen:t,schema:r,parentSchema:i,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(n.opts.discriminator&&i.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(o,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,d)=>{let p;if((0,HI.alwaysValidSchema)(n,l))t.var(c,!0);else p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c);if(d>0)t.if(An._`${c} && ${o}`).assign(o,!1).assign(a,An._`[${a}, ${d}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,d),p)e.mergeEvaluated(p,An.Name)})})}}};Pa.default=QI});var Np=b(function(ba){Object.defineProperty(ba,"__esModule",{value:!0});var YI=D(),XI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let n=t.name("valid");r.forEach((s,o)=>{if((0,YI.alwaysValidSchema)(i,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},n);e.ok(n),e.mergeEvaluated(a)})}};ba.default=XI});var Mp=b(function(va){Object.defineProperty(va,"__esModule",{value:!0});var kn=F(),qp=D(),ZI={message:({params:e})=>kn.str`must match "${e.ifClause}" schema`,params:({params:e})=>kn._`{failingKeyword: ${e.ifClause}}`},eS={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ZI,code(e){let{gen:t,parentSchema:r,it:i}=e;if(r.then===void 0&&r.else===void 0)(0,qp.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let n=Lp(i,"then"),s=Lp(i,"else");if(!n&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),n&&s){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else if(n)t.if(a,u("then"));else t.if((0,kn.not)(a),u("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,d){return()=>{let p=e.subschema({keyword:l},a);if(t.assign(o,a),e.mergeValidEvaluated(p,o),d)t.assign(d,kn._`${l}`);else e.setParams({ifClause:l})}}}};function Lp(e,t){let r=e.schema[t];return r!==void 0&&!(0,qp.alwaysValidSchema)(e,r)}va.default=eS});var Up=b(function(wa){Object.defineProperty(wa,"__esModule",{value:!0});var tS=D(),rS={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,tS.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};wa.default=rS});var Ea=b(function($a){Object.defineProperty($a,"__esModule",{value:!0});var iS=sa(),nS=Pp(),sS=oa(),oS=vp(),aS=wp(),lS=jn(),cS=Sp(),dS=fa(),uS=Cp(),pS=Tp(),fS=Ap(),mS=kp(),hS=Dp(),gS=Np(),yS=Mp(),_S=Up();function PS(e=!1){let t=[fS.default,mS.default,hS.default,gS.default,yS.default,_S.default,cS.default,dS.default,lS.default,uS.default,pS.default];if(e)t.push(nS.default,oS.default);else t.push(iS.default,sS.default);return t.push(aS.default),t}$a.default=PS});var Sa=b(function(fi){Object.defineProperty(fi,"__esModule",{value:!0});fi.dynamicAnchor=void 0;var Ia=F(),bS=Re(),Bp=ei(),vS=$n(),wS={keyword:"$dynamicAnchor",schemaType:"string",code:(e)=>Gp(e,e.schema)};function Gp(e,t){let{gen:r,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let n=Ia._`${bS.default.dynamicAnchors}${(0,Ia.getProperty)(t)}`,s=i.errSchemaPath==="#"?i.validateName:$S(e);r.if(Ia._`!${n}`,()=>r.assign(n,s))}fi.dynamicAnchor=Gp;function $S(e){let{schemaEnv:t,schema:r,self:i}=e.it,{root:n,baseId:s,localRefs:o,meta:a}=t.root,{schemaId:c}=i.opts,u=new Bp.SchemaEnv({schema:r,schemaId:c,root:n,baseId:s,localRefs:o,meta:a});return Bp.compileSchema.call(i,u),(0,vS.getValidate)(e,u)}fi.default=wS});var xa=b(function(mi){Object.defineProperty(mi,"__esModule",{value:!0});mi.dynamicRef=void 0;var Vp=F(),ES=Re(),Kp=$n(),IS={keyword:"$dynamicRef",schemaType:"string",code:(e)=>zp(e,e.schema)};function zp(e,t){let{gen:r,keyword:i,it:n}=e;if(t[0]!=="#")throw Error(`"${i}" only supports hash fragment reference`);let s=t.slice(1);if(n.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(n.schemaEnv.root.dynamicAnchors[s]){let u=r.let("_v",Vp._`${ES.default.dynamicAnchors}${(0,Vp.getProperty)(s)}`);r.if(u,a(u,c),a(n.validateName,c))}else a(n.validateName,c)()}function a(c,u){return u?()=>r.block(()=>{(0,Kp.callRef)(e,c),r.let(u,!0)}):()=>(0,Kp.callRef)(e,c)}}mi.dynamicRef=zp;mi.default=IS});var Wp=b(function(Ra){Object.defineProperty(Ra,"__esModule",{value:!0});var SS=Sa(),xS=D(),RS={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){if(e.schema)(0,SS.dynamicAnchor)(e,"");else(0,xS.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ra.default=RS});var Hp=b(function(Ca){Object.defineProperty(Ca,"__esModule",{value:!0});var CS=xa(),jS={keyword:"$recursiveRef",schemaType:"string",code:(e)=>(0,CS.dynamicRef)(e,e.schema)};Ca.default=jS});var Jp=b(function(ja){Object.defineProperty(ja,"__esModule",{value:!0});var FS=Sa(),OS=xa(),TS=Wp(),AS=Hp(),kS=[FS.default,OS.default,TS.default,AS.default];ja.default=kS});var Yp=b(function(Fa){Object.defineProperty(Fa,"__esModule",{value:!0});var Qp=jn(),DS={keyword:"dependentRequired",type:"object",schemaType:"object",error:Qp.error,code:(e)=>(0,Qp.validatePropertyDeps)(e)};Fa.default=DS});var Xp=b(function(Oa){Object.defineProperty(Oa,"__esModule",{value:!0});var NS=jn(),LS={keyword:"dependentSchemas",type:"object",schemaType:"object",code:(e)=>(0,NS.validateSchemaDeps)(e)};Oa.default=LS});var Zp=b(function(Ta){Object.defineProperty(Ta,"__esModule",{value:!0});var qS=D(),MS={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){if(t.contains===void 0)(0,qS.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Ta.default=MS});var ef=b(function(Aa){Object.defineProperty(Aa,"__esModule",{value:!0});var US=Yp(),BS=Xp(),GS=Zp(),VS=[US.default,BS.default,GS.default];Aa.default=VS});var rf=b(function(ka){Object.defineProperty(ka,"__esModule",{value:!0});var Et=F(),tf=D(),KS=Re(),zS={message:"must NOT have unevaluated properties",params:({params:e})=>Et._`{unevaluatedProperty: ${e.unevaluatedProperty}}`},WS={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:zS,code(e){let{gen:t,schema:r,data:i,errsCount:n,it:s}=e;if(!n)throw Error("ajv implementation error");let{allErrors:o,props:a}=s;if(a instanceof Et.Name)t.if(Et._`${a} !== true`,()=>t.forIn("key",i,(d)=>t.if(u(a,d),()=>c(d))));else if(a!==!0)t.forIn("key",i,(d)=>a===void 0?c(d):t.if(l(a,d),()=>c(d)));s.props=!0,e.ok(Et._`${n} === ${KS.default.errors}`);function c(d){if(r===!1){if(e.setParams({unevaluatedProperty:d}),e.error(),!o)t.break();return}if(!(0,tf.alwaysValidSchema)(s,r)){let p=t.name("valid");if(e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tf.Type.Str},p),!o)t.if((0,Et.not)(p),()=>t.break())}}function u(d,p){return Et._`!${d} || !${d}[${p}]`}function l(d,p){let f=[];for(let m in d)if(d[m]===!0)f.push(Et._`${p} !== ${m}`);return(0,Et.and)(...f)}}};ka.default=WS});var sf=b(function(Da){Object.defineProperty(Da,"__esModule",{value:!0});var Dt=F(),nf=D(),HS={message:({params:{len:e}})=>Dt.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Dt._`{limit: ${e}}`},JS={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:HS,code(e){let{gen:t,schema:r,data:i,it:n}=e,s=n.items||0;if(s===!0)return;let o=t.const("len",Dt._`${i}.length`);if(r===!1)e.setParams({len:s}),e.fail(Dt._`${o} > ${s}`);else if(typeof r=="object"&&!(0,nf.alwaysValidSchema)(n,r)){let c=t.var("valid",Dt._`${o} <= ${s}`);t.if((0,Dt.not)(c),()=>a(c,s)),e.ok(c)}n.items=!0;function a(c,u){t.forRange("i",u,o,(l)=>{if(e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:nf.Type.Num},c),!n.allErrors)t.if((0,Dt.not)(c),()=>t.break())})}}};Da.default=JS});var of=b(function(Na){Object.defineProperty(Na,"__esModule",{value:!0});var QS=rf(),YS=sf(),XS=[QS.default,YS.default];Na.default=XS});var af=b(function(La){Object.defineProperty(La,"__esModule",{value:!0});var Q=F(),ZS={message:({schemaCode:e})=>Q.str`must match format "${e}"`,params:({schemaCode:e})=>Q._`{format: ${e}}`},ex={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ZS,code(e,t){let{gen:r,data:i,$data:n,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;if(n)p();else f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",Q._`${m}[${o}]`),g=r.let("fType"),y=r.let("format");r.if(Q._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,Q._`${h}.type || "string"`).assign(y,Q._`${h}.validate`),()=>r.assign(g,Q._`"string"`).assign(y,h)),e.fail$data((0,Q.or)(P(),v()));function P(){if(c.strictSchema===!1)return Q.nil;return Q._`${o} && !${y}`}function v(){let w=l.$async?Q._`(${h}.async ? await ${y}(${i}) : ${y}(${i}))`:Q._`${y}(${i})`,I=Q._`(typeof ${y} == "function" ? ${w} : ${y}.test(${i}))`;return Q._`${y} && ${y} !== true && ${g} === ${t} && !${I}`}}function f(){let m=d.formats[s];if(!m){P();return}if(m===!0)return;let[h,g,y]=v(m);if(h===t)e.pass(w());function P(){if(c.strictSchema===!1){d.logger.warn(I());return}throw Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(I){let E=I instanceof RegExp?(0,Q.regexpCode)(I):c.code.formats?Q._`${c.code.formats}${(0,Q.getProperty)(s)}`:void 0,x=r.scopeValue("formats",{key:s,ref:I,code:E});if(typeof I=="object"&&!(I instanceof RegExp))return[I.type||"string",I.validate,Q._`${x}.validate`];return["string",I,x]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw Error("async format in sync schema");return Q._`await ${y}(${i})`}return typeof g=="function"?Q._`${y}(${i})`:Q._`${y}.test(${i})`}}}};La.default=ex});var Ma=b(function(qa){Object.defineProperty(qa,"__esModule",{value:!0});var tx=af(),rx=[tx.default];qa.default=rx});var Ua=b(function(fr){Object.defineProperty(fr,"__esModule",{value:!0});fr.contentVocabulary=fr.metadataVocabulary=void 0;fr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cf=b(function(Ba){Object.defineProperty(Ba,"__esModule",{value:!0});var ix=Uo(),nx=ia(),sx=Ea(),ox=Jp(),ax=ef(),lx=of(),cx=Ma(),lf=Ua(),dx=[ox.default,ix.default,nx.default,(0,sx.default)(!0),cx.default,lf.metadataVocabulary,lf.contentVocabulary,ax.default,lx.default];Ba.default=dx});var uf=b(function(Dn){Object.defineProperty(Dn,"__esModule",{value:!0});Dn.DiscrError=void 0;var df;(function(e){e.Tag="tag",e.Mapping="mapping"})(df||(Dn.DiscrError=df={}))});var Ka=b(function(Va){Object.defineProperty(Va,"__esModule",{value:!0});var mr=F(),Ga=uf(),pf=ei(),ux=dr(),px=D(),fx={message:({params:{discrError:e,tagName:t}})=>e===Ga.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>mr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},mx={keyword:"discriminator",type:"object",schemaType:"object",error:fx,code(e){let{gen:t,data:r,schema:i,parentSchema:n,it:s}=e,{oneOf:o}=n;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(i.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",mr._`${r}${(0,mr.getProperty)(a)}`);t.if(mr._`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Ga.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let f=p();t.if(!1);for(let m in f)t.elseIf(mr._`${u} === ${m}`),t.assign(c,d(f[m]));t.else(),e.error(!1,{discrError:Ga.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function d(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,mr.Name),m}function p(){var f;let m={},h=y(n),g=!0;for(let w=0;w<o.length;w++){let I=o[w];if((I===null||I===void 0?void 0:I.$ref)&&!(0,px.schemaHasRulesButRef)(I,s.self.RULES)){let x=I.$ref;if(I=pf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,x),I instanceof pf.SchemaEnv)I=I.schema;if(I===void 0)throw new ux.default(s.opts.uriResolver,s.baseId,x)}let E=(f=I===null||I===void 0?void 0:I.properties)===null||f===void 0?void 0:f[a];if(typeof E!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(I)),P(E,w)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function y({required:w}){return Array.isArray(w)&&w.includes(a)}function P(w,I){if(w.const)v(w.const,I);else if(w.enum)for(let E of w.enum)v(E,I);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(w,I){if(typeof w!="string"||w in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[w]=I}}}};Va.default=mx});var ff=b(function(xk,hx){hx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var mf=b(function(Rk,gx){gx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var hf=b(function(Ck,yx){yx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var gf=b(function(jk,_x){_x.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var yf=b(function(Fk,Px){Px.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var _f=b(function(Ok,bx){bx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var Pf=b(function(Tk,vx){vx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var bf=b(function(Ak,wx){wx.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var vf=b(function(za){Object.defineProperty(za,"__esModule",{value:!0});var $x=ff(),Ex=mf(),Ix=hf(),Sx=gf(),xx=yf(),Rx=_f(),Cx=Pf(),jx=bf(),Fx=["/properties"];function Ox(e){return[$x,Ex,Ix,Sx,xx,t(this,Rx),Cx,t(this,jx)].forEach((r)=>this.addMetaSchema(r,void 0,!1)),this;function t(r,i){return e?r.$dataMetaSchema(i,Fx):i}}za.default=Ox});var Ja=b(function(z,Ha){Object.defineProperty(z,"__esModule",{value:!0});z.MissingRefError=z.ValidationError=z.CodeGen=z.Name=z.nil=z.stringify=z.str=z._=z.KeywordCxt=z.Ajv2020=void 0;var Tx=Lo(),Ax=cf(),kx=Ka(),Dx=vf(),Wa="https://json-schema.org/draft/2020-12/schema";class hi extends Tx.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){if(super._addVocabularies(),Ax.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(kx.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;if(!t)return;Dx.default.call(this,e),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}}z.Ajv2020=hi;Ha.exports=z=hi;Ha.exports.Ajv2020=hi;Object.defineProperty(z,"__esModule",{value:!0});z.default=hi;var Nx=cr();Object.defineProperty(z,"KeywordCxt",{enumerable:!0,get:function(){return Nx.KeywordCxt}});var hr=F();Object.defineProperty(z,"_",{enumerable:!0,get:function(){return hr._}});Object.defineProperty(z,"str",{enumerable:!0,get:function(){return hr.str}});Object.defineProperty(z,"stringify",{enumerable:!0,get:function(){return hr.stringify}});Object.defineProperty(z,"nil",{enumerable:!0,get:function(){return hr.nil}});Object.defineProperty(z,"Name",{enumerable:!0,get:function(){return hr.Name}});Object.defineProperty(z,"CodeGen",{enumerable:!0,get:function(){return hr.CodeGen}});var Lx=Xr();Object.defineProperty(z,"ValidationError",{enumerable:!0,get:function(){return Lx.default}});var qx=dr();Object.defineProperty(z,"MissingRefError",{enumerable:!0,get:function(){return qx.default}})});var eg=b(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.formatNames=Ze.fastFormats=Ze.fullFormats=void 0;function Xe(e,t){return{validate:e,compare:t}}Ze.fullFormats={date:Xe(Qh,Ul),time:Xe(ql(!0),Bl),"date-time":Xe(Wh(!0),Xh),"iso-time":Xe(ql(),Yh),"iso-date-time":Xe(Wh(),Zh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:fF,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:bF,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:mF,int32:{type:"number",validate:yF},int64:{type:"number",validate:_F},float:{type:"number",validate:Jh},double:{type:"number",validate:Jh},password:!0,binary:!0};Ze.fastFormats={...Ze.fullFormats,date:Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ul),time:Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bl),"date-time":Xe(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Xh),"iso-time":Xe(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yh),"iso-date-time":Xe(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Zh),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Ze.formatNames=Object.keys(Ze.fullFormats);function lF(e){return e%4===0&&(e%100!==0||e%400===0)}var cF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,dF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Qh(e){let t=cF.exec(e);if(!t)return!1;let r=+t[1],i=+t[2],n=+t[3];return i>=1&&i<=12&&n>=1&&n<=(i===2&&lF(r)?29:dF[i])}function Ul(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var Ll=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ql(e){return function(r){let i=Ll.exec(r);if(!i)return!1;let n=+i[1],s=+i[2],o=+i[3],a=i[4],c=i[5]==="-"?-1:1,u=+(i[6]||0),l=+(i[7]||0);if(u>23||l>59||e&&!a)return!1;if(n<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function Bl(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),i=new Date("2020-01-01T"+t).valueOf();if(!(r&&i))return;return r-i}function Yh(e,t){if(!(e&&t))return;let r=Ll.exec(e),i=Ll.exec(t);if(!(r&&i))return;if(e=r[1]+r[2]+r[3],t=i[1]+i[2]+i[3],e>t)return 1;if(e<t)return-1;return 0}var Ml=/t|\s/i;function Wh(e){let t=ql(e);return function(i){let n=i.split(Ml);return n.length===2&&Qh(n[0])&&t(n[1])}}function Xh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),i=new Date(t).valueOf();if(!(r&&i))return;return r-i}function Zh(e,t){if(!(e&&t))return;let[r,i]=e.split(Ml),[n,s]=t.split(Ml),o=Ul(r,n);if(o===void 0)return;return o||Bl(i,s)}var uF=/\/|:/,pF=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function fF(e){return uF.test(e)&&pF.test(e)}var Hh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mF(e){return Hh.lastIndex=0,Hh.test(e)}var hF=-2147483648,gF=2147483647;function yF(e){return Number.isInteger(e)&&e<=gF&&e>=hF}function _F(e){return Number.isInteger(e)}function Jh(){return!0}var PF=/[^\\]\\Z/;function bF(e){if(PF.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var rg=b(function(Gl){Object.defineProperty(Gl,"__esModule",{value:!0});var vF=Uo(),wF=ia(),$F=Ea(),EF=Ma(),tg=Ua(),IF=[vF.default,wF.default,(0,$F.default)(),EF.default,tg.metadataVocabulary,tg.contentVocabulary];Gl.default=IF});var ig=b(function(Vq,SF){SF.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var sg=b(function(W,Vl){Object.defineProperty(W,"__esModule",{value:!0});W.MissingRefError=W.ValidationError=W.CodeGen=W.Name=W.nil=W.stringify=W.str=W._=W.KeywordCxt=W.Ajv=void 0;var xF=Lo(),RF=rg(),CF=Ka(),ng=ig(),jF=["/properties"],bs="http://json-schema.org/draft-07/schema";class Di extends xF.default{_addVocabularies(){if(super._addVocabularies(),RF.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(CF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ng,jF):ng;this.addMetaSchema(e,bs,!1),this.refs["http://json-schema.org/schema"]=bs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bs)?bs:void 0)}}W.Ajv=Di;Vl.exports=W=Di;Vl.exports.Ajv=Di;Object.defineProperty(W,"__esModule",{value:!0});W.default=Di;var FF=cr();Object.defineProperty(W,"KeywordCxt",{enumerable:!0,get:function(){return FF.KeywordCxt}});var Cr=F();Object.defineProperty(W,"_",{enumerable:!0,get:function(){return Cr._}});Object.defineProperty(W,"str",{enumerable:!0,get:function(){return Cr.str}});Object.defineProperty(W,"stringify",{enumerable:!0,get:function(){return Cr.stringify}});Object.defineProperty(W,"nil",{enumerable:!0,get:function(){return Cr.nil}});Object.defineProperty(W,"Name",{enumerable:!0,get:function(){return Cr.Name}});Object.defineProperty(W,"CodeGen",{enumerable:!0,get:function(){return Cr.CodeGen}});var OF=Xr();Object.defineProperty(W,"ValidationError",{enumerable:!0,get:function(){return OF.default}});var TF=dr();Object.defineProperty(W,"MissingRefError",{enumerable:!0,get:function(){return TF.default}})});var og=b(function(jr){Object.defineProperty(jr,"__esModule",{value:!0});jr.formatLimitDefinition=void 0;var AF=sg(),Be=F(),Rt=Be.operators,vs={formatMaximum:{okStr:"<=",ok:Rt.LTE,fail:Rt.GT},formatMinimum:{okStr:">=",ok:Rt.GTE,fail:Rt.LT},formatExclusiveMaximum:{okStr:"<",ok:Rt.LT,fail:Rt.GTE},formatExclusiveMinimum:{okStr:">",ok:Rt.GT,fail:Rt.LTE}},kF={message:({keyword:e,schemaCode:t})=>Be.str`should be ${vs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>Be._`{comparison: ${vs[e].okStr}, limit: ${t}}`};jr.formatLimitDefinition={keyword:Object.keys(vs),type:"string",schemaType:"string",$data:!0,error:kF,code(e){let{gen:t,data:r,schemaCode:i,keyword:n,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new AF.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)u();else l();function u(){let p=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=t.const("fmt",Be._`${p}[${c.schemaCode}]`);e.fail$data((0,Be.or)(Be._`typeof ${f} != "object"`,Be._`${f} instanceof RegExp`,Be._`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${n}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:o.code.formats?Be._`${o.code.formats}${(0,Be.getProperty)(p)}`:void 0});e.fail$data(d(m))}function d(p){return Be._`${p}.compare(${r}, ${i}) ${vs[n].fail} 0`}},dependencies:["format"]};var DF=(e)=>(e.addKeyword(jr.formatLimitDefinition),e);jr.default=DF});var dg=b(function(Ni,cg){Object.defineProperty(Ni,"__esModule",{value:!0});var Fr=eg(),NF=og(),Kl=F(),ag=new Kl.Name("fullFormats"),LF=new Kl.Name("fastFormats"),zl=(e,t={keywords:!0})=>{if(Array.isArray(t))return lg(e,t,Fr.fullFormats,ag),e;let[r,i]=t.mode==="fast"?[Fr.fastFormats,LF]:[Fr.fullFormats,ag],n=t.formats||Fr.formatNames;if(lg(e,n,r,i),t.keywords)(0,NF.default)(e);return e};zl.get=(e,t="full")=>{let i=(t==="fast"?Fr.fastFormats:Fr.fullFormats)[e];if(!i)throw Error(`Unknown format "${e}"`);return i};function lg(e,t,r,i){var n,s;(n=(s=e.opts.code).formats)!==null&&n!==void 0||(s.formats=Kl._`require("ajv-formats/dist/formats").${i}`);for(let o of t)e.addFormat(o,r[o])}cg.exports=Ni=zl;Object.defineProperty(Ni,"__esModule",{value:!0});Ni.default=zl});var Zg=b(function(HM,Xg){Xg.exports=jO;function CO(e){let t={defaultWidth:0,output:process.stdout,tty:require("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function jO(e){let t=CO(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var _y=b(function(lU,yy){var KO=require("stream");class gy extends KO{#r=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}yy.exports=gy});class rt extends Error{constructor(e,t,r){super(r);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class ft extends rt{constructor(e){super(1,"commander.invalidArgument",e);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class Qi{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.push(e),t}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ft(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(t,r);return t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Yi(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}var Dc=require("events"),Zi=xe(require("child_process")),Ge=xe(require("path")),Br=xe(require("fs")),U=xe(require("process")),Nc=require("util");var Oc=require("util");class Xi{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter((i)=>!i._hidden),r=e._getHelpCommand();if(r&&!r._hidden)t.push(r);if(this.sortSubcommands)t.sort((i,n)=>i.name().localeCompare(n.name()));return t}compareOptions(e,t){let r=(i)=>i.short?i.short.replace(/^-/,""):i.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter((i)=>!i.hidden),r=e._getHelpOption();if(r&&!r.hidden){let i=r.short&&e._findOption(r.short),n=r.long&&e._findOption(r.long);if(!i&&!n)t.push(r);else if(r.long&&!n)t.push(e.createOption(r.long,r.description));else if(r.short&&!i)t.push(e.createOption(r.short,r.description))}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let i=r.options.filter((n)=>!n.hidden);t.push(...i)}if(this.sortOptions)t.sort(this.compareOptions);return t}visibleArguments(e){if(e._argsDescription)e.registeredArguments.forEach((t)=>{t.description=t.description||e._argsDescription[t.name()]||""});if(e.registeredArguments.find((t)=>t.description))return e.registeredArguments;return[]}subcommandTerm(e){let t=e.registeredArguments.map((r)=>Yi(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,i)=>Math.max(r,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;if(e._aliases[0])t=t+"|"+e._aliases[0];let r="";for(let i=e.parent;i;i=i.parent)r=i.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0){if(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue==="boolean")t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`)}if(e.presetArg!==void 0&&e.optional)t.push(`preset: ${JSON.stringify(e.presetArg)}`);if(e.envVar!==void 0)t.push(`env: ${e.envVar}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}argumentDescription(e){let t=[];if(e.argChoices)t.push(`choices: ${e.argChoices.map((r)=>JSON.stringify(r)).join(", ")}`);if(e.defaultValue!==void 0)t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`);if(t.length>0){let r=`(${t.join(", ")})`;if(e.description)return`${e.description} ${r}`;return r}return e.description}formatItemList(e,t,r){if(t.length===0)return[];return[r.styleTitle(e),...t,""]}groupItems(e,t,r){let i=new Map;return e.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[])}),t.forEach((n)=>{let s=r(n);if(!i.has(s))i.set(s,[]);i.get(s).push(n)}),i}formatHelp(e,t){let r=t.padWidth(e,t),i=t.helpWidth??80;function n(l,d){return t.formatItem(l,r,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],o=t.commandDescription(e);if(o.length>0)s=s.concat([t.boxWrap(t.styleCommandDescription(o),i),""]);let a=t.visibleArguments(e).map((l)=>n(t.styleArgumentTerm(t.argumentTerm(l)),t.styleArgumentDescription(t.argumentDescription(l))));if(s=s.concat(this.formatItemList("Arguments:",a,t)),this.groupItems(e.options,t.visibleOptions(e),(l)=>l.helpGroupHeading??"Options:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),t.showGlobalOptions){let l=t.visibleGlobalOptions(e).map((d)=>n(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));s=s.concat(this.formatItemList("Global Options:",l,t))}return this.groupItems(e.commands,t.visibleCommands(e),(l)=>l.helpGroup()||"Commands:").forEach((l,d)=>{let p=l.map((f)=>n(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));s=s.concat(this.formatItemList(d,p,t))}),s.join(`
|
|
11
|
-
`)}displayWidth(e){return
|
|
12
|
-
`+" ".repeat(t+a));return s+o+" ".repeat(a)+
|
|
13
|
-
${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let r=e.split(/\r\n|\n/),
|
|
14
|
-
`)}}class
|
|
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(
|
|
18
|
-
- too many short flags`);if(
|
|
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
|
|
21
|
-
(Did you mean one of ${
|
|
22
|
-
(Did you mean ${
|
|
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
|
|
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
|
|
25
|
-
- already used by option '${t.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let t=(
|
|
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(
|
|
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
|
-
- ${
|
|
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||{},
|
|
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
|
|
34
|
-
Expecting one of '${r.join("', '")}'`);let
|
|
35
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((
|
|
36
|
-
`);return new
|
|
37
|
-
${t}`,e)}}var qs="x-potato-sdk-base-url",Lc=(e,t,r)=>(_(e.length>0,"The SDK base URL cannot be empty"),_(t.length>0,"The SDK API key cannot be empty"),{headers:{Accept:"application/json",Authorization:`ApiKey ${t}`,[qs]:new URL(e).toString()},fetch:r});async function C(e,t){let{fetch:r=globalThis.fetch,...i}=t,n=new Headers(i.headers),s=n.get(qs);_(s,"The SDK base URL is missing"),n.delete(qs);let o=await r(new URL(e,s),{...i,headers:n}),a=await o.text();if(!o.ok){let c=a;if(a.length===0)c=void 0;else if(o.headers.get("content-type")?.includes("application/json"))c=JSON.parse(a);throw re.fromResponse(o.status,c)}return a.length===0?void 0:JSON.parse(a)}var $0=()=>"/api/v2-beta/me",qc=async(e)=>C($0(),{...e,method:"GET"}),E0=(e)=>{let t=new URLSearchParams;Object.entries(e||{}).forEach(([i,n])=>{if(n!==void 0)t.append(i,n===null?"null":n.toString())});let r=t.toString();return r.length>0?`/api/v2-beta/projects?${r}`:"/api/v2-beta/projects"},Ms=async(e,t)=>C(E0(e),{...t,method:"GET"}),I0=()=>"/api/v2-beta/projects",Mc=async(e,t)=>C(I0(),{...t,method:"POST",headers:{"Content-Type":"application/json",...t?.headers},body:JSON.stringify(e)}),S0=(e)=>`/api/v2-beta/projects/${e}`,Uc=async(e,t)=>C(S0(e),{...t,method:"GET"}),x0=(e)=>`/api/v2-beta/projects/${e}`,Bc=async(e,t,r)=>C(x0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),R0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/pipelines?${i}`:`/api/v2-beta/projects/${e}/pipelines`},Us=async(e,t,r)=>C(R0(e,t),{...r,method:"GET"}),C0=(e)=>`/api/v2-beta/pipelines/${e}`,Gc=async(e,t)=>C(C0(e),{...t,method:"GET"}),j0=(e)=>`/api/v2-beta/pipelines/${e}`,Vc=async(e,t,r)=>C(j0(e),{...r,method:"PATCH",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),F0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/projects/${e}/datasets?${i}`:`/api/v2-beta/projects/${e}/datasets`},Bs=async(e,t,r)=>C(F0(e,t),{...r,method:"GET"}),O0=(e)=>`/api/v2-beta/projects/${e}/datasets`,Kc=async(e,t,r)=>C(O0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),T0=(e)=>`/api/v2-beta/datasets/${e}`,zc=async(e,t)=>C(T0(e),{...t,method:"GET"}),A0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/fields?${i}`:`/api/v2-beta/datasets/${e}/fields`},Gs=async(e,t,r)=>C(A0(e,t),{...r,method:"GET"}),k0=(e)=>`/api/v2-beta/datasets/${e}/fields`,Vs=async(e,t,r)=>C(k0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),D0=(e)=>`/api/v2-beta/datasets/${e}/inferred-fields`,Wc=async(e,t)=>C(D0(e),{...t,method:"GET"}),N0=(e)=>`/api/v2-beta/datasets/${e}/items`,Hc=async(e,t,r)=>C(N0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),L0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/datasets/${e}/items?${i}`:`/api/v2-beta/datasets/${e}/items`},Ks=async(e,t,r)=>C(L0(e,t),{...r,method:"GET"}),q0=(e)=>`/api/v2-beta/datasets/${e}/uploads`,Jc=async(e,t,r)=>C(q0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),M0=(e)=>`/api/v2-beta/uploads/${e}/finalize`,Qc=async(e,t)=>C(M0(e),{...t,method:"POST"}),U0=(e)=>`/api/v2-beta/uploads/${e}`,zs=async(e,t)=>C(U0(e),{...t,method:"GET"}),B0=(e)=>`/api/v2-beta/projects/${e}/pipelines/import`,Yc=async(e,t,r)=>C(B0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),G0=(e)=>`/api/v2-beta/pipelines/${e}/dataset`,Xc=async(e,t,r)=>C(G0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),V0=(e)=>`/api/v2-beta/pipelines/${e}/export`,Zc=async(e,t)=>C(V0(e),{...t,method:"GET"}),K0=(e)=>`/api/v2-beta/pipelines/${e}/copy`,ed=async(e,t,r)=>C(K0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),z0=(e)=>`/api/v2-beta/pipelines/${e}/cost-estimate`,td=async(e,t,r)=>C(z0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),W0=(e)=>`/api/v2-beta/pipelines/${e}/runs`,rd=async(e,t)=>C(W0(e),{...t,method:"POST"}),H0=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/pipelines/${e}/runs?${i}`:`/api/v2-beta/pipelines/${e}/runs`},Ws=async(e,t,r)=>C(H0(e,t),{...r,method:"GET"}),J0=(e)=>`/api/v2-beta/runs/${e}`,Hs=async(e,t)=>C(J0(e),{...t,method:"GET"}),Q0=(e)=>`/api/v2-beta/runs/${e}/cancel`,id=async(e,t)=>C(Q0(e),{...t,method:"POST"}),Y0=(e)=>`/api/v2-beta/datasets/${e}/exports`,nd=async(e,t,r)=>C(Y0(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),X0=(e)=>`/api/v2-beta/exports/${e}`,Js=async(e,t)=>C(X0(e),{...t,method:"GET"}),Z0=(e)=>`/api/v2-beta/pipelines/${e}/graph`,sd=async(e,t)=>C(Z0(e),{...t,method:"GET"}),ev=(e)=>`/api/v2-beta/pipelines/${e}/graph`,od=async(e,t,r)=>C(ev(e),{...r,method:"PUT",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),tv=(e)=>`/api/v2-beta/pipelines/${e}/graph/validate`,ad=async(e,t,r)=>C(tv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),rv=(e,t)=>`/api/v2-beta/pipelines/${e}/graph/nodes/${t}`,ld=async(e,t,r,i)=>C(rv(e,t),{...i,method:"PATCH",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),iv=(e)=>`/api/v2-beta/projects/${e}/secrets`,cd=async(e,t)=>C(iv(e),{...t,method:"GET"}),nv=(e,t)=>`/api/v2-beta/projects/${e}/secrets/${t}`,dd=async(e,t,r,i)=>C(nv(e,t),{...i,method:"PUT",headers:{"Content-Type":"application/json",...i?.headers},body:JSON.stringify(r)}),sv=(e)=>`/api/v2-beta/projects/${e}/files`,ud=async(e,t)=>C(sv(e),{...t,method:"GET"}),ov=(e)=>`/api/v2-beta/projects/${e}/files`,pd=async(e,t,r)=>C(ov(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),av=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}/finalize`,fd=async(e,t,r)=>C(av(e,t),{...r,method:"POST"}),lv=(e,t)=>`/api/v2-beta/projects/${e}/files/${t}`,md=async(e,t,r)=>C(lv(e,t),{...r,method:"DELETE"}),cv=(e,t)=>{let r=new URLSearchParams;Object.entries(t||{}).forEach(([n,s])=>{if(s!==void 0)r.append(n,s===null?"null":s.toString())});let i=r.toString();return i.length>0?`/api/v2-beta/runs/${e}/items?${i}`:`/api/v2-beta/runs/${e}/items`},Qs=async(e,t,r)=>C(cv(e,t),{...r,method:"GET"}),dv=(e,t)=>`/api/v2-beta/runs/${e}/items/${t}`,hd=async(e,t,r)=>C(dv(e,t),{...r,method:"GET"}),uv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,gd=async(e,t)=>C(uv(e),{...t,method:"GET"}),pv=(e)=>`/api/v2-beta/pipelines/${e}/checks`,yd=async(e,t,r)=>C(pv(e),{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(t)}),fv=(e)=>`/api/v2-beta/checks/${e}`,Ys=async(e,t)=>C(fv(e),{...t,method:"GET"});async function*mt(e,t={}){let r=t.offset;while(!0){let i=await e({limit:t.limit,offset:r});if(yield*i.items,!i.pagination.hasMore)return;r=i.pagination.offset+i.pagination.limit}}var Gr=async(e,t,r={})=>{let i=r.timeoutMs??60000,n=r.intervalMs??1000;_(Number.isFinite(i)&&i>=0,"The wait timeout must be a nonnegative finite number"),_(Number.isFinite(n)&&n>0,"The polling interval must be a positive finite number");let s=Date.now()+i,o=new AbortController,a=setTimeout(()=>o.abort(),i);try{while(!0){if(o.signal.aborted)throw re.waitTimeout(i);let c=await e(o.signal);if(t(c))return c;let u=s-Date.now();if(u<=0)throw re.waitTimeout(i);let{promise:l,resolve:d}=Promise.withResolvers();setTimeout(d,Math.min(n,u)),await l}}catch(c){if(o.signal.aborted)throw re.waitTimeout(i);throw c}finally{clearTimeout(a)}};var hv=(e)=>{let t=Lc(e.baseUrl,e.apiKey,e.fetch);async function r(l,d){switch(l.type){case"datasetUpload":return Gr((p)=>zs(l.uploadId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"datasetExport":return Gr((p)=>Js(l.exportId,{...t,signal:p}),(p)=>p.status==="succeeded",d);case"pipelineCheck":return Gr((p)=>Ys(l.checkRunId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d);case"pipelineRun":return Gr((p)=>Hs(l.runId,{...t,signal:p}),(p)=>p.status==="succeeded"||p.status==="failed",d)}}return{me:()=>qc(t),projects:{create:(l)=>Mc(l,t),get:({projectId:l})=>Uc(l,t),update:({projectId:l,...d})=>Bc(l,d,t),listPage:(l={})=>Ms(l,t),listAll:(l={})=>mt(async(d)=>{let p=await Ms({...l,...d},t);return{items:p.projects,pagination:p.pagination}},l)},pipelines:{import:({projectId:l,...d})=>Yc(l,d,t),get:({pipelineId:l})=>Gc(l,t),update:({pipelineId:l,...d})=>Vc(l,d,t),listPage:({projectId:l,...d})=>Us(l,d,t),listAll:({projectId:l,...d})=>mt(async(p)=>{let f=await Us(l,{...d,...p},t);return{items:f.pipelines,pagination:f.pagination}},d),getGraph:({pipelineId:l})=>sd(l,t),replaceGraph:({pipelineId:l,...d})=>od(l,"version"in d?{graph:d.graph,expectedVersion:d.version}:d,t),validateGraph:({pipelineId:l,...d})=>ad(l,d,t),estimateCost:({pipelineId:l,...d})=>td(l,d,t),patchNode:({pipelineId:l,nodeId:d,...p})=>ld(l,d,p,t),attachDataset:({pipelineId:l,...d})=>Xc(l,d,t),export:({pipelineId:l})=>Zc(l,t),copy:({pipelineId:l,...d})=>ed(l,d,t)},datasets:{create:({projectId:l,...d})=>Kc(l,d,t),get:({datasetId:l})=>zc(l,t),listPage:({projectId:l,...d})=>Bs(l,d,t),listAll:({projectId:l,...d})=>mt(async(p)=>{let f=await Bs(l,{...d,...p},t);return{items:f.datasets,pagination:f.pagination}},d),createField:async({datasetId:l,...d})=>{let p=await Vs(l,d,t);return _(!("fields"in p),"Creating one field must return that field"),p},createFields:async({datasetId:l,fields:d})=>{let p=await Vs(l,{fields:d},t);return _("fields"in p,"Creating several fields must return those fields"),p.fields},listFieldsPage:({datasetId:l,...d})=>Gs(l,d,t),getInferredFields:({datasetId:l})=>Wc(l,t),listAllFields:({datasetId:l,...d})=>mt(async(p)=>{let f=await Gs(l,{...d,...p},t);return{items:f.fields,pagination:f.pagination}},d),appendItems:({datasetId:l,...d})=>Hc(l,d,t),listItemsPage:({datasetId:l,...d})=>Ks(l,d,t),listAllItems:({datasetId:l,...d})=>mt(async(p)=>{let f=await Ks(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),startUpload:({datasetId:l,...d})=>Jc(l,d,t),finalizeUpload:({uploadId:l})=>Qc(l,t),getUpload:({uploadId:l})=>zs(l,t),startExport:({datasetId:l,...d})=>nd(l,d,t),getExport:({exportId:l})=>Js(l,t)},runs:{start:({pipelineId:l})=>{let d=new Headers(t.headers);return d.set("Content-Type","application/json"),rd(l,{...t,headers:d,body:"{}"})},get:({runId:l})=>Hs(l,t),cancel:({runId:l})=>id(l,t),listPage:({pipelineId:l,...d})=>Ws(l,d,t),listAll:({pipelineId:l,...d})=>mt(async(p)=>{let f=await Ws(l,{...d,...p},t);return{items:f.runs,pagination:f.pagination}},d),listItemsPage:({runId:l,...d})=>Qs(l,d,t),listAllItems:({runId:l,...d})=>mt(async(p)=>{let f=await Qs(l,{...d,...p},t);return{items:f.items,pagination:f.pagination}},d),getItem:({runId:l,itemId:d})=>hd(l,d,t)},secrets:{list:async({projectId:l})=>(await cd(l,t)).secrets,set:({projectId:l,name:d,...p})=>dd(l,d,p,t)},files:{list:async({projectId:l})=>(await ud(l,t)).files,startUpload:({projectId:l,...d})=>pd(l,d,t),finalizeUpload:({projectId:l,fileId:d})=>fd(l,d,t),delete:({projectId:l,fileId:d})=>md(l,d,t)},checks:{list:async({pipelineId:l})=>(await gd(l,t)).checks,start:({pipelineId:l,...d})=>yd(l,d,t),get:({checkRunId:l})=>Ys(l,t)},waitFor:r}};function it(e){return hv(e)}var gr=require("fs/promises"),Qa=require("path"),$f=xe(Ja(),1);var Nn="toloka.json";class Ya extends Error{constructor(e,t){super(e,t);this.name="TolokaStateError"}}var Mx="^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//).+$",Ux={type:"object",properties:{projectId:{type:"string",minLength:1},pipelines:{type:"object",propertyNames:{type:"string",pattern:Mx},additionalProperties:{type:"object",properties:{pipelineId:{type:"string",minLength:1}},required:["pipelineId"],additionalProperties:!1}},datasets:{type:"object",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",properties:{datasetId:{type:"string",minLength:1}},required:["datasetId"],additionalProperties:!1}}},required:["projectId","pipelines","datasets"],additionalProperties:!1},Bx=new $f.default({allErrors:!0,strict:!1}),wf=Bx.compile(Ux);function Gx(e){let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return`${typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/"}: ${e.message??`failed ${e.keyword} validation`}`}function Ef(e){if(wf(e))return e;let t=wf.errors;throw _(t,"toloka.json validation failed without errors"),new Ya(`Invalid toloka.json: ${t.map(Gx).join("; ")}`)}async function $e(e){let t;try{t=await gr.readFile(Qa.join(e,Nn),"utf8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return;throw r}try{return Ef(JSON.parse(t))}catch(r){if(r instanceof SyntaxError)throw new Ya(`Invalid toloka.json: ${r.message}`,{cause:r});throw r}}async function Nt(e,t){let r=Ef(t),i=Object.fromEntries(Object.entries(r.pipelines).sort(([s],[o])=>s<o?-1:s>o?1:0)),n=Object.fromEntries(Object.entries(r.datasets).sort(([s],[o])=>s<o?-1:s>o?1:0));await gr.mkdir(e,{recursive:!0}),await gr.writeFile(Qa.join(e,Nn),`${JSON.stringify({projectId:r.projectId,pipelines:i,datasets:n},null,2)}
|
|
38
|
-
`,"utf8")}var
|
|
39
|
-
`,{mode:384}),await
|
|
40
|
-
`);return e.io.stdout(r),{output:r}}async function
|
|
41
|
-
`),{cause:
|
|
42
|
-
`),{cause:
|
|
43
|
-
`);return e.io?.stdout(a),{output:a,projectId:s.id,alias:r}}var
|
|
44
|
-
`);function
|
|
45
|
-
`)};async function
|
|
46
|
-
${
|
|
47
|
-
`),
|
|
48
|
-
`),{cause:
|
|
49
|
-
`)}}async function
|
|
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
|
|
52
|
-
`)};let{value:
|
|
53
|
-
`)}}catch(
|
|
54
|
-
`)}}}var Ah=require("crypto"),zt=require("fs/promises"),_s=require("path");var Pr=require("path");function Wf(){let e=pR();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function pR(e=process.argv[1]?Pr.dirname(process.argv[1]):process.cwd(),t=Pr.sep==="\\"){let r=t?zf(e):e;return(i)=>{if(!i)return;let n=t?zf(i):i,{dir:s,base:o,ext:a}=Pr.posix.parse(n);if(a===".js"||a===".mjs"||a===".cjs")o=o.slice(0,-1*a.length);let c=decodeURIComponent(o);if(!s)s=".";let u=s.lastIndexOf("/node_modules");if(u>-1)return`${s.slice(u+14).replace(/\//g,".")}:${c}`;if(s.startsWith(r)){let l=s.slice(r.length+1).replace(/\//g,".");return l?`${l}:${c}`:c}return c}}function zf(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var il=(e)=>{if("flags"in e){let t=Hf(e.flags),r=Jf(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([n,s])=>[n,Vn(s)])),i=Object.fromEntries(Object.entries(t).map(([n,s])=>[n,fR(n,s,r[n])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}};function fR(e,t,r){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:r?JSON.stringify(r):void 0,description:void 0}}}var Hf=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,bi(r)]).filter(([,t])=>t!==void 0)),Jf=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let i=t[r];return i.enabled&&i.metadata&&i.metadata.payload!==void 0}).map((r)=>{let i=t[r].metadata?.payload;return[r,i?Vn(i):void 0]}))},bi=(e)=>e===void 0?void 0:e.variant??e.enabled,Vn=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var mR=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],vi=(e,t=[])=>{let r={},i=(n)=>{if(e[n]!==void 0)r[n]=e[n]};return mR.forEach(i),t.forEach(i),r};var Ee=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({});function nl(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var gR="NativeGzipValidationError",yR=31,_R=139,PR=8,bR=(e)=>e.length>=2&&e[0]===yR&&e[1]===_R;var wi,vR=()=>{if(wi)return wi;wi=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;wi[e]=t>>>0}return wi},wR=(e)=>{let t=vR(),r=4294967295;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(4294967295^r)>>>0},Kn=(e)=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name=gR,t},$R=async(e,t)=>{if(e.size<18)Kn("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!bR(r)||r[2]!==PR)Kn("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());if(i.getUint32(0,!0)!==wR(t))Kn("invalid-crc");let n=t.length>>>0;if(i.getUint32(4,!0)!==n)Kn("invalid-size")};async function qt(e,t=!0,r){try{let i=new TextEncoder().encode(e),n=new globalThis.CompressionStream("gzip"),s=n.writable.getWriter(),o=s.write(i).then(()=>s.close()).catch(async(u)=>{try{await s.abort(u)}catch{}throw u}),a=new Response(n.readable).blob(),[c]=await Promise.all([a,o]);return await $R(c,i),c}catch(i){if(r?.rethrow)throw i;if(t)console.error("Failed to gzip compress data",i);return null}}var ER=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Qf=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return ER.concat(t).some((i)=>{let n=i.toLowerCase();return r.indexOf(n)!==-1})};function br(e){let t=[];return JSON.stringify(e,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i=="function"||typeof i=="symbol")return;if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i})??"null"}var SR=Array.isArray,Yf=Object.prototype,uD=Yf.hasOwnProperty,zn=Yf.toString,He=SR||function(e){return zn.call(e)==="[object Array]"};var $i=(e)=>e===Object(e)&&!He(e);var Mt=(e)=>e===void 0,lt=(e)=>zn.call(e)=="[object String]",Xf=(e)=>lt(e)&&e.trim().length===0,Zf=(e)=>e===null;var Ei=(e)=>zn.call(e)=="[object Number]"&&e===e;var em=(e)=>zn.call(e)==="[object Boolean]";var tm=(e)=>e instanceof Error;function Wn(e){return e===null||typeof e!="object"}function Ut(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function rm(e){return Ut(e,"ErrorEvent")}function vr(e){return typeof Event<"u"&&xR(e,Event)}function im(e){return Ut(e,"Object")}function xR(e,t){try{return e instanceof t}catch{return!1}}function Ii(e,t,r,i,n){if(t>r)i.warn("min cannot be greater than max."),t=r;if(Ei(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else{if(!(e<t))return e;return i.warn(" cannot be less than min: "+t+". Using min value instead."),t}return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+n),Ii(n||r,t,r,i)}var RR=86400000,CR=1,jR=10;function nm(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??CR,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??jR}}class sl{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ii(e.bucketSize,0,100,e._logger),this._refillRate=Ii(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ii(e.refillInterval,0,RR,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,i=Math.floor(r/this._refillInterval);if(i>0){let n=i*this._refillRate;e.tokens=Math.min(e.tokens+n,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];if(i)this._applyRefill(i,t);else i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i;if(i.tokens===0)return!0;if(i.tokens--,i.tokens===0)this._onBucketRateLimited?.(e);return i.tokens===0}stop(){this._buckets={}}}/*! For license information please see uuidv7.mjs.LICENSE.txt */class Bt{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Bt(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>281474976710655||t>4095||r>1073741823||i>4294967295)throw RangeError("invalid field value");let n=new Uint8Array(16);return n[0]=e/1099511627776,n[1]=e/4294967296,n[2]=e/16777216,n[3]=e/65536,n[4]=e/256,n[5]=e,n[6]=112|t>>>8,n[7]=t,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new Bt(n)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let r=new Uint8Array(16);for(let i=0;i<16;i+=4){let n=parseInt(t.substring(2*i,2*i+8),16);r[i+0]=n>>>24,r[i+1]=n>>>16,r[i+2]=n>>>8,r[i+3]=n}return new Bt(r)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new Bt(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class om{constructor(e){this.timestamp=0,this.counter=0,this.random=e??FR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return Bt.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Bt.ofInner(e)}}var FR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),sm,Ie=()=>OR().toString(),OR=()=>(sm||(sm=new om)).generate();class ol{add(e){let t=Ie(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((i)=>i.id<=t&&!r.has(i.promise)).map((i)=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}function TR(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var am=(e,t,r)=>{function i(s,...o){t(()=>{let a=r[s];a(e,...o)})}return{debug:(...s)=>{i("debug",...s)},info:(...s)=>{i("log",...s)},warn:(...s)=>{i("warn",...s)},error:(...s)=>{i("error",...s)},critical:(...s)=>{r.error(e,...s)},createLogger:(s)=>am(`${e} ${s}`,t,r)}},AR=(e)=>e();function lm(e,t=AR){return am(e,t,TR())}var $r="Mobile",Jn="iOS",wr="Android",fm="Tablet",$D=wr+" "+fm;var DR="Apple",ED=DR+" Watch",mm="Safari",Qn="BlackBerry",hm="Samsung",NR=hm+"Browser",LR=hm+" Internet",Yn="Chrome",qR=Yn+" OS",MR=Yn+" "+Jn,gm="Internet Explorer",UR=gm+" "+$r,ll="Opera",ID=ll+" Mini",ym="Edge",BR="Microsoft "+ym,cl="Firefox",GR=cl+" "+Jn,dl="Nintendo",ul="PlayStation",Hn="Xbox",VR=wr+" "+$r,KR=$r+" "+mm,Si="Windows",zR=Si+" Phone";var _m="Generic",SD=_m+" "+$r.toLowerCase(),xD=_m+" "+fm.toLowerCase(),WR="Konqueror",HR="Oculus Browser",cm="Vivaldi",JR="Yandex",dm="Whale",QR="DuckDuckGo",YR="Pale Moon",um="Waterfox",pm="Brave",XR="Google Search App",H="(\\d+(\\.\\d+)?)",al=new RegExp("Version/"+H);var RD=new RegExp(Hn,"i"),CD=new RegExp(ul+" \\w+","i"),jD=new RegExp(dl+" \\w+","i"),ZR=new RegExp(Qn+"|PlayBook|BB10","i"),eC={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var FD={[UR]:[new RegExp("rv:"+H)],[BR]:[new RegExp(ym+"?\\/"+H)],[Yn]:[new RegExp("("+Yn+"|CrMo)\\/"+H)],[MR]:[new RegExp("CriOS\\/"+H)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+H)],[mm]:[al],[KR]:[al],[ll]:[new RegExp("("+ll+"|OPR)\\/"+H)],[cl]:[new RegExp(cl+"\\/"+H)],[GR]:[new RegExp("FxiOS\\/"+H)],[WR]:[new RegExp("Konqueror[:/]?"+H,"i")],[Qn]:[new RegExp(Qn+" "+H),al],[VR]:[new RegExp("android\\s"+H,"i")],[LR]:[new RegExp(NR+"\\/"+H)],[HR]:[new RegExp("OculusBrowser\\/"+H)],[cm]:[new RegExp(cm+"\\/"+H)],[JR]:[new RegExp("YaBrowser\\/"+H)],[dm]:[new RegExp(dm+"\\/"+H)],[pm]:[new RegExp(pm+"\\/"+H)],[QR]:[new RegExp("(DuckDuckGo|Ddg)\\/"+H)],[YR]:[new RegExp("PaleMoon\\/"+H)],[um]:[new RegExp(um+"\\/"+H)],[XR]:[new RegExp("GSA\\/"+H)],[gm]:[new RegExp("(rv:|MSIE )"+H)],Mozilla:[new RegExp("rv:"+H)]};var OD=[[new RegExp(Hn+"; "+Hn+" (.*?)[);]","i"),(e)=>[Hn,e&&e[1]||""]],[new RegExp(dl,"i"),[dl,""]],[new RegExp(ul,"i"),[ul,""]],[ZR,[Qn,""]],[new RegExp(Si,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[zR,""];if(new RegExp($r).test(t)&&!/IEMobile\b/.test(t))return[Si+" "+$r,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let i=r[1],n=eC[i]||"";if(/arm/i.test(t))n="RT";return[Si,n]}return[Si,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[Jn,t.join(".")]}return[Jn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=Mt(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+wr+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+wr+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[wr,t.join(".")]}return[wr,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[qR,""]],[/Linux|debian/i,["Linux",""]]];var Pm="utf8",tC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rC(e){return typeof e=="string"&&tC.test(e)}function Xn(e,t){return rC(e)?e:t()}function bm(e){return e?.replace(/\/+$/,"")}async function vm(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){if(i>0)await new Promise((n)=>setTimeout(n,t.retryDelay));try{return await e()}catch(n){if(r=n,!t.retryCheck(n))throw n}}throw r}function pl(){return new Date().toISOString()}function de(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}var wm=(e)=>e instanceof Error;function fl(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var nC={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},VD=nC.info;function ml(e){if(em(e))return{boolValue:e};if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e))return{intValue:e};return{doubleValue:e}}if(typeof e=="string")return{stringValue:e};if(He(e))return{arrayValue:{values:e.map((t)=>ml(t))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function xi(e){let t=[];for(let r in e){let i=e[r];if(!(Zf(i)||Mt(i)))t.push({key:r,value:ml(i)})}return t}var Ri=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function hl(e){return String(e)+"000000"}function gl(e,t,r,i){let n="";if(i)n=Object.keys(i).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(i[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${n}`}function $m(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function yl(e,t,r){return{...e.resourceAttributes,"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}function _l(e,t,r,i){return{resourceMetrics:[{resource:{attributes:xi(t)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]}}function Zn(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var Em=1;class es{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,i;try{r=t.attributes?{...t.attributes}:void 0,i=gl(t.type,t.name,t.unit,r)}catch(o){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let n=this._series.get(i);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(i,n)}let s=this._typeByName.get(t.name);if(s===void 0)this._typeByName.set(t.name,t.type);else if(s!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(n,t.value),this._armFlushTimer()}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(Ri.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[$m(t,Ri)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=He(t)?t:[t],i=e;for(let n of r)try{let s=n(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){if(this._flushTimer)return;this._flushTimer=de(()=>{this._flushTimer=void 0,this.flush().catch((e)=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs)}_clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){return _l(this._buildMetrics(e),yl(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=hl(Date.now()),r=new Map;for(let i of e.values()){let n=gl(i.type,i.name,i.unit,void 0),s=r.get(n);if(!s){if(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count")s.sum={aggregationTemporality:Em,isMonotonic:!0,dataPoints:[]};else if(i.type==="gauge")s.gauge={dataPoints:[]};else s.histogram={aggregationTemporality:Em,dataPoints:[]};r.set(n,s)}let o=xi(i.attributes??{}),a=hl(i.windowStartMs);if(i.type==="count"){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(c)}else if(i.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(c)}else if(i.hist){let c={attributes:o,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ri};s.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let i=this._series.get(t);if(!i){if(this._admitNewSeries())this._series.set(t,r);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,r.windowStartMs),i.type){case"count":i.total=(i.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(i.hist){i.hist.count+=r.hist.count,i.hist.sum+=r.hist.sum,i.hist.min=Math.min(i.hist.min,r.hist.min),i.hist.max=Math.max(i.hist.max,r.hist.max);for(let n=0;n<i.hist.bucketCounts.length;n++)i.hist.bucketCounts[n]+=r.hist.bucketCounts[n]}else i.hist=r.hist;break}}}}class Pl{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}var ve={};o_(ve,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ds,DOMExceptionCoercer:()=>Dm,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ci,ErrorCoercer:()=>ss,ErrorEventCoercer:()=>Nm,ErrorPropertiesBuilder:()=>is,EventCoercer:()=>qm,ExceptionStepsBuffer:()=>Bm,ObjectCoercer:()=>ls,PrimitiveCoercer:()=>cs,PromiseRejectionEventCoercer:()=>Mm,ReduceableCache:()=>Um,StringCoercer:()=>os,chromeStackLineParser:()=>bl,createDefaultStackParser:()=>wl,createStackParser:()=>km,geckoStackLineParser:()=>vl,getUtf8ByteLength:()=>Gm,nodeStackLineParser:()=>Fm,opera10StackLineParser:()=>Rm,opera11StackLineParser:()=>Cm,resolveExceptionStepsConfig:()=>$l,reverseAndStripFrames:()=>Am,stripReservedExceptionStepFields:()=>SC,winjsStackLineParser:()=>xm});var ts,Im,rs;function Sm(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);if(rs&&r.length===Im)return rs;return Im=r.length,rs=r.reduce((i,n)=>{if(!ts)ts={};let s=ts[n];if(s)i[s[0]]=s[1];else{let o=e(n);for(let a=o.length-1;a>=0;a--){let u=o[a]?.filename,l=t[n];if(u&&l){i[u]=l,ts[n]=[u,l];break}}}return i},{}),rs}var lC=4;class is{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),o=this.buildParsingContext(t),a=this.parseStacktrace(s,o);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&He(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r;if(e.cause!=null)r=this.parseStacktrace(e.cause,t);let i;if(e.stack!=""&&e.stack!=null)i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap);return{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};if(e.stack)r.stacktrace={type:"raw",frames:e.stack};let i=[r];if(e.cause!=null)i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0}));return i}buildParsingContext(e){return{chunkIdMap:Sm(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(s,o)=>{if(!(o<=lC))return;{let a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return{...t,syntheticException:r==0?t.syntheticException:void 0,mechanism:e,apply:(s)=>i(s,r),next:(s)=>i(s,r+1)}}}var se="?";function Je(e,t,r,i,n){let s={platform:e,filename:t,function:r==="<anonymous>"?se:r,in_app:!0};if(!Mt(i))s.lineno=i;if(!Mt(n))s.colno=n;return s}var ns=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,i=e.indexOf("safari-web-extension")!==-1;return r||i?[e.indexOf("@")!==-1?e.split("@")[0]:se,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var cC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,dC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,uC=/\((\S*)(?::(\d+))(?::(\d+))\)/,bl=(e,t)=>{let r=cC.exec(e);if(r){let[,n,s,o]=r;return Je(t,n,se,+s,+o)}let i=dC.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){let a=uC.exec(i[2]);if(a)i[2]=a[1],i[3]=a[2],i[4]=a[3]}let[s,o]=ns(i[1]||se,i[2]);return Je(t,o,s,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}};var pC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,vl=(e,t)=>{let r=pC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=fC.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let n=r[3],s=r[1]||se;return[s,n]=ns(s,n),Je(t,n,s,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var mC=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,xm=(e,t)=>{let r=mC.exec(e);return r?Je(t,r[2],r[1]||se,+r[3],r[4]?+r[4]:void 0):void 0};var hC=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Rm=(e,t)=>{let r=hC.exec(e);return r?Je(t,r[2],r[3]||se,+r[1]):void 0},gC=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Cm=(e,t)=>{let r=gC.exec(e);return r?Je(t,r[5],r[3]||r[4]||se,+r[1],+r[2]):void 0};var yC=/^\s*[-]{4,}$/,_C=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,PC=/^Promise\.(?:all|any)$/,bC=/^index \d+$/,vC="node:internal/promise",Fm=(e,t)=>{let r=e.match(_C);if(r){let i,n,s,o,a;if(r[1]){s=r[1];let l=s.lastIndexOf(".");if(s[l-1]===".")l--;if(l>0){i=s.slice(0,l),n=s.slice(l+1);let d=i.indexOf(".Module");if(d>0)s=s.slice(d+1),i=i.slice(0,d)}o=void 0}if(n)o=i,a=n;if(n==="<anonymous>")a=void 0,s=void 0;if(s===void 0)a=a||se,s=o?`${o}.${a}`:a;let c=r[2]?.startsWith("file://")?r[2].slice(7):r[2],u=r[5]==="native";if(c?.match(/\/[A-Z]:/))c=c.slice(1);if(!c&&r[5]&&!u)c=r[5];if(PC.test(s)&&bC.test(c||""))c=vC;return{filename:c?decodeURI(c):void 0,module:void 0,function:s,lineno:jm(r[3]),colno:jm(r[4]),in_app:wC(c||"",u),platform:t}}if(e.match(yC))return{filename:e,platform:t}};function wC(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function jm(e){return parseInt(e||"",10)||void 0}var Om=/\(error: (.*)\)/,Tm=50;function Am(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Tm).map((r)=>({...r,filename:r.filename||$C(t).filename,function:r.function||se}))}function $C(e){return e[e.length-1]||{}}function wl(){return km("web:javascript",bl,vl)}function km(e,...t){return(r,i=0)=>{let n=[],s=r.split(`
|
|
55
|
-
`);for(let o=i;o<s.length;o++){let a=s[o];if(a.length>1024)continue;let c=Om.test(a)?a.replace(Om,"$1"):a;if(!c.match(/\S*Error: /)){for(let u of t){let l=u(c,e);if(l){n.push(l);break}}if(n.length>=Tm)break}}return Am(n)}}class Dm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=lt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ut(e,"DOMException")}isDOMError(e){return Ut(e,"DOMError")}}class ss{match(e){return tm(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Nm{constructor(){}match(e){return rm(e)&&e.error!=null}coerce(e,t){let r=t.apply(e.error);if(!r)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return r}}var EC=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class os{match(e){return typeof e=="string"}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(EC);if(i)t=i[1],r=i[2];return[t,r]}}var Lm=["fatal","error","warning","log","info","debug"];function as(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let i=r.length;i>0;i--){let n=r.slice(0,i).join(", ");if(!(n.length>t)){if(i===r.length)return n;return n.length<=t?n:`${n.slice(0,t)}...`}}return""}class ls{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);return{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return vr(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")i+=` with message: '${e.message}'`;return i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),r=as(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return lt(e)&&!Xf(e)&&Lm.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(wm(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class qm{match(e){return vr(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${as(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class cs{match(e){return Wn(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class Mm{match(e){return Ut(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!vr(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);if(Wn(r))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}class Um{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Ci={MESSAGE:"$message",TIMESTAMP:"$timestamp"},IC=new Set([Ci.MESSAGE,Ci.TIMESTAMP]),ds={enabled:!0,max_bytes:32768};function $l(e){if(!e)return{...ds};return{enabled:e.enabled??ds.enabled,max_bytes:xC(e.max_bytes,ds.max_bytes)}}function SC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,n)=>{if(IC.has(n))return t.push(n),i;return i[n]=e[n],i},{}),droppedKeys:t}}class Bm{constructor(e){this._entries=[],this._totalBytes=0,this._config=$l(e)}setConfig(e){this._config=$l(e),this._trimToMaxBytes()}add(e){let t=RC(e);if(!t)return;let r=Gm(t.json);if(r>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes()}getAttachable(){return this._entries.map((e)=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let e=this._entries.shift();if(e)this._totalBytes-=e.bytes}}}function xC(e,t){if(!Ei(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);if(r<0)return t;return r}function RC(e){let t;try{t=br(e)}catch{return}try{let r=JSON.parse(t);if(!$i(r))return;let i=r,n=i[Ci.MESSAGE],s=i[Ci.TIMESTAMP];if(!lt(n)||n.trim().length===0)return;if(!lt(s)&&!Ei(s))return;return{step:i,json:t}}catch{return}}function Gm(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let i=0;i<t.length;i++)if(t[i]==="%")r+=1,i+=2;else r+=1;return r}class St extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class Gt extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var zm=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Vm(e){if(e instanceof St){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function CC(e){return typeof e=="object"&&(e instanceof St||Wm(e))}function Wm(e){return e instanceof Gt}function jC(e){if(e instanceof St)return e.status===502||e.status===504;if(!(e instanceof Gt))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function Er(e){return typeof e=="object"&&e instanceof St&&e.status===413}function ji(e){if(e instanceof St)return e.status===408||e.status===429||e.status>=500;return Wm(e)}function Km(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var El="default";class us{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new is([new ss,new ls,new os,new cs],wl())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ol,this._events=new Pl,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",n=!r;if(this._logger=lm("[PostHog]",this.logMsgIfDebug.bind(this)),n)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=bm(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:ji},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!nl()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(Ee.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Ee.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,i)=>this._logger.info(r,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};if(zm(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=vi(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",n,i)})}async captureStatelessImmediate(e,t,r,i){let n=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",n,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",n,i)})}async aliasStatelessImmediate(e,t,r,i){let n=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",n,i)}groupIdentifyStateless(e,t,r,i,n,s){this.wrap(()=>{let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});this.enqueue("capture",o,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,n,s){let o=this.buildPayload({distinct_id:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...s||{}}});await this.sendImmediate("capture",o,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((i)=>i.json()).catch((i)=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},r={},i={},n={},s=!1){await this._initPromise;let o=s?"&config=true":"",a=`${this.host}/flags/?v=2${o}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...n};if(r.$device_id)c.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)c.evaluation_contexts=this.evaluationContexts;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:jC},this.featureFlagsRequestTimeoutMs).then((l)=>l.json()).then((l)=>({success:!0,response:il(l)})).catch((l)=>(this._events.emit("error",l),{success:!1,error:this.categorizeRequestError(l)}))}categorizeRequestError(e){if(e instanceof St)return{type:"api_error",statusCode:e.status};if(e instanceof Gt){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,i,n,s);if(o===void 0)return{response:void 0,requestId:void 0};let a=bi(o.response);if(a===void 0)a=!1;return{response:a,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,i,n,s,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},n={},s){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,i,n,s,[e]);if(!o)return;let a=o[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},n,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},n,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,n,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,i,n,s);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},n,s){await this._initPromise;let o={geoip_disable:n??this.disableGeoip};if(s)o.flag_keys_to_evaluate=s;let a=await this.getFlags(e,t,r,i,o);if(!a.success)return;let c=a.response;if(c.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(c.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited};return c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(e,t).then((n)=>{if(n.status!==200||!n.json){let s=`Surveys API could not be loaded: ${n.status}`,o=Error(s);this._logger.error(o),this._events.emit("error",Error(s));return}return n.json()}).catch((n)=>{this._logger.error("Surveys API could not be loaded",n),this._events.emit("error",n)}))?.surveys;if(i)this._logger.info("Surveys fetched from API: ",JSON.stringify(i));return i??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Ee.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Ee.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Ee.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return El}persistedQueueKeyForRoute(e){return Ee.Queue}getActiveQueueRoutes(){return[El]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(n)||[];if(s.length>=this.maxQueueSize)s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(s.push({message:i}),this.setPersistedProperty(n,s),this._events.emit(e,i),s.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=de(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:i,...n}=e,s=Km(n.properties)?n.properties:void 0;if(r!==void 0&&s?.$lib===void 0)s={...s||{},$lib:r};if(i!==void 0&&s?.$lib_version===void 0)s={...s||{},$lib_version:i};if(s)n.properties=s;return n.uuid=Xn(n.uuid,Ie),n}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:pl(),uuid:Xn(t?.uuid,Ie)};if(t?.disableGeoip??this.disableGeoip){if(!Km(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await Vm(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter((n)=>!!n),i=0;while(!0){let n=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(n.length===0)return;if(i>0)this._logger.debug(`flush() re-checking ${n.length} pending promise(s) before flushing`);await Promise.all(n.map((s)=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>fl([t])).then(()=>{if(this.pendingFlushPromise===i)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),fl([i]).then(()=>{if(this.flushPromises.delete(i),this.pendingFlushPromise===i)this.pendingFlushPromise=null;if(this.flushPromise===i)this.flushPromise=null}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}async sendBatch(e,t,r=El){let i={api_key:this.apiKey,batch:e,sent_at:pl()};if(this.historicalMigration)i.historical_migration=!0;let n=br(i),s=`${this.host}/batch/`,o=this.disableCompression?null:await qt(n,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||n};await(await this.fetchWithRetry(s,a,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((i)=>this.getRouteQueue(i).length>0))return;let t=[],r;for(let i of e)try{await this._flushRoute(i,t)}catch(n){if(r===void 0)r=n}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let n=i.length,s=0;while(i.length>0&&s<n){let o=i.slice(0,this.maxBatchSize),a=o.map((l)=>l.message===void 0?l.message:this.normalizeMessage(l.message)),c=async()=>{let d=(this.getPersistedProperty(r)||[]).slice(o.length);this.setPersistedProperty(r,d),i=d,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},u={retryCheck:(l)=>{if(Er(l))return!1;return ji(l)}};try{await this.sendBatch(a,u,e)}catch(l){if(Er(l)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(l instanceof Gt))await c();throw this._events.emit("error",l),l}await c(),t.push(...a),s+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(s instanceof Gt)return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),r=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await qt(t,this.isDebug),n={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(r,n,{retryCheck:(s)=>{if(Er(s))return!1;return ji(s)}}),{kind:"ok"}}catch(s){if(Er(s))return{kind:"too-large"};if(ji(s))return{kind:"retry-later",error:s};return{kind:"fatal",error:s}}}async fetchWithRetry(e,t,r,i){let n=t.body?t.body:"",s=-1;try{s=n instanceof Blob?n.size:Buffer.byteLength(n,Pm)}catch{if(n instanceof Blob)s=n.size;else s=new TextEncoder().encode(n).length}return await vm(async()=>{let o=new AbortController,a=i??this.requestTimeout,c=de(()=>o.abort(),a),u=null;try{u=await this.fetch(e,{signal:o.signal,...t})}catch(d){throw new Gt(d)}finally{clearTimeout(c)}if(t.mode!=="no-cors"&&(u.status<200||u.status>=400))throw new St(u,s);return u},{...this._retryOptions,...r})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let r=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((o)=>this.getRouteQueue(o).length>0))break;let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(n){if(!CC(n))throw n;await Vm(n)}},i;try{return await Promise.race([new Promise((n,s)=>{i=de(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),r()])}finally{clearTimeout(i)}}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Qm=require("fs"),Ym=require("readline"),ps=new ve.ReduceableCache(25),Xm=new ve.ReduceableCache(20),Il=7,kC=1000,DC=1e4;async function Zm(e){let t={};for(let n=e.length-1;n>=0;n--){let s=e[n],o=s?.filename;if(!s||typeof o!="string"||typeof s.lineno!="number"||MC(o)||UC(s))continue;if(!t[o])t[o]=[];t[o].push(s.lineno)}let r=Object.keys(t);if(r.length==0)return e;let i=[];for(let n of r){if(Xm.get(n))continue;let s=t[n];if(!s)continue;s.sort((c,u)=>c-u);let o=GC(s);if(o.every((c)=>BC(n,c)))continue;let a=VC(ps,n,{});i.push(NC(n,o,a))}if(await Promise.all(i).catch(()=>{}),e&&e.length>0)LC(e,ps);return ps.reduce(),e}function NC(e,t,r){return new Promise((i)=>{let n=Qm.createReadStream(e),s=Ym.createInterface({input:n});function o(){n.destroy(),i()}let a=0,c=0,u=t[c];if(u===void 0)return void o();let l=u[0],d=u[1];function p(){Xm.set(e,1),s.close(),s.removeAllListeners(),o()}n.on("error",p),s.on("error",p),s.on("close",o),s.on("line",(f)=>{if(a++,a<l)return;if(r[a]=KC(f,0),a>=d){if(c===t.length-1){s.close(),s.removeAllListeners();return}c++;let m=t[c];if(m===void 0){s.close(),s.removeAllListeners();return}l=m[0],d=m[1]}})})}function LC(e,t){for(let r of e)if(r.filename&&r.context_line===void 0&&typeof r.lineno=="number"){let i=t.get(r.filename);if(i===void 0)continue;qC(r.lineno,r,i)}}function qC(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let n=eh(e);n<e;n++){let s=r[n];if(s===void 0)return void Hm(t);t.pre_context.push(s)}if(r[e]===void 0)return void Hm(t);t.context_line=r[e];let i=th(e);t.post_context=[];for(let n=e+1;n<=i;n++){let s=r[n];if(s===void 0)break;t.post_context.push(s)}}function Hm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function MC(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function UC(e){if(e.lineno!==void 0&&e.lineno>DC)return!0;if(e.colno!==void 0&&e.colno>kC)return!0;return!1}function BC(e,t){let r=ps.get(e);if(r===void 0)return!1;for(let i=t[0];i<=t[1];i++)if(r[i]===void 0)return!1;return!0}function GC(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let i=Jm(r),n=[];while(!0){if(t===e.length-1){n.push(i);break}let s=e[t+1];if(typeof s!="number")break;if(s<=i[1])i[1]=s+Il;else n.push(i),i=Jm(s);t++}return n}function Jm(e){return[eh(e),th(e)]}function eh(e){return Math.max(1,e-Il)}function th(e){return e+Il}function VC(e,t,r){let i=e.get(t);if(i===void 0)return e.set(t,r),r;return i}function KC(e,t){let r=e,i=r.length;if(i<=150)return r;if(t>i)t=i;let n=Math.max(t-60,0);if(n<5)n=0;let s=Math.min(n+140,i);if(s>i-5)s=i;if(s===i)n=Math.max(s-140,0);if(r=r.slice(n,s),n>0)r=`...${r}`;if(s<i)r+="...";return r}var Ir=require("path");function rh(e=process.cwd()){let t=Ir.sep==="\\",r=(n)=>t?n.replace(/\\/g,"/"):n,i=r(e);return async(n)=>{for(let s of n)if(!(!s.filename||s.filename.startsWith("node:")||s.filename.startsWith("data:"))){if(Ir.isAbsolute(s.filename))s.filename=r(Ir.relative(i,r(s.filename)))}return n}}var ih="5.46.1";var ct={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class Vt{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let n=this._flags[i];if(n)t[i]=n;else r.push(i)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let n=i.enabled===!1?!1:i.variant??!0;if(e[`$feature/${r}`]=n,i.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Vt({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)i.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let n=[];if(this._errorsWhileComputing)n.push(ct.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)n.push(ct.QUOTA_LIMITED);if(t===void 0)n.push(ct.FLAG_MISSING);if(n.length>0)i.$feature_flag_error=n.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function nh(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((n)=>n.toString(16).padStart(2,"0")).join("")}var zC=60000,WC=1152921504606847000,HC=["is_not","is_set"];class Sr extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,Sr.prototype)}}function lh(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class q extends Error{constructor(e){super(e);lh(this,q)}}class Qe extends Error{constructor(e){super(e);lh(this,Qe)}}class Sl{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:n,customHeaders:s,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=n,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=s,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},r={},i={},n={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:n}}async getFeatureFlag(e,t,r={},i={},n={}){await this.loadFeatureFlags();let s,o;if(!this.loadedSuccessfullyOnce)return s;if(o=this.featureFlagsByKey[e],o!==void 0){let a=this.createEvaluationContext(t,r,i,n);try{s=(await this.computeFlagAndPayloadLocally(o,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},n=this.featureFlags.length==0,s=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,o={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,o);if(r[a.key]=c,u)i[a.key]=u}catch(c){if(c instanceof Qe||c instanceof q)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`));else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:i,skipLoadCheck:n=!1}=r;if(!n)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let o=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:n,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new q("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(a!=null){let c=this.groupTypeMapping[String(a)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new q("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(n?.$device_id===void 0||n?.$device_id===null||n?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let u=s[c];return await this.matchFeatureFlagProperties(e,i[c],u,t)}{let c=this.getBucketingValueForFlag(e,r,n);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new q(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,n,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=r?.$device_id;if(i==null||i==="")return;return i}return t}getFeatureFlagPayload(e,t){let r=null;if(t!==!1&&t!=null){if(typeof t=="boolean")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(r!=null){if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{}return r}}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,n=e.key;if(!this.featureFlagsByKey)throw new q("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new q(`Flag dependency property for '${n}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new q(`Flag dependency property for '${n}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new q(`Circular dependency detected for flag '${n}' (empty dependency chain)`);for(let a of s){if(!(a in i)){let u=this.featureFlagsByKey[a];if(u)if(u.active)try{let l=await this.computeFlagValueLocally(u,r);i[a]=l}catch(l){throw new q(`Error evaluating flag dependency '${a}' for flag '${n}': ${l}`)}else i[a]=!1;else throw new q(`Missing flag dependency '${a}' for flag '${n}'`)}if(i[a]==null)throw new q(`Dependency '${a}' could not be evaluated`)}let o=i[n];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,r,i){let n=e.filters||{},s=n.groups||[],o=n.aggregation_group_type_index,a=n.early_exit??!1,{groups:c,groupProperties:u}=i,l=!1,d;for(let p of s)try{let f=p.aggregation_group_type_index!==void 0?p.aggregation_group_type_index:o,m=r,h=t;if(f!==o){if(f!=null){let y=this.groupTypeMapping[String(f)];if(!y||!(y in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${f} not available`));continue}if(!(y in u)){l=!0;continue}m=u[y],h=c[y]}}let g=await this.isConditionMatch(e,h,p,m,i);if(g==="match"){let y=p.variant,P=n.multivariate?.variants||[];d=y&&P.some((v)=>v.key===y)?y:await this.getMatchingVariant(e,h)||!0;break}if(a&&g==="out_of_rollout_bound")return!1}catch(f){if(f instanceof Qe)throw f;if(f instanceof q)l=!0;else throw f}if(d!==void 0)return d;if(l)throw new q("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,n){let s=r.rollout_percentage,o=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){for(let a of r.properties){let c=a.type,u=!1;if(c==="cohort"){let l=await dh(a,i,this.cohorts,this.debugMode,(d)=>this.evaluateFlagDependency(d,i,n));u=a.operator==="not_in"?!l:l}else u=c==="flag"?await this.evaluateFlagDependency(a,i,n):ch(a,i,o);if(!u)return"no_match"}if(s==null)return"match"}if(s!=null&&await sh(e.key,t)>s/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let r=await sh(e.key,t,"variant"),i=this.variantLookupTable(e).find((n)=>r>=n.valueMin&&r<n.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach((o)=>{i=r+o.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:o.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,r)=>(t[r.key]=r,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((r)=>r.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map((r)=>r.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(zC,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Sr(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Sr(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Sr(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:r.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(n){this.onError?.(Error(`Failed to store in cache: ${n}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){if(e instanceof Sr)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=de(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(r)}}async stopPoller(e=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await Promise.race([t,new Promise((r,i)=>setTimeout(()=>i(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function sh(e,t,r=""){let i=await nh(`${e}.${t}${r}`);return parseInt(i.slice(0,15),16)/WC}function ch(e,t,r){let{key:i,value:n}=e,s=e.operator||"exact";if(i in t){if(s==="is_not_set")return!1}else{if(s==="is_not_set")return!0;throw new q(`Property ${i} not found in propertyValues`)}let o=t[i];if(o==null&&!HC.includes(s)){if(r)r(`Property ${i} cannot have a value of null/undefined with the ${s} operator`);return!1}function a(u,l){if(Array.isArray(u))return u.map((d)=>String(d).toLowerCase()).includes(String(l).toLowerCase());return String(u).toLowerCase()===String(l).toLowerCase()}function c(u,l,d){if(d==="gt")return u>l;if(d==="gte")return u>=l;if(d==="lt")return u<l;if(d==="lte")return u<=l;throw Error(`Invalid operator: ${d}`)}switch(s){case"exact":return a(n,o);case"is_not":return!a(n,o);case"is_set":return i in t;case"icontains":return String(o).toLowerCase().includes(String(n).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(n).toLowerCase());case"regex":return oh(String(n))&&String(o).match(String(n))!==null;case"not_regex":return oh(String(n))&&String(o).match(String(n))===null;case"gt":case"gte":case"lt":case"lte":{let u=typeof n=="number"?n:parseFloat(String(n)),l;if(l=typeof o=="number"?o:o!=null?parseFloat(String(o)):NaN,Number.isFinite(u)&&Number.isFinite(l))return c(l,u,s);return c(String(o),String(n),s)}case"is_date_after":case"is_date_before":{if(typeof n=="boolean")throw new q("Date operations cannot be performed on boolean values");let u=ZC(String(n));if(u==null)u=ah(n);if(u==null)throw new q(`Invalid date: ${n}`);let l=ah(o);if(["is_date_before"].includes(s))return l<u;return l>u}case"semver_eq":return Oe(oe(String(o)),oe(String(n)))===0;case"semver_neq":return Oe(oe(String(o)),oe(String(n)))!==0;case"semver_gt":return Oe(oe(String(o)),oe(String(n)))>0;case"semver_gte":return Oe(oe(String(o)),oe(String(n)))>=0;case"semver_lt":return Oe(oe(String(o)),oe(String(n)))<0;case"semver_lte":return Oe(oe(String(o)),oe(String(n)))<=0;case"semver_tilde":{let u=oe(String(o)),{lower:l,upper:d}=QC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_caret":{let u=oe(String(o)),{lower:l,upper:d}=YC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}case"semver_wildcard":{let u=oe(String(o)),{lower:l,upper:d}=XC(String(n));return Oe(u,l)>=0&&Oe(u,d)<0}default:throw new q(`Unknown operator: ${s}`)}}function JC(e,t){if(!(e in t))throw new Qe(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function dh(e,t,r,i=!1,n){let s=String(e.value);JC(s,r);let o=r[s];return uh(o,t,r,i,n)}async function uh(e,t,r,i=!1,n){if(!e)return!0;let{type:s,values:o}=e;if(!o||o.length===0)return!0;let a=!1;if("values"in o[0]){for(let c of o)try{let u=await uh(c,t,r,i,n);if(s==="AND"){if(!u)return!1}else if(u)return!0}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("Can't match cohort without a given cohort property value");return s==="AND"}for(let c of o)try{let u;if(c.type==="cohort")u=await dh(c,t,r,i,n);else if(c.type==="flag"){if(!n)throw new q(`Flag dependency '${c.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);u=await n(c)}else u=ch(c,t);let l=c.negation||!1;if(s==="AND"){if(!u&&!l)return!1;if(u&&l)return!1}else{if(u&&!l)return!0;if(!u&&l)return!0}}catch(u){if(u instanceof Qe)throw u;if(u instanceof q){if(i)console.debug(`Failed to compute property ${c} locally: ${u}`);a=!0}else throw u}if(a)throw new q("can't match cohort without a given cohort property value");return s==="AND"}function oh(e){try{return new RegExp(e),!0}catch(t){return!1}}function ph(e,t){if(!/^\d+$/.test(e))throw new q(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new q(`Invalid semver: ${t}`);return parseInt(e,10)}function oe(e){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new q(`Invalid semver: ${e}`);let i=r.split("."),n=(c)=>{if(c===void 0||c==="")return 0;return ph(c,e)},s=n(i[0]),o=n(i[1]),a=n(i[2]);return[s,o,a]}function Oe(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function QC(e){let t=oe(e),r=[t[0],t[1],t[2]],i=[t[0],t[1]+1,0];return{lower:r,upper:i}}function YC(e){let t=oe(e),[r,i,n]=t,s=[r,i,n],o;return o=r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,n+1],{lower:s,upper:o}}function XC(e){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new q(`Invalid wildcard semver: ${e}`);let i=r.split("."),n=(c)=>{try{return ph(c,e)}catch{throw new q(`Invalid wildcard semver: ${e}`)}},s=n(i[0]),o,a;if(i.length===1)o=[s,0,0],a=[s+1,0,0];else{let c=n(i[1]);o=[s,c,0],a=[s,c+1,0]}return{lower:o,upper:a}}function ah(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new q(`${e} is in an invalid date format`)}throw new q(`The date provided ${e} must be a string, number, or date object`)}function ZC(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),i=new Date(new Date().toISOString());if(!r)return null;{if(!r.groups)return null;let n=parseInt(r.groups.number);if(n>=1e4)return null;let s=r.groups.interval;if(s=="h")i.setUTCHours(i.getUTCHours()-n);else if(s=="d")i.setUTCDate(i.getUTCDate()-n);else if(s=="w")i.setUTCDate(i.getUTCDate()-7*n);else if(s=="m")i.setUTCMonth(i.getUTCMonth()-n);else{if(s!="y")return null;i.setUTCFullYear(i.getUTCFullYear()-n)}return i}}function ej(e,t){let r=!1;return Object.assign((i)=>{let s=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length===0;if(e(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),!r&&s)r=!0,t(i)},{_posthogErrorHandler:!0})}function fh(e,t){globalThis.process?.on("uncaughtException",ej(e,t))}function mh(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var tj=2000;class Ye{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new sl({...nm(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return $i(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,i,n){let s={...n},o=e.buildFromUnknown(t,r);return o.$exception_list=await e.modifyFrames(o.$exception_list),{event:"$exception",distinctId:i,properties:{...o,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())fh(this.onException.bind(this),this.onFatalError.bind(this)),mh(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Ye.isPreviouslyCapturedError(e)){let r=await Ye.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),n=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(n))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(tj),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class xl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function rj(e){return e==="v0"||e==="v1"}function hh(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return rj(e)?e:"v0"}var Fi="analytics",Oi="ai";function gh(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class xr extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(xr.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let n=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(i instanceof Error)n+=` (${i.message})`;return n}}function Rl(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function ij(e){return typeof e=="string"?e:void 0}var nj=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Rl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Rl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Rl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:ij}],sj=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function oj(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aj(e){if(typeof e=="string"){let r=new Date(e);return Number.isNaN(r.getTime())?new Date().toISOString():e}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function yh(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function lj(e){let r={...oj(e.properties)?e.properties:{}},i={};for(let{property:s,optionKey:o,coerce:a}of nj)if(s in r){let c=a(r[s]);if(c!==void 0)i[o]=c;delete r[s]}let n={};for(let{property:s,field:o}of sj)if(s in r){let a=r[s];if(typeof a=="string")n[o]=a;delete r[s]}return delete r.$lib,delete r.$lib_version,yh(r,"$set",e.$set),yh(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:aj(e.timestamp),...n,options:i,properties:r}}function _h(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(lj)};if(r)i.historical_migration=!0;return i}var cj="/i/v1/analytics/events",dj=30000,uj=new Set([408,500,502,503,504]);class Cl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??dj,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((i)=>de(i,r))),this.generateRequestId=t.generateRequestId??Ie,this.compress=t.compress??qt}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=_h(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),n=`${this.config.host}${cj}`,s=[],o=i,a=Math.max(1,this.config.maxAttempts);for(let c=1;c<=a;c++){let u=c===a,l=br({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),d;try{d=await this.sendOnce(n,l,c,t)}catch(g){if(u)return this.surfaceBatchFailure(t,s,o,g);await this.sleep(this.backoffDelay(c));continue}let{status:p}=d;if(p<200||p>=300){if(!u&&uj.has(p)){let y=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(c,y));continue}let g=await this.buildHttpError(d,p);return this.surfaceBatchFailure(t,s,o,g)}let f;try{f=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(t,s,o,Error(`Capture V1 returned an unparseable ${p} response body`))}let m=this.classify(o,f,s);if(m.length===0)return this.surfacePartialDrops(t,s);if(u)return void this.onError(new xr({requestId:t,drops:s,retryExhausted:m.map((g)=>g.uuid)}));o=m;let h=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(c,h))}}async sendOnce(e,t,r,i){let n=this.buildHeaders(r,i),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);if(c!==null)s=c,n["Content-Encoding"]="gzip"}let o=new AbortController,a=de(()=>o.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:n,body:s,signal:o.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)i["User-Agent"]=this.config.userAgent;return i}classify(e,t,r){let i=t.results??{},n=[];for(let s of e){let o=i[s.uuid];if(o){if(o.result==="drop")r.push({uuid:s.uuid,details:o.details??void 0});else if(o.result==="retry")n.push(s)}}return n}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let s=parseInt(r,10);return Number.isFinite(s)&&s>0?1000*s:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let n=i-this.now();return n>0?n:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let i=r.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let r="";try{r=(await e.text()).slice(0,512)}catch{}let i=r?`: ${r}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,i){this.onError(new xr({requestId:e,drops:t,retryExhausted:r.map((n)=>n.uuid),cause:i}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new xr({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var pj=100,Ph=30000,fj=50000,mj=50,hj=500,gj="https://us.i.posthog.com",bh=new Set;function fs(e,t){if(bh.has(e))return;bh.add(e),console.warn(`[PostHog] ${t}`)}function yj(e){return typeof e=="string"?e.trim():""}function _j(e){return(typeof e=="string"?e.trim():"")||void 0}function Pj(e){return(typeof e=="string"?e.trim():"")||gj}function bj(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function vj(e){if(!e)return{};let t={};for(let[i,n]of Object.entries(e))t[`$feature/${i}`]=n;let r=Object.keys(e).filter((i)=>e[i]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class jl extends us{constructor(e,t={}){let r=yj(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:Pj(t.host),personalApiKey:_j(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new xl,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=hh(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,pj):Ph,typeof i.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0);if(typeof i.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0);if(!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(i.enableLocalEvaluation!==!1)this.featureFlagsPoller=new Sl({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:(s)=>{this._events.emit("error",s)},onLoad:(s)=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:(s)=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation})}this.errorTracking=new Ye(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||fj}enqueue(e,t,r){super.enqueue(e,t,r),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,o=new Promise((a)=>{s=a});try{e(o)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??hj,i=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(i)return void this.resolveWaitUntilFlush();let n=this.options.waitUntilDebounceMs??mj;this._waitUntilCycle.timer=de(()=>{this.resolveWaitUntilFlush()},n)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&gh(e)?Oi:Fi}persistedQueueKeyForRoute(e){return e===Oi?Ee.AiQueue:Ee.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Fi,Oi]:[Fi]}async sendBatch(e,t,r=Fi){if(this.captureMode!=="v1"||r===Oi)return super.sendBatch(e,t,r);let i=e.filter((n)=>n!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Cl({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e)});return this._v1Sender}getLibraryVersion(){return ih}get metrics(){if(!this._metrics)this._metrics=new es(this,Zn(this.options.metrics),this._logger);return this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:n,event:s,properties:o,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:s,properties:{...o,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c):this.enqueue(e,u,c)}).catch((n)=>{if(n)console.error(n)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:n,$anon_distinct_id:s,...o}=t,u={$set:i||o,$set_once:n||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:u,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let i={};if(Object.keys(t).length>0)i.$set=t;if(Object.keys(r).length>0)i.$set_once=r;this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=bj(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=Ph){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",(n)=>{clearTimeout(r),i(),t(n>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let n=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let E=this._flagOverrides[e];if(E===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:E!==!1,variant:typeof E=="string"?E:void 0,payload:x}}let{groups:s,disableGeoip:o}=r,{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=r,l=this.addLocalPersonAndGroupProperties(t,s,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p,f=!1,m,h,g,y,P,v,w;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let E=this.featureFlagsPoller?.featureFlagsByKey[e];if(E)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(E,d,{matchValue:i});if(x){f=!0;let T=x.value;y=E.id,v="Evaluated locally",w=E.has_experiment,p={key:e,enabled:T!==!1,variant:typeof T=="string"?T:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof Qe||x instanceof q)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!f&&!a){let E=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,o,[e]);if(E===void 0)g=ct.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=E.minimalFlagCalledEvents===!0,m=E.requestId,h=E.evaluatedAt;let x=[];if(E.errorsWhileComputingFlags)x.push(ct.ERRORS_WHILE_COMPUTING);if(E.quotaLimited?.includes("feature_flags"))x.push(ct.QUOTA_LIMITED);let T=E.flags[e];if(T===void 0)x.push(ct.FLAG_MISSING);else{y=T.metadata?.id,P=T.metadata?.version,v=T.reason?.description??T.reason?.code,w=T.metadata?.has_experiment;let R;if(T.metadata?.payload!==void 0)try{R=JSON.parse(T.metadata.payload)}catch{R=T.metadata.payload}p={key:e,enabled:T.enabled,variant:T.variant,payload:R}}if(x.length>0)g=x.join(",")}}if(n){let E=p===void 0?void 0:p.enabled===!1?!1:p.variant??!0,x={$feature_flag:e,$feature_flag_response:E,$feature_flag_id:y,$feature_flag_version:P,$feature_flag_reason:v,locally_evaluated:f,[`$feature/${e}`]:E,$feature_flag_request_id:m,$feature_flag_evaluated_at:f?Date.now():h};if(w!==void 0)x.$feature_flag_has_experiment=w;if(f&&this.featureFlagsPoller){let T=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(T!==void 0)x.$feature_flag_definitions_loaded_at=T}if(g)x.$feature_flag_error=g;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:E,groups:s,disableGeoip:o,properties:x})}if(p!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)p={...p,payload:this._payloadOverrides[e]};return p}async getFeatureFlag(e,t,r){fs("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return i.variant??!0}async getFeatureFlagPayload(e,t,r,i){if(fs("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let n=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(n===void 0)return;return n.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:n}=this._resolveDistinctId(t,r);if(!i)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,i,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(i){}return r}async isFeatureEnabled(e,t,r){fs("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i===void 0)return;if(i.enabled===!1)return!1;return!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),f={},m={},h=!0;if(p)f=p.response,m=p.payloads,h=p.fallbackToFlags;if(h&&!a){let g=await super.getFeatureFlagsAndPayloadsStateless(d.distinctId,d.groups,c,u,s,o);f={...f,...g.flags||{}},m={...m,...g.payloads||{}}}if(this._flagOverrides!==void 0)f={...f,...this._flagOverrides};if(this._payloadOverrides!==void 0)m={...m,...this._payloadOverrides};return{featureFlags:f,featureFlagPayloads:m}}async evaluateFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:n,disableGeoip:s,flagKeys:o}=i||{},{onlyEvaluateLocally:a,personProperties:c,groupProperties:u}=i||{},l=this.addLocalPersonAndGroupProperties(r,n,c,u);c=l.allPersonProperties,u=l.allGroupProperties;let d=this.createFeatureFlagEvaluationContext(r,n,this.personPropertiesForLocalEvaluation(r,c),u);if(a==null)a=this.options.strictLocalEvaluation??!1;let p={},f,m,h=!1,g=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(d,o),P=new Set;if(y)for(let[w,I]of Object.entries(y.response)){let E=this.featureFlagsPoller?.featureFlagsByKey[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:y.payloads[w],id:E?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:E?.has_experiment},P.add(w)}if((y?y.fallbackToFlags:!0)&&!a){let w=await super.getFeatureFlagDetailsStateless(d.distinctId,d.groups,c,u,s,o);if(w){this._minimalFlagCalledEvents=w.minimalFlagCalledEvents===!0,f=w.requestId,m=w.evaluatedAt,h=Boolean(w.errorsWhileComputingFlags),g=Array.isArray(w.quotaLimited)&&w.quotaLimited.includes("feature_flags");for(let[I,E]of Object.entries(w.flags)){if(P.has(I))continue;let x;if(E.metadata?.payload!==void 0)try{x=JSON.parse(E.metadata.payload)}catch{x=E.metadata.payload}p[I]={key:I,enabled:E.enabled,variant:E.variant,payload:x,id:E.metadata?.id,version:E.metadata?.version,reason:E.reason?.description??E.reason?.code,locallyEvaluated:!1,hasExperiment:E.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[w,I]of Object.entries(this._flagOverrides)){if(I===void 0){delete p[w];continue}let E=p[w];p[w]={key:w,enabled:I!==!1,variant:typeof I=="string"?I:void 0,payload:E?.payload,id:E?.id,version:E?.version,reason:E?.reason,locallyEvaluated:E?.locallyEvaluated??!1,hasExperiment:E?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[w,I]of Object.entries(this._payloadOverrides)){let E=p[w];if(E)p[w]={...E,payload:I}}return new Vt({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:n,disableGeoip:s,flags:p,requestId:f,evaluatedAt:m,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:h,quotaLimited:g})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:n,disableGeoip:s,properties:o}=e,a=n&&Object.keys(n).length>0?`_${JSON.stringify(Object.entries(n).sort(([u],[l])=>u<l?-1:u>l?1:0))}`:"",c=`${r}_${i}${a}`;if(t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c))return;if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(this.distinctIdHasSentFlagCalls[t]instanceof Set)this.distinctIdHasSentFlagCalls[t].add(c);else this.distinctIdHasSentFlagCalls[t]=new Set([c]);this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:n,disableGeoip:s})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:n}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:n},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.map((i)=>[i,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((i)=>de(i,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let n=new AbortController;i=de(()=>{n.abort()},this.options.requestTimeout),r.signal=n.signal}try{return await this.fetch(t,r)}catch(n){this._events.emit("error",n);return}finally{if(i)clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[n,s]of Object.entries(e))if(im(s)&&t&&n in t){let o={};for(let[a,c]of Object.entries(s))o[String(a)]=String(c);i[String(n)]=o}else r[String(n)]=String(s);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let n=i?.personProperties||{},s=i?.groupProperties||{},o=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[u,l]of Object.entries(t||{}))c[u]=String(l);return await this.getAllFlags(e,{groups:c,personProperties:n,groupProperties:s,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,n,s,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let n={...r||{}},s={};if(t)for(let o of Object.keys(t))s[o]={$group_key:t[o],...i?.[o]||{}};return{allPersonProperties:n,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,n){if(!Ye.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:i,flags:n},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!Ye.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");return this.addPendingPromise(Ye.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((s)=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:n,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l}=e,d=this.context?.get(),p=t.includeContextProperties??!0,f=r||d?.distinctId,m=p?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};if(!f)f=Ie(),m.$process_person_profile=!1;if(p&&d?.sessionId&&!m.$session_id)m.$session_id=d.sessionId;let h=this._shouldSendMinimalFlagCalledEvent(i,m)?vi(m):m,g=this._runBeforeSend({distinctId:f,event:i,properties:h,groups:s,flags:o,sendFeatureFlags:a,timestamp:c,disableGeoip:u,uuid:l});if(!g)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(o){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(a){fs("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let P=typeof a=="object"?a:void 0,v=await this.getFeatureFlagsForEvent(g.distinctId,s,u,P);return vj(v)}return{}}).catch(()=>({})).then((P)=>{let v=g.groups||s;return{...P,...g.properties||{},...v!==void 0&&Object.keys(v).length>0?{$groups:v}:{}}});if(g.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof y.$raw_user_agent=="string"){if(Qf(y.$raw_user_agent,this.options.custom_blocked_useragents||[]))g.event="$bot_pageview",y.$browser_type="bot"}return{distinctId:g.distinctId,event:g.event,properties:y,options:{timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let n of r){if(i=n(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}}var vh=require("async_hooks");class Fl{constructor(){this.storage=new vh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function wj(e,{organization:t,projectId:r,prefix:i,severityAllowList:n=["error"],sendExceptionsToPostHog:s=!0}={}){return(o)=>{if(!(n==="*"||n.includes(o.level)))return o;if(!o.tags)o.tags={};let c=o.tags[wh.POSTHOG_ID_TAG];if(c===void 0)return o;let u=e.options.host??"https://us.i.posthog.com",l=new URL(`/project/${e.apiKey}/person/${c}`,u).toString();o.tags["PostHog Person URL"]=l;let d=o.exception?.values||[],p=d.map((m)=>({...m,stacktrace:m.stacktrace?{...m.stacktrace,type:"raw",frames:(m.stacktrace.frames||[]).map((h)=>({...h,platform:"node:javascript"}))}:void 0})),f={$exception_message:d[0]?.value||o.message,$exception_type:d[0]?.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:d[0]?.value||o.message,$sentry_exception_type:d[0]?.type,$sentry_tags:o.tags};if(t&&r)f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(s)e.capture({event:"$exception",distinctId:c,properties:f});return o}}class wh{static#r=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,n){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(s,o){let a=o()?.getClient()?.getDsn()?.projectId;s(wj(e,{organization:t,projectId:a,prefix:r,severityAllowList:i,sendExceptionsToPostHog:n??!0}))}}}class Ol extends jl{getLibraryId(){return"posthog-node"}initializeContext(){return new Fl}createErrorPropertiesBuilder(){return new ve.ErrorPropertiesBuilder([new ve.EventCoercer,new ve.ErrorCoercer,new ve.ObjectCoercer,new ve.StringCoercer,new ve.PrimitiveCoercer],ve.createStackParser("node:javascript",ve.nodeStackLineParser),[Wf(),Zm,rh()])}}var Eh=require("crypto"),Z=require("fs/promises"),Y=require("path");var $h={name:"@toloka-platform/sdk",version:"0.1.0-preview.4",private:!1,description:"Preview. Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change.",license:"Apache-2.0",bin:{toloka:"bin/toloka.js"},files:["README.md","bin","docs","dist","examples","openapi/gen","skills","src"],type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"preview"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js",prepack:"bun run build",test:"vitest run",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","posthog-node":"5.46.1"},devDependencies:{"@types/node":"24.10.1",orval:"7.17.0",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},engines:{bun:"1.4.0"}};var Kt=$h.version,dt="@toloka-platform/sdk",hs="toloka-build",Ih=`.claude/skills/${hs}/SKILL.md`,Sh=`.cursor/rules/${hs}.mdc`,Rr="AGENTS.md",ms="<!-- toloka:begin -->",Ti="<!-- toloka:end -->",Ej=/<!-- toloka:sdk-version ([^\s>]+) -->/u,Ij=/<!-- toloka:skill-digest sha256:([a-f0-9]{64}) -->/u,Sj=[Ih,Sh,Rr],xh="toloka-pipeline-as-code",Rh=Y.join(".claude","skills",xh),Ch=Y.join(".cursor","rules",`${xh}.mdc`),xj=[Rh,Ch],Rj=[Y.join(Rh,"SKILL.md"),Ch],Cj=[["SKILL.md",new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/node-semantics.md",new URL("../../skills/references/node-semantics.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")],["references/workflow-and-cli.md",new URL("../../skills/references/workflow-and-cli.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts")]],Ai=(e)=>e instanceof Error&&("code"in e)&&e.code==="ENOENT",gs=async(e)=>{try{return await Z.readFile(e,"utf8")}catch(t){if(Ai(t))return;throw t}},Tl=async(e)=>{try{return(await Z.lstat(e)).isDirectory()}catch(t){if(Ai(t))return!1;throw t}},jj=async(e)=>{try{return(await Z.lstat(e)).isFile()}catch(t){if(Ai(t))return!1;throw t}},jh=async(e,t)=>{let r=e;for(let i of t.split("/")){r=Y.join(r,i);try{let n=await Z.lstat(r);_(!n.isSymbolicLink(),`Refusing to write through symbolic link ${r}.`)}catch(n){if(Ai(n))return;throw n}}};async function Fh(){let e=Eh.createHash("sha256");for(let[t,r]of Cj)e.update(t),e.update("\x00"),e.update(await Z.readFile(r)),e.update("\x00");return e.digest("hex")}var Fj=new URL("../../skills/SKILL.md","file:///Users/gzarip/code/potato-pr-1367/packages/sdk/src/cli/init.ts"),Oj=`node_modules/${dt}/skills/references/`,Tj=async(e)=>{let n=(await Z.readFile(Fj,"utf8")).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/u,"").replace(/^#\s.*\r?\n+/u,"").replaceAll("](references/",`](${Oj}`).replaceAll("](../examples/",`](node_modules/${dt}/examples/`);return e==="##"?n:n.replaceAll(/^## /gmu,"### ")},Al=async(e,t)=>`Generated by \`${dt}\` version \`${Kt}\`.
|
|
56
|
-
|
|
57
|
-
|
|
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}
|
|
58
59
|
|
|
59
|
-
|
|
60
|
-
Use the globally installed \`toloka\` binary. Install it with \`curl -fsSL https://platform.toloka.ai/cli/install.sh | sh\` if it is not on \`PATH\`.
|
|
60
|
+
## Toloka Agent Bootstrap
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
${$g}
|
|
63
|
+
Re-run \`toloka init\` to refresh this block. Keep your own instructions outside it.
|
|
63
64
|
|
|
64
|
-
|
|
65
|
-
name: ${hs}
|
|
66
|
-
description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka. Use when the user wants to create, adopt, inspect, plan, or apply a pipeline project as code.
|
|
67
|
-
---
|
|
65
|
+
This repository works with the Toloka platform through the \`toloka\` CLI. Before starting a Toloka task:
|
|
68
66
|
|
|
69
|
-
|
|
67
|
+
1. Run \`toloka --help\`, then \`toloka <resource> --help\` for the resource you need.
|
|
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 \`${Dr}/<skill-id>/${kr}\` before acting; add \`--force\` to refresh a stale skill.
|
|
70
|
+
4. Follow the installed skill. When no skill matches, continue with the CLI help and never invent commands or SDK helpers.
|
|
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.
|
|
70
72
|
|
|
71
|
-
${
|
|
72
|
-
description: Build, inspect, and change Toloka platform pipeline projects as TypeScript source with @toloka-platform/sdk and toloka
|
|
73
|
-
alwaysApply: false
|
|
74
|
-
---
|
|
73
|
+
${Nr.end}`,Ig=`# Toloka Agent Bootstrap pointer
|
|
75
74
|
|
|
76
|
-
|
|
75
|
+
${$g}
|
|
77
76
|
|
|
78
|
-
|
|
79
|
-
|
|
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
|
+
---
|
|
82
|
+
|
|
83
|
+
${Ig}`,eF=`---
|
|
84
|
+
description: Toloka Agent Bootstrap pointer for the toloka CLI and ${ze}
|
|
85
|
+
alwaysApply: true
|
|
86
|
+
---
|
|
80
87
|
|
|
81
|
-
${(
|
|
82
|
-
${Ti}`,Nj=(e,t)=>{let r=e.indexOf(ms),i=e.indexOf(Ti),n=r!==-1,s=i!==-1,o=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
|
|
83
89
|
`)?`\r
|
|
84
90
|
`:`
|
|
85
|
-
`,
|
|
86
|
-
`,o
|
|
87
|
-
`),
|
|
88
|
-
`,{mode:384}),await
|
|
89
|
-
${e.map((s)=>`${
|
|
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(`,
|
|
90
96
|
`)}
|
|
91
|
-
${
|
|
92
|
-
${r.map(([
|
|
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(`,
|
|
93
99
|
`)}
|
|
94
|
-
${
|
|
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(`
|
|
95
101
|
`)}
|
|
96
102
|
|
|
97
103
|
export const ${t} = ${e.type}(
|
|
98
|
-
${
|
|
104
|
+
${d.join(`,
|
|
99
105
|
`)}
|
|
100
106
|
);
|
|
101
|
-
`}}function
|
|
107
|
+
`}}function Ng(e,t){if(e.length===0)return`export {};
|
|
102
108
|
`;return`import { field } from '@toloka-platform/sdk';
|
|
103
109
|
|
|
104
|
-
${e.map((
|
|
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(
|
|
105
111
|
${s.join(`,
|
|
106
112
|
`)}
|
|
107
|
-
);`}}).toSorted((i
|
|
113
|
+
);`}}).toSorted((n,i)=>Ft(n.binding,i.binding)).map(({source:n})=>n).join(`
|
|
108
114
|
|
|
109
115
|
`)}
|
|
110
|
-
`}function
|
|
111
|
-
${
|
|
112
|
-
${
|
|
113
|
-
${
|
|
114
|
-
${
|
|
115
|
-
${
|
|
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(`,
|
|
116
122
|
`)}
|
|
117
|
-
${
|
|
123
|
+
${ne(h)}]`};return`${o.join(`
|
|
118
124
|
`)}
|
|
119
125
|
|
|
120
126
|
export default definePipeline({
|
|
121
|
-
dataset: ${
|
|
122
|
-
fields: ${
|
|
123
|
-
nodes: ${l
|
|
124
|
-
connections: ${
|
|
127
|
+
dataset: ${ke(t)},
|
|
128
|
+
fields: ${c(a,1)},
|
|
129
|
+
nodes: ${c(l,1)},
|
|
130
|
+
connections: ${c(d,1)}
|
|
125
131
|
});
|
|
126
|
-
`}function zh(e,t={dataset:"imported-dataset"}){let r=[...e.fields.map((u)=>({key:`field:${u.id}`,name:u.name,fallback:"field"})),...e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type}))],i=Dl(r,({name:u,fallback:l})=>Gh(u,l),Uh),n=Dl(e.nodes.map((u)=>({key:`node:${u.id}`,name:u.type==="root"?"root":u.settings.about.name||u.type,fallback:u.type})),({name:u,fallback:l})=>rF(u,l)),s=new Map(e.fields.map((u)=>{let l=i.get(`field:${u.id}`);return _(l,`Field "${u.id}" has no allocated binding`),[u.id,l]})),o=new Map(e.nodes.map((u)=>{let l=i.get(`node:${u.id}`);return _(l,`Node "${u.id}" has no allocated binding`),[u.id,l]})),a=e.nodes.map((u)=>{let l=o.get(u.id),d=n.get(`node:${u.id}`);return _(l&&d,`Node "${u.id}" has no allocated source name`),sF(u,l,`nodes/${d}/node.ts`,s)}),c=[{path:"fields.ts",source:oF(e,s)},...a.map(({path:u,source:l})=>({path:u,source:l})),{path:"pipeline.ts",source:aF(e,t.dataset,a,s,o)}].toSorted((u,l)=>xt(u.path,l.path));return Object.fromEntries(c.map(({path:u,source:l})=>[u,l]))}var ut=require("fs/promises"),Wt=require("path");var fg=xe(Ja(),1),mg=xe(dg(),1);var ug={$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",properties:{version:{type:"number",const:1},fields:{maxItems:500,type:"array",items:{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},name:{type:"string"},jsonSchema:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1,ref:"JsonSchema"}},required:["id","name","jsonSchema"],additionalProperties:!1}},nodes:{maxItems:500,type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"root"},settings:{type:"object",properties:{datasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},itemFilter:{type:"object",properties:{fieldValues:{default:[],type:"array",items:{type:"object",properties:{jsonPath:{type:"string",minLength:1},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},latestOnly:{default:!0,type:"boolean"},sources:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["jsonPath","operator","value","fieldId"],additionalProperties:!1}},fieldSources:{default:[],type:"array",items:{type:"object",properties:{fieldId:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},sources:{minItems:1,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"user"},userId:{type:"string",minLength:1}},required:["type","userId"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"system"},source:{type:"string",minLength:1}},required:["type","source"],additionalProperties:!1}]}}},required:["fieldId","sources"],additionalProperties:!1}},missingRevisionFields:{default:[],type:"array",items:{type:"string",pattern:"^df\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"}},createdBefore:{type:"string",format:"date-time",pattern:"^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"}},additionalProperties:!1},itemLimit:{type:"integer",exclusiveMinimum:0,maximum:9007199254740991},startedFieldProxies:{type:"object",properties:{output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["output"]},completedFieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["startedFieldProxies","completedFieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"code"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}},output:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input","output"]},code:{type:"object",properties:{code:{type:"string"}},required:["code"],additionalProperties:!1},envVars:{default:[],type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"static"},name:{type:"string"},value:{type:"string"}},required:["type","name","value"],additionalProperties:!1},{type:"object",properties:{type:{type:"string",const:"secret"},name:{type:"string"},secretName:{type:"string"}},required:["type","name","secretName"],additionalProperties:!1}]}},checks:{type:"object",propertyNames:{type:"string",enum:["code"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["code"]}},required:["about","fieldProxies","code"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"generation"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"human_only"},smartSamplingPercent:{default:100,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"hybrid"},smartSamplingPercent:{default:30,type:"number",minimum:10,maximum:100},humanQaTimeForTask:{type:"number",exclusiveMinimum:0},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]}]},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},oneOf:[{type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},{type:"object",properties:{audienceType:{type:"string",const:"synthetic"},generationModelId:{default:"gpt-5.6-terra",type:"string",enum:["gpt-5.4","gpt-5.4-mini","claude-sonnet-4-6","gemini-3.1-pro-preview","gemini-3.5-flash","claude-sonnet-5","gpt-5.6-terra","gpt-5.6-luna"]},reasoningEffort:{type:"string",enum:["low","medium","high"]},llmInstruction:{default:"",type:"string"}},required:["audienceType"],additionalProperties:!1}]},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset","synthgen"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"match"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},conditions:{type:"array",items:{type:"object",properties:{name:{type:"string"},logic:{default:"and",type:"string",enum:["and","or"]},predicates:{type:"array",items:{type:"object",properties:{fieldProxyId:{type:"string"},jsonPath:{type:"string"},operator:{type:"string",enum:["text_eq","text_neq"]},value:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]}},required:["fieldProxyId","jsonPath","operator","value"],additionalProperties:!1}}},required:["name","predicates"],additionalProperties:!1}},fieldProxies:{type:"object",properties:{input:{type:"array",items:{type:"object",properties:{id:{type:"string"},optional:{type:"boolean"}},required:["id","optional"],additionalProperties:!1}}},required:["input"]}},required:["about","conditions","fieldProxies"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1},{type:"object",properties:{id:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},type:{type:"string",const:"quorum"},settings:{type:"object",properties:{about:{type:"object",properties:{name:{type:"string"},description:{type:"string"},projectType:{type:"string",enum:["general","data_collection"]}},required:["name"],additionalProperties:!1},publicName:{type:"string"},audienceAndPricing:{default:{audienceType:"human",verifiedExperts:!0,audience:{languages:{type:"and",values:[]},specializations:{type:"and",values:[]},countries:{type:"or",values:[]}},pricePerTask:1,timeForTask:1800,perExpertCapEnabled:!1,perExpertCapValue:1},type:"object",properties:{verifiedExperts:{type:"boolean"},audience:{type:"object",properties:{languages:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"}},required:["value"]}}},required:["type","values"],additionalProperties:!1},specializations:{type:"object",properties:{type:{type:"string",enum:["or","and"]},values:{type:"array",items:{type:"object",properties:{value:{type:"string"},qualificationId:{type:"string"}},required:["value","qualificationId"],additionalProperties:!1}}},required:["type","values"],additionalProperties:!1},countries:{type:"object",properties:{type:{type:"string",enum:["or"]},values:{type:"array",items:{type:"string"}}},required:["type","values"],additionalProperties:!1}},required:["languages","specializations","countries"],additionalProperties:!1},pricePerTask:{type:"number"},timeForTask:{type:"number"},perExpertCapEnabled:{default:!1,type:"boolean"},perExpertCapValue:{default:1,type:"integer",exclusiveMinimum:0,maximum:50},audienceType:{type:"string",const:"human"}},required:["verifiedExperts","audience","pricePerTask","timeForTask","audienceType"],additionalProperties:!1},entities:{type:"object",properties:{input:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}},output:{type:"array",items:{oneOf:[{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!1},maxEntities:{type:"null"}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1},{type:"object",properties:{fieldProxyId:{type:"string"},entityType:{type:"string"},optional:{type:"boolean"},jsonPath:{type:"string"},description:{type:"string"},relations:{type:"array",items:{anyOf:[{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",enum:["context","references","depends_on","evaluates"]}},required:["id","rel_type"]},{type:"object",properties:{id:{type:"string"},rel_type:{type:"string",const:"conditional"},condition:{type:"object",properties:{operator:{type:"string",enum:["EQ","NEQ","IN","NOT_IN","NOT_EMPTY"]},value:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["operator","value"]}},required:["id","rel_type","condition"]}]}},minDurationSeconds:{type:"number",exclusiveMinimum:0},maxDurationSeconds:{type:"number",exclusiveMinimum:0},allowedLabels:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"}},required:["label","value"],additionalProperties:!1}},dynamic:{type:"boolean",const:!0},maxEntities:{anyOf:[{type:"number"},{type:"null"}]}},required:["fieldProxyId","entityType","optional","jsonPath","description","dynamic"],additionalProperties:!1}]}}},required:["input","output"],additionalProperties:!1},qualityCriteria:{type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},qualityElement:{type:"string"},thresholds:{type:"object",properties:{pass:{type:"string"},fail:{type:"string"}},required:["pass","fail"]},targetEntity:{type:"string"},llmQaInstruction:{type:"string",maxLength:5000}},required:["id","qualityElement","thresholds","targetEntity"]}},offboardingRules:{default:[],type:"array",items:{type:"object",properties:{id:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"},type:{type:"string",enum:["mv_agreement"]},agreementScale:{type:"string"}},required:["id"],additionalProperties:!1}},instruction:{type:"string"},ui:{type:"object",properties:{code:{type:"string"},data:{type:"string"},preprocess:{type:"string"},postprocess:{default:"return {};",type:"string"},constants:{type:"string"}},required:["code","data","preprocess","constants"]},qualityAssurance:{default:{qaMode:"llm_only",llmQaModelId:"gpt-5.4"},oneOf:[{type:"object",properties:{qaMode:{type:"string",const:"llm_only"},llmQaModelId:{default:"gpt-5.4",type:"string",enum:["gpt-5.4","gpt-5.4-mini","gpt-5","gpt-5-mini","claude-sonnet-4-6"]}},required:["qaMode"]},{type:"object",properties:{qaMode:{type:"string",const:"none"}},required:["qaMode"]}]},overlap:{type:"integer",minimum:1,maximum:100},onboarding:{type:"object",properties:{enabled:{type:"boolean"},steps:{type:"array",items:{type:"object",properties:{id:{type:"string"},blocks:{type:"array",items:{oneOf:[{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"info"},estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["id","type","estimatedTime","role","goal","successCriteria"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"text"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"quiz"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},questions:{type:"array",items:{type:"object",properties:{id:{type:"string"},type:{type:"string",enum:["single-choice","multiple-choice"]},title:{type:"string"},question:{type:"string"},hint:{type:"string"},correctAnswerFeedback:{type:"string"},incorrectAnswerFeedback:{type:"string"},options:{type:"array",items:{type:"object",properties:{value:{type:"string"},label:{type:"string"}},required:["value","label"]}},correctAnswer:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},required:["id","type","question","options","correctAnswer"]}}},required:["id","type","questions"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"practice"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},imageUrl:{type:"string"},editorType:{type:"string"},editorConfig:{type:"object",properties:{rows:{type:"number"},language:{type:"string"},placeholder:{type:"string"}}},validators:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},criteria:{type:"string"}},required:["id","name","description","criteria"]}}},required:["id","type"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"examples"},title:{type:"string"},examples:{maxItems:10,type:"array",items:{type:"object",properties:{id:{type:"string"},input:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}},checks:{maxItems:10,type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",const:"exact"},path:{type:"string"},golden:{$ref:"#/$defs/__schema4"},hint:{type:"string"}},required:["type","path","golden","hint"]},{type:"object",properties:{type:{type:"string",const:"code"},code:{type:"string"},hint:{type:"string"}},required:["type","code","hint"]},{type:"object",properties:{type:{type:"string",const:"llm"},paths:{type:"array",items:{type:"string"}},criteria:{type:"string"},reference:{type:"string"},hint:{type:"string"},imageUrl:{type:"string"}},required:["type","paths","criteria"]}]}},explanation:{type:"string"},sourceItemId:{type:"string"}},required:["id","input","checks"]}}},required:["id","type","examples"]},{type:"object",properties:{id:{type:"string"},type:{type:"string",const:"consent"},title:{type:"string"},content:{type:"array",items:{type:"object",properties:{type:{type:"string",const:"markdown"},value:{type:"string"}},required:["type","value"]}},consentLabel:{type:"string"}},required:["id","type","consentLabel"]}]}}},required:["id"]}},info:{type:"object",properties:{estimatedTime:{type:"string"},role:{type:"string"},goal:{type:"string"},successCriteria:{type:"string"}},required:["estimatedTime","role","goal","successCriteria"]}},required:["enabled","steps","info"]},exam:{default:{enabled:!1,gradedEntities:[],tasksPerExpert:1,passThreshold:1},type:"object",properties:{enabled:{type:"boolean"},gradedEntities:{type:"array",items:{type:"object",properties:{targetEntity:{type:"string"},mode:{type:"string",enum:["ground_truth","quality_criteria","not_graded"]},groundTruthType:{type:"string",enum:["direct","custom"]},customInstruction:{type:"string"},disabledCriterionIds:{type:"array",items:{type:"string",format:"uuid",pattern:"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"}}},required:["targetEntity","mode","groundTruthType","customInstruction","disabledCriterionIds"],additionalProperties:!1}},goldenDatasetId:{type:"string",pattern:"^ds\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},tasksPerExpert:{type:"integer",minimum:1,maximum:9007199254740991},passThreshold:{type:"integer",minimum:0,maximum:9007199254740991}},required:["enabled","gradedEntities","tasksPerExpert","passThreshold"],additionalProperties:!1},reuseAudienceWithNodeId:{default:null,anyOf:[{type:"object",properties:{pipelineId:{type:"string",pattern:"^pl\\.[0-9a-f]{8}-[0-9a-f]{4}-[7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"},nodeId:{type:"string"}},required:["pipelineId","nodeId"],additionalProperties:!1},{type:"null"}]},smartSearch:{default:null,anyOf:[{type:"object",properties:{briefDescription:{type:"string"},projectDescription:{anyOf:[{type:"string"},{type:"null"}]},extraHardRequirements:{type:"array",items:{type:"string"}},relevanceCriteria:{type:"array",items:{type:"string"}},typicalJobTitles:{type:"array",items:{type:"string"}},idealCandidateProfile:{type:"string"},whoIsNotAFit:{type:"array",items:{type:"string"}},sourceFingerprint:{type:"string"}},required:["briefDescription","projectDescription","extraHardRequirements","relevanceCriteria","typicalJobTitles","idealCandidateProfile","whoIsNotAFit"],additionalProperties:!1},{type:"null"}]},checks:{type:"object",propertyNames:{type:"string",enum:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]},additionalProperties:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},input:{type:"string"}},required:["id","name","input"]}},required:["ui","llmqa","qc_lint","ui_types_lint","exam_dataset"]}},required:["about","publicName","entities","qualityCriteria","instruction","ui","overlap","onboarding"],additionalProperties:!1}},required:["id","type","settings"],additionalProperties:!1}]}},connections:{maxItems:2000,type:"array",items:{type:"object",properties:{from:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},to:{type:"object",properties:{node:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},handle:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"}},required:["node","handle"],additionalProperties:!1},settings:{type:"object",properties:{},additionalProperties:{}}},required:["from","to","settings"],additionalProperties:!1}},layout:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"object",propertyNames:{type:"string",pattern:"^(?!(?:__proto__|constructor|prototype)$).+$"},additionalProperties:{type:"array",prefixItems:[{type:"number",description:"X"},{type:"number",description:"Y"}]},maxProperties:2},maxProperties:500}},required:["version","fields","nodes","connections"],additionalProperties:!1,$defs:{__schema0:{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema1"}},__schema1:{type:"object",properties:{type:{anyOf:[{type:"string",enum:["string","number","integer","boolean","object","array","null"]},{minItems:1,type:"array",items:{type:"string",enum:["string","number","integer","boolean","object","array","null"]}}]},properties:{$ref:"#/$defs/__schema0"},required:{type:"array",items:{type:"string"}},additionalProperties:{anyOf:[{type:"boolean"},{$ref:"#/$defs/__schema1"}]},items:{$ref:"#/$defs/__schema1"},minItems:{type:"integer",minimum:0,maximum:9007199254740991},maxItems:{type:"integer",minimum:0,maximum:9007199254740991},uniqueItems:{type:"boolean"},enum:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema2"}},const:{$ref:"#/$defs/__schema2"},minimum:{type:"number"},maximum:{type:"number"},exclusiveMinimum:{type:"number"},exclusiveMaximum:{type:"number"},minLength:{type:"integer",minimum:0,maximum:9007199254740991},maxLength:{type:"integer",minimum:0,maximum:9007199254740991},pattern:{type:"string"},format:{type:"string"},title:{type:"string"},description:{type:"string"},default:{$ref:"#/$defs/__schema2"},examples:{type:"array",items:{$ref:"#/$defs/__schema2"}},anyOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},oneOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}},allOf:{minItems:1,type:"array",items:{$ref:"#/$defs/__schema1"}}},additionalProperties:!1},__schema2:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema2"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema2"}}]},__schema3:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema3"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema3"}}]},__schema4:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"},{type:"array",items:{$ref:"#/$defs/__schema4"}},{type:"object",propertyNames:{type:"string"},additionalProperties:{$ref:"#/$defs/__schema4"}}]}}};var hg=new fg.default({strict:!1});mg.default(hg);var pg=hg.compile(ug),MF=(e)=>{let t=e.keyword==="required"?e.params.missingProperty:e.keyword==="additionalProperties"?e.params.additionalProperty:void 0;return{path:typeof t==="string"?`${e.instancePath}/${t.replaceAll("~","~0").replaceAll("/","~1")}`:e.instancePath||"/",reason:e.message??`failed ${e.keyword} validation`}};function Wl(e){if(pg(e))return;let t=pg.errors;_(t,"Pipeline graph validation failed without errors");let r=new Set,i=[];for(let n of t){let s=MF(n),o=`${s.path}
|
|
127
|
-
${s.reason}`;if(r.has(o))continue;r.add(o),
|
|
128
|
-
`)},
|
|
129
|
-
`)}}async function
|
|
130
|
-
`)}}var
|
|
131
|
-
`)},
|
|
132
|
-
Run toloka dataset fields ${JSON.stringify(p)} to inspect the inferred schema stored from the first successful upload.`:"";_(
|
|
133
|
-
${
|
|
134
|
-
`)}}var
|
|
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(`
|
|
135
141
|
`)}
|
|
136
|
-
`),{output:`Wrote ${a.length} rows to ${t.outPath}.`}}async function Ug(e,t){return await e.secrets.set({projectId:t.projectId,name:t.name,value:t.value}),{name:t.name,output:`Set secret ${t.name}.`}}var yO=["emacs","vim"],_O=new Set(yO);function PO(e){return _O.has(e)}function Bg(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(PO)))}var Ui=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",xs=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var rc=(e)=>e.name==="backspace";var ic=(e)=>"1234567890".includes(e.name),nc=(e)=>e.name==="enter"||e.name==="return";class sc extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class oc extends Error{name="CancelPromptError";message="Prompt was canceled"}class Rs extends Error{name="ExitPromptError"}class ac extends Error{name="HookError"}class Bi extends Error{name="ValidationError"}var zg=require("async_hooks");var Cs=require("async_hooks");var Gg=new Cs.AsyncLocalStorage;function bO(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function Vg(e,t){let r=bO(e);return Gg.run(r,()=>{function i(n){r.handleChange=()=>{r.index=0,n()},r.handleChange()}return t(i)})}function Ht(){let e=Gg.getStore();if(!e)throw new ac("[Inquirer] Hook functions can only be called from within a prompt");return e}function lc(){return Ht().rl}function cc(e){let t=(...r)=>{let i=Ht(),n=!1,s=i.handleChange;i.handleChange=()=>{n=!0};let o=e(...r);if(n)s();return i.handleChange=s,o};return Cs.AsyncResource.bind(t)}function Ar(e){let t=Ht(),{index:r}=t,i={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},n=e(i);return t.index++,n}function Kg(){Ht().handleChange()}var Jt={queue(e){let t=Ht(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(lc());if(i!=null&&typeof i!=="function")throw new Bi("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=Ht();cc(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Ht();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function vO(e){return typeof e==="function"}function et(e){return Ar((t)=>{let r=zg.AsyncResource.bind(function(s){if(t.get()!==s)t.set(s),Kg()});if(t.initialized)return[t.get(),r];let i=vO(e)?e():e;return t.set(i),[i,r]})}function Qt(e,t){Ar((r)=>{let i=r.get();if(!Array.isArray(i)||t.some((s,o)=>!Object.is(s,i[o])))Jt.queue(e);r.set(t)})}var ke=require("util");var Ae=xe(require("process"));function wO(){if(!Ae.default.platform.startsWith("win"))return Ae.default.env.TERM!=="linux";return Boolean(Ae.default.env.CI)||Boolean(Ae.default.env.WT_SESSION)||Boolean(Ae.default.env.TERMINUS_SUBLIME)||Ae.default.env.ConEmuTask==="{cmd::Cmder}"||Ae.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ae.default.env.TERM_PROGRAM==="vscode"||Ae.default.env.TERM==="xterm-256color"||Ae.default.env.TERM==="alacritty"||Ae.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Wg={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Hg={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},$O={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},EO={...Wg,...Hg},IO={...Wg,...$O},SO=wO(),xO=SO?EO:IO,kr=xO,CM=Object.entries(Hg);var RO={prefix:{idle:ke.styleText("blue","?"),done:ke.styleText("green",kr.tick)},spinner:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map((e)=>ke.styleText("yellow",e))},keybindings:[],style:{answer:(e)=>ke.styleText("cyan",e),message:(e)=>ke.styleText("bold",e),error:(e)=>ke.styleText("red",`> ${e}`),defaultAnswer:(e)=>ke.styleText("dim",`(${e})`),help:(e)=>ke.styleText("dim",e),highlight:(e)=>ke.styleText("cyan",e),key:(e)=>ke.styleText("cyan",ke.styleText("bold",`<${e}>`))}};function Jg(){return{...RO,keybindings:Bg()}}function Qg(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Yg(...e){let t={};for(let r of e)for(let[i,n]of Object.entries(r)){let s=t[i];t[i]=Qg(s)&&Qg(n)?Yg(s,n):n}return t}function Gi(...e){let t=[Jg(),...e.filter((r)=>r!=null)];return Yg(...t)}function dc({status:e="idle",theme:t}){let[r,i]=et(!1),[n,s]=et(0),{prefix:o,spinner:a}=Gi(t);if(Qt(()=>{if(e==="loading"){let u,l=-1,d=setTimeout(()=>{i(!0),u=setInterval(()=>{l=l+1,s(l%a.frames.length)},a.interval)},300);return()=>{clearTimeout(d),clearInterval(u)}}else i(!1)},[e]),r)return a.frames[n];return typeof o==="string"?o:o[e==="loading"?"idle":e]??o.idle}function Vi(e,t){return Ar((r)=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((n,s)=>n!==t[s])){let n=e();return r.set({value:n,dependencies:t}),n}return i.value})}function Yt(e){return et({current:e})[0]}function uc(e){let t=Yt(e);t.current=e,Qt((r)=>{let i=!1,n=cc((s,o)=>{if(i)return;t.current(o,r)});return r.input.on("keypress",n),()=>{i=!0,r.input.removeListener("keypress",n)}},[])}var hy=xe(Zg(),1);var ey=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),ty=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ry=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var FO=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,OO=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,iy=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,TO=/\t{1,1000}/y,ny=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,AO=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,kO=/\p{M}+/gu,DO={limit:1/0,ellipsis:""},sy=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",s=t?.ellipsisWidth??(n?sy(n,DO,r).width:0),o=0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.emojiWidth??2,l=2,d=r.regularWidth??1,p=r.wideWidth??2,f=[[AO,d],[FO,0],[OO,a],[TO,c],[ny,u],[iy,p]],m=0,h=0,g=e.length,y=0,P=!1,v=g,w=Math.max(0,i-s),I=0,E=0,x=0,T=0;e:while(!0){if(E>I||h>=g&&h>m){let R=e.slice(I,E)||e.slice(m,h);y=0;for(let V of R.replaceAll(kO,"")){let J=V.codePointAt(0)||0;if(ty(J))T=2;else if(ry(J))T=p;else T=d;if(x+T>w)v=Math.min(v,Math.max(I,m)+y);if(x+T>i){P=!0;break e}y+=V.length,x+=T}I=E=0}if(h>=g)break e;for(let R=0,V=f.length;R<V;R++){let[J,X]=f[R];if(J.lastIndex=h,J.test(e)){if(y=J===iy?ey(e.slice(h,J.lastIndex)):J===ny?1:J.lastIndex-h,T=y*X,x+T>w)v=Math.min(v,h+Math.floor((w-x)/X));if(x+T>i){P=!0;break e}x+=T,I=m,E=h,h=m=J.lastIndex;continue e}}h+=1}return{width:P?w:x,index:P?v:g,truncated:P,ellipsed:P&&i>=s}},oy=sy;var NO={limit:1/0,ellipsis:"",ellipsisWidth:0},LO=(e,t={})=>oy(e,NO,t).width,pt=LO;var js="\x1B",uy="\x9B",qO=39,fc="\x07",py="[",MO="]",fy="m",mc=`${MO}8;;`,ay=new RegExp(`(?:\\${py}(?<code>\\d+)m|\\${mc}(?<uri>.*)${fc})`,"y"),ly=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0;return},cy=(e)=>`${js}${py}${e}${fy}`,dy=(e)=>`${js}${mc}${e}${fc}`,pc=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,s=!1,o=e.at(-1),a=o===void 0?0:pt(o),c=i.next(),u=i.next(),l=0;while(!c.done){let d=c.value,p=pt(d);if(a+p<=r)e[e.length-1]+=d;else e.push(d),a=0;if(d===js||d===uy)n=!0,s=t.startsWith(mc,l+1);if(n){if(s){if(d===fc)n=!1,s=!1}else if(d===fy)n=!1}else if(a+=p,a===r&&!u.done)e.push(""),a=0;c=u,u=i.next(),l+=d.length}if(o=e.at(-1),!a&&o!==void 0&&o.length&&e.length>1)e[e.length-2]+=e.pop()},UO=(e)=>{let t=e.split(" "),r=t.length;while(r){if(pt(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},BO=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let i="",n,s,o=e.split(" "),a=[""],c=0;for(let d=0;d<o.length;d++){let p=o[d];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=pt(h)}if(d!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let f=pt(p);if(r.hard&&f>t){let m=t-c,h=1+Math.floor((f-m-1)/t);if(Math.floor((f-1)/t)<h)a.push("");pc(a,p,t),c=pt(a.at(-1)??"");continue}if(c+f>t&&c&&f){if(r.wordWrap===!1&&c<t){pc(a,p,t),c=pt(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>t&&r.wordWrap===!1){pc(a,p,t),c=pt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}if(r.trim!==!1)a=a.map((d)=>UO(d));let u=a.join(`
|
|
137
|
-
`),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(i+=p,!l){if(l=p>="\uD800"&&p<="\uDBFF",l)continue}else l=!1;if(p===js||p===uy){ay.lastIndex=d+1;let m=ay.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);n=h===qO?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(u[d+1]===`
|
|
138
|
-
`){if(
|
|
139
|
-
`){if(n
|
|
140
|
-
`)}function
|
|
141
|
-
`)
|
|
142
|
-
`).
|
|
143
|
-
`)
|
|
144
|
-
`)})
|
|
145
|
-
`)}
|
|
146
|
-
`).length,
|
|
147
|
-
`).
|
|
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+=`
|
|
148
155
|
`;let o=e+(t?`
|
|
149
|
-
`+t:""),
|
|
150
|
-
`,t+=
|
|
151
|
-
at ${R}`)}let[x,T]=typeof
|
|
152
|
-
`).trimEnd()}${
|
|
153
|
-
`)}}var
|
|
154
|
-
`)};try{let
|
|
155
|
-
`):`Run ${
|
|
156
|
-
`)};throw
|
|
157
|
-
`)}}async function
|
|
158
|
-
`)}}async function
|
|
159
|
-
${
|
|
160
|
-
${e.state.error}`};async function
|
|
161
|
-
`)}}var
|
|
162
|
-
`)};async function
|
|
163
|
-
`),
|
|
164
|
-
${cT}`).configureOutput({writeOut:(l)=>e.io.stdout(l.replace(/\n$/u,"")),writeErr:(l)=>e.io.stderr(l.replace(/\n$/u,""))}).exitOverride();let n=()=>t.opts();t.hook("postAction",async(l)=>{if(i)return;let d=[];for(let m=l;m!==null;m=m.parent)d.push(m.name());if(d.includes("init")||d.includes("help"))return;let p=await Wi(n(),e.io),f=await Th(p).catch(()=>{return});if(f===void 0)return;i=!0,e.io.stderr(f)}),t.command("login").description("store an API key for this machine after verifying it").action(async()=>{let l=await Bf({...n().apiKey===void 0?{}:{apiKey:n().apiKey},...n().baseUrl===void 0?{}:{baseUrl:n().baseUrl},...e.io.prompt===void 0?{}:{prompt:e.io.prompt},write:e.io.stdout,environment:e.environment});e.io.stdout(l.output);try{let d=await jf(e.environment);if(d===void 0)return;let p=e.injectedClient??it(d);await Hi(p,e.analytics)}catch{}}),t.command("logout").description("remove stored credentials from this machine").action(async()=>{let l=await Gf(e.environment);e.io.stdout(l.output)}),t.command("auth-status").alias("whoami").description("show which platform and key the CLI would use").option("--show-token","print the API key instead of masking it",!1).action(async(l)=>{let d=n(),p=await yi(e.environment,d.apiKey??e.environment.POTATO_API_KEY),f=p.found?.credentials,m=await Wi(d,e.io),h=await $e(m),g=jc(d,e,f,h),y=e.injectedClient,P=await Kf({environment:e.environment,showToken:l.showToken,credentialLookup:p,...d.apiKey===void 0?{}:{flagApiKey:d.apiKey},...d.baseUrl===void 0?{}:{flagBaseUrl:d.baseUrl},...y===void 0?{}:{probe:()=>y},...g===void 0?{}:{project:g}});if(e.io.stdout(P.output),!P.authenticated){r.value=1;return}try{let v=rl(d,h,e.environment,f),w=e.injectedClient??it({apiKey:v.apiKey,baseUrl:v.baseUrl});await Hi(w,e.analytics)}catch{}});let s=t.command("project").description("select and manage the current platform project");s.command("list").description("list remote projects this key can see").action(async()=>{let l=n(),{client:d,stored:p,state:f}=await te(l,e),m=jc(l,e,p,f);await kf({client:d,io:e.io,...m===void 0?{}:{context:m}})}),s.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??it(f.credentials);await Df({environment:e.environment,flags:p,client:m,io:e.io,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d===void 0?{}:{projectId:d}})}),s.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(l)=>{await Nf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("current").description("show the project this command would use").action(async()=>{let l=n(),d=await Fc(l,e),p=await Wi(l,e.io),f=await $e(p);if(qf({flags:l,environment:e.environment,stored:d,...f===void 0?{}:{state:f},io:e.io}).project===void 0)r.value=1}),s.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(l)=>{await Lf({environment:e.environment,flags:n(),alias:l,io:e.io})}),s.command("create").argument("[alias]","local name for the new project").option("--name <name>","platform project name").option("--team-id <id>","team that owns the project").description("create a live project and select it").action(async(l,d)=>{let p=n(),f=await It(e.environment),m=e.injectedClient??it(f.credentials),h=await Wi(p,e.io);await Mf({environment:e.environment,flags:p,client:m,io:e.io,sourceRoot:h,afterPreflight:async()=>Hi(m,e.analytics),...l===void 0?{}:{alias:l},...d.name===void 0?{}:{name:d.name},...d.teamId===void 0?{}:{teamId:d.teamId}})}),t.command("init").description("initialize this project directory and install agent skills").action(async()=>{let l=n(),d=dT(l),p=await Fc(l,e),f=await $e(d),m=jc(l,e,p,f),h=await Oh(d,m===void 0?{}:{projectId:m.id});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)}),t.command("import").argument("[projectId]","existing project to write into source; defaults to the selected project").option("-f, --force","replace an existing pipelines/ directory",!1).description("generate TypeScript source from a live project").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=l??m;_(h,he);let g=await Rg(f,{sourceRoot:p,projectId:h,...d?.force===!0?{force:!0}:{}});e.io.stdout(g.output)}),t.command("plan").description("show what apply would change").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Cg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("validate").description("run platform spec validation and report matching checks").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Og(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});if(e.io.stdout(f.output),!f.valid)r.value=1}),t.command("apply").description("make the platform match source").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e),f=await Fg(d,{sourceRoot:l,...p===void 0?{}:{projectId:p}});e.io.stdout(f.output)}),t.command("secret").description("manage project secrets").command("set").argument("<name>","secret name referenced by a code node").option("--from-env <variable>","read the value from this environment variable instead of stdin").description("set a secret value without writing it to disk").action(async(l,d)=>{let{client:p,projectId:f}=await te(n(),e);_(f,he);let m=d.fromEnv===void 0?(await e.io.readStdin()).replace(/\r?\n$/u,""):e.environment[d.fromEnv];_(m!==void 0,`Missing secret value. Set ${d.fromEnv??"the named environment variable"} or pipe it to stdin.`);try{let h=await Ug(p,{projectId:f,name:l,value:m});e.io.stdout(h.output)}catch{e.io.stderr(`Failed to set secret ${l}.`),r.value=1}});let a=t.command("dataset").description("inspect and move dataset catalog and rows");a.command("list").description("list live datasets in the selected project").action(async()=>{let{client:l,projectId:d}=await te(n(),e);_(d,he);let p=await qg(l,{projectId:d});e.io.stdout(p.output)}),a.command("fields").argument("<name>","dataset name or id").description("print field declarations inferred from uploaded rows").action(async(l)=>{let{sourceRoot:d,client:p,projectId:f}=await te(n(),e),m=await Lg(p,{sourceRoot:d,datasetName:l,...f===void 0?{}:{projectId:f}});e.io.stdout(m.output)}),a.command("load").argument("<name>","dataset name or id").requiredOption("--out <file>","JSONL file to write").option("--limit <n>","how many rows to keep after download",Lr).option("--timeout <ms>","how long to wait for the export",Lr).description("download live dataset rows into a JSONL file").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Mg(f,{sourceRoot:p,datasetName:l,outPath:Ji.resolve(d.out),...m===void 0?{}:{projectId:m},...d.limit===void 0?{}:{limit:d.limit},...d.timeout===void 0?{}:{timeoutMs:d.timeout}});e.io.stdout(h.output)}),a.command("upload").argument("<name>","dataset name or id").argument("<file>","JSONL file, one JSON object per line").description("append rows to a dataset").action(async(l,d)=>{let{sourceRoot:p,client:f,projectId:m}=await te(n(),e),h=await Ng(f,{sourceRoot:p,datasetName:l,filePath:Ji.resolve(d),...m===void 0?{}:{projectId:m}});if(e.io.stdout(h.output),h.warning!==void 0)e.io.stderr(h.warning)});let c="pipeline name or id; required unless a TTY picker can choose among several",u=t.command("pipeline").description("operate on a live pipeline in the selected project");return u.command("list").description("list live pipelines in the selected project").action(async()=>{let{client:l,projectId:d,state:p}=await te(n(),e);_(d,he);let f=await Dy({client:l,projectId:d,state:p});e.io.stdout(f.output)}),u.command("run").argument("[name]",c).option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long to wait",Lr).description("start a run on a deployed pipeline").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await My(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},wait:d.wait,...d.timeout===void 0?{}:{timeoutMs:d.timeout},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output),r.value=Cc(h.outcome)}),u.command("status").argument("[name]",c).description("report the latest run's state and item counts").action(async(l)=>{let{client:d,state:p,projectId:f}=await te(n(),e);_(f,he);let m=await By(d,{projectId:f,state:p,...l===void 0?{}:{pipeline:l},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(m.output),r.value=Cc(m.outcome)}),u.command("runs").argument("[name]",c).option("--limit <n>","how many runs to list",Lr).description("list recent runs").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await Uy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.limit===void 0?{}:{limit:d.limit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cost").argument("[name]",c).option("--item-limit <n>","cap how many items to price",Lr).description("forecast what a run of this pipeline would bill").action(async(l,d)=>{let{client:p,state:f,projectId:m}=await te(n(),e);_(m,he);let h=await Wy(p,{projectId:m,state:f,...l===void 0?{}:{pipeline:l},...d.itemLimit===void 0?{}:{itemLimit:d.itemLimit},...e.io.select===void 0?{}:{select:e.io.select}});e.io.stdout(h.output)}),u.command("cancel").argument("<runId>","run to cancel").description("request cancellation of a run").action(async(l)=>{let{client:d}=await te(n(),e),p=await Gy(d,{runId:l});e.io.stdout(p.output)}),u.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",Lr).option("--failed","only report failed items",!1).description("report a run's items").action(async(l,d)=>{let{client:p}=await te(n(),e),f=await Vy(p,{runId:l,failedOnly:d.failed,...d.limit===void 0?{}:{limit:d.limit}});e.io.stdout(f.output),r.value=Cc(f.outcome)}),t.command("status").description("report project health: live counts and pending source changes").action(async()=>{let{sourceRoot:l,client:d,projectId:p}=await te(n(),e);_(p,he);let f=await jg(d,{sourceRoot:l,projectId:p});e.io.stdout(f.output)}),{program:t,exitCode:r}}var pT=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},fT=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:r,resolve:i,reject:n}=Promise.withResolvers(),s="",o=()=>{process.stdin.off("data",l),process.stdin.off("end",c),process.stdin.off("error",u),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{o(),process.stdout.write(`
|
|
165
|
-
`)},
|
|
166
|
-
`){a(),
|
|
167
|
-
${t}`}return e instanceof Error?e.message:String(e)},yT=async(e,t,r,i)=>{try{await e.parseAsync([...r],{from:"user"});let n=t.value;return{code:n,outcome:n===0?"succeeded":"failed"}}catch(n){if(n instanceof rt){let s=n.exitCode===0?0:1;return{code:s,outcome:s===0?"succeeded":"usage_error",error:n}}return i.stderr(gT(n)),{code:1,outcome:"failed",error:n}}};async function Jy(e,t=process.env,r=hT(),i,n=Dh({environment:t})){let{program:s,exitCode:o}=uT({environment:t,io:r,analytics:n,...i===void 0?{}:{injectedClient:i}}),a=Date.now(),c=await yT(s,o,e,r);try{n.captureCommand({command:kh(e),durationMs:Date.now()-a,exitCode:c.code,outcome:c.outcome,...c.error===void 0?{}:{error:c.error}}),await n.shutdown()}catch{}return c.code}Jy(process.argv.slice(2)).then((e)=>{process.exitCode=e},(e)=>{console.error(e),process.exitCode=1});})
|
|
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});})
|