@toloka-platform/sdk 0.17.0 → 0.17.2
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/dist/cli/toloka.js +3 -3
- 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/package.json +2 -2
- package/skills/catalog.json +6 -6
- package/skills/toloka-build/references/human-work.md +4 -4
- package/skills/toloka-build/references/workflow-and-cli.md +1 -1
- package/src/cli/cost.ts +3 -9
package/dist/cli/toloka.js
CHANGED
|
@@ -36,7 +36,7 @@ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,(r)=>{l
|
|
|
36
36
|
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let l=Du.test(a)?a.replace(Du,"$1"):a;if(!l.match(/\S*Error: /)){for(let g of t){let d=g(l,e);if(d){r.push(d);break}}if(r.length>=_u)break}}return Qu(r)}}class Lu{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=vt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?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 Ci(e,"DOMException")}isDOMError(e){return Ci(e,"DOMError")}}class Lo{match(e){return Cu(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 i=e.message;if(i.error&&typeof i.error.message=="string")return String(i.error.message);return String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Mu{constructor(){}match(e){return pu(e)&&e.error!=null}coerce(e,t){let i=t.apply(e.error);if(!i)return{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0};return i}}var e0=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Mo{match(e){return typeof e=="string"}coerce(e,t){let[i,n]=this.getInfos(e);return{type:i??"Error",value:n??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,n=e.match(e0);if(n)t=n[1],i=n[2];return[t,i]}}var $u=["fatal","error","warning","log","info","debug"];function $o(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let n=i.length;n>0;n--){let r=i.slice(0,n).join(", ");if(!(r.length>t)){if(n===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class qo{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let i=this.getErrorPropertyFromObject(e);if(i)return t.apply(i);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 nn(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),i=$o(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return vt(e)&&!Iu(e)&&$u.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(xu(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class qu{match(e){return nn(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${$o(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class es{match(e){return Eo(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class em{match(e){return Ci(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!nn(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);if(Eo(i))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0};return t.apply(i)}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 tm{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 pr={MESSAGE:"$message",TIMESTAMP:"$timestamp"},t0=new Set([pr.MESSAGE,pr.TIMESTAMP]),ts={enabled:!0,max_bytes:32768};function Cl(e){if(!e)return{...ts};return{enabled:e.enabled??ts.enabled,max_bytes:n0(e.max_bytes,ts.max_bytes)}}function i0(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((n,r)=>{if(t0.has(r))return t.push(r),n;return n[r]=e[r],n},{}),droppedKeys:t}}class im{constructor(e){this._entries=[],this._totalBytes=0,this._config=Cl(e)}setConfig(e){this._config=Cl(e),this._trimToMaxBytes()}add(e){let t=r0(e);if(!t)return;let i=nm(t.json);if(i>this._config.max_bytes)return;this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,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 n0(e,t){if(!cr(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);if(i<0)return t;return i}function r0(e){let t;try{t=tn(e)}catch{return}try{let i=JSON.parse(t);if(!dr(i))return;let n=i,r=n[pr.MESSAGE],o=n[pr.TIMESTAMP];if(!vt(r)||r.trim().length===0)return;if(!vt(o)&&!cr(o))return;return{step:n,json:t}}catch{return}}function nm(e){if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let n=0;n<t.length;n++)if(t[n]==="%")i+=1,n+=2;else i+=1;return i}class Jt extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class Ai extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var sm=(e,t)=>{for(let i of Object.keys(t))if(i.startsWith("$feature/")||i==="$active_feature_flags")e[i]=t[i]};async function rm(e){if(e instanceof Jt){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function o0(e){return typeof e=="object"&&(e instanceof Jt||am(e))}function am(e){return e instanceof Ai}function s0(e){if(e instanceof Jt)return e.status===502||e.status===504;if(!(e instanceof Ai))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function sn(e){return typeof e=="object"&&e instanceof Jt&&e.status===413}function Ar(e){if(e instanceof Jt)return e.status===408||e.status===429||e.status>=500;return am(e)}function om(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var pl="default";class is{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Qo([new Lo,new qo,new Mo,new es],ml())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new $a,this._events=new cl,this._isInitialized=!1;let i=typeof e=="string"?e.trim():"",n=typeof t.host=="string"?t.host.trim():"",r=!i;if(this._logger=yu("[PostHog]",this.logMsgIfDebug.bind(this)),r)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=i,this.host=Nu(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:Ar},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)||r,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=!La()||(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(Je.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(Je.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(Je.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(i,n)=>this._logger.info(i,n));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};if(sm(i,t),e.event==="$feature_flag_called"&&i.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())i=lr(i);return{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",n,i)})}async identifyStatelessImmediate(e,t,i){let n={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",n,i)}captureStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",r,n)})}async captureStatelessImmediate(e,t,i,n){let r=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",r,n)}aliasStateless(e,t,i,n){this.wrap(()=>{let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",r,n)})}async aliasStatelessImmediate(e,t,i,n){let r=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",r,n)}groupIdentifyStateless(e,t,i,n,r,o){this.wrap(()=>{let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});this.enqueue("capture",s,n)})}async groupIdentifyStatelessImmediate(e,t,i,n,r,o){let s=this.buildPayload({distinct_id:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...o||{}}});await this.sendImmediate("capture",s,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`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,i,{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={},i={},n={},r={},o=!1){await this._initPromise;let s=o?"&config=true":"",a=`${this.host}/flags/?v=2${s}`,l={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:n,...r};if(i.$device_id)l.$device_id=i.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)l.evaluation_contexts=this.evaluationContexts;let g={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,g,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:s0},this.featureFlagsRequestTimeoutMs).then((d)=>d.json()).then((d)=>({success:!0,response:Ka(d)})).catch((d)=>(this._events.emit("error",d),{success:!1,error:this.categorizeRequestError(d)}))}categorizeRequestError(e){if(e instanceof Jt)return{type:"api_error",statusCode:e.status};if(e instanceof Ai){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,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailStateless(e,t,i,n,r,o);if(s===void 0)return{response:void 0,requestId:void 0};let a=ar(s.response);if(a===void 0)a=!1;return{response:a,requestId:s.requestId}}async getFeatureFlagDetailStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(t,i,n,r,o,[e]);if(s===void 0)return;return{response:s.flags[e],requestId:s.requestId,evaluatedAt:s.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},n={},r={},o){await this._initPromise;let s=await this.getFeatureFlagPayloadsStateless(t,i,n,r,o,[e]);if(!s)return;let a=s[e];if(a===void 0)return null;return a}async getFeatureFlagPayloadsStateless(e,t={},i={},n={},r,o){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)).payloads}async getFeatureFlagsStateless(e,t={},i={},n={},r,o){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,n,r,o)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s=await this.getFeatureFlagDetailsStateless(e,t,i,n,r,o);if(!s)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:s.featureFlags,payloads:s.featureFlagPayloads,requestId:s.requestId}}async getFeatureFlagDetailsStateless(e,t={},i={},n={},r,o){await this._initPromise;let s={geoip_disable:r??this.disableGeoip};if(o)s.flag_keys_to_evaluate=o;let a=await this.getFlags(e,t,i,n,s);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((r)=>{if(r.status!==200||!r.json){let o=`Surveys API could not be loaded: ${r.status}`,s=Error(o);this._logger.error(s),this._events.emit("error",Error(o));return}return r.json()}).catch((r)=>{this._logger.error("Surveys API could not be loaded",r),this._events.emit("error",r)}))?.surveys;if(n)this._logger.info("Surveys fetched from API: ",JSON.stringify(n));return n??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(Je.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(Je.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(Je.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return pl}persistedQueueKeyForRoute(e){return Je.Queue}getActiveQueueRoutes(){return[pl]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){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,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);let r=this.persistedQueueKeyForRoute(this.getQueueRouteKey(n)),o=this.getPersistedProperty(r)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:n}),this.setPersistedProperty(r,o),this._events.emit(e,n),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=ye(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,i){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,i);if(n=this.processBeforeEnqueue(n),n===null)return;n=this.normalizeMessage(n);try{await this.sendBatch([n],void 0,this.getQueueRouteKey(n))}catch(r){this._events.emit("error",r)}}normalizeMessage(e){let{type:t,library:i,library_version:n,...r}=e,o=om(r.properties)?r.properties:void 0;if(i!==void 0&&o?.$lib===void 0)o={...o||{},$lib:i};if(n!==void 0&&o?.$lib_version===void 0)o={...o||{},$lib_version:n};if(o)r.properties=o;return r.uuid=Jo(r.uuid,je),r}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:rl(),uuid:Jo(t?.uuid,je)};if(t?.disableGeoip??this.disableGeoip){if(!om(i.properties))i.properties={};i.properties.$geoip_disable=!0}if(i.distinctId)i.distinct_id=i.distinctId,delete i.distinctId;return i}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flush().catch(async(e)=>{await rm(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter((r)=>!!r),n=0;while(!0){let r=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(r.length===0)return;if(n>0)this._logger.debug(`flush() re-checking ${r.length} pending promise(s) before flushing`);await Promise.all(r.map((o)=>o.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,i=this.promiseQueue.maxId,n=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,n])}).then(()=>ol([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),ol([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,i=pl){let n={api_key:this.apiKey,batch:e,sent_at:rl()};if(this.historicalMigration)n.historical_migration=!0;let r=tn(n),o=`${this.host}/batch/`,s=this.disableCompression?null:await ui(r,this.isDebug),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...s!==null&&{"Content-Encoding":"gzip"}},body:s||r};await(await this.fetchWithRetry(o,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=[],i;for(let n of e)try{await this._flushRoute(n,t)}catch(r){if(i===void 0)i=r}if(i!==void 0)throw i;this._events.emit("flush",t)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),n=this.getPersistedProperty(i)||[];if(!n.length)return;let r=n.length,o=0;while(n.length>0&&o<r){let s=n.slice(0,this.maxBatchSize),a=s.map((d)=>d.message===void 0?d.message:this.normalizeMessage(d.message)),l=async()=>{let c=(this.getPersistedProperty(i)||[]).slice(s.length);this.setPersistedProperty(i,c),n=c,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},g={retryCheck:(d)=>{if(sn(d))return!1;return Ar(d)}};try{await this.sendBatch(a,g,e)}catch(d){if(sn(d)&&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(!(d instanceof Ai))await l();throw this._events.emit("error",d),d}await l(),t.push(...a),o+=a.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await ui(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(sn(o))return!1;return Ar(o)}}),{kind:"ok"}}catch(o){if(sn(o))return{kind:"too-large"};if(o instanceof Ai)return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,n=this.disableCompression?null:await ui(t,this.isDebug),r={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...n!==null&&{"Content-Encoding":"gzip"}},body:n||t};try{return await this.fetchWithRetry(i,r,{retryCheck:(o)=>{if(sn(o))return!1;return Ar(o)}}),{kind:"ok"}}catch(o){if(sn(o))return{kind:"too-large"};if(Ar(o))return{kind:"retry-later",error:o};return{kind:"fatal",error:o}}}async fetchWithRetry(e,t,i,n){let r=t.body?t.body:"",o=-1;try{o=r instanceof Blob?r.size:Buffer.byteLength(r,Pu)}catch{if(r instanceof Blob)o=r.size;else o=new TextEncoder().encode(r).length}return await Su(async()=>{let s=new AbortController,a=n??this.requestTimeout,l=ye(()=>s.abort(),a),g=null;try{g=await this.fetch(e,{signal:s.signal,...t})}catch(c){throw new Ai(c)}finally{clearTimeout(l)}if(t.mode!=="no-cors"&&(g.status<200||g.status>=400))throw new Jt(g,o);return g},{...this._retryOptions,...i})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let i=async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((s)=>this.getRouteQueue(s).length>0))break;let o=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===o){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(r){if(!o0(r))throw r;await rm(r)}},n;try{return await Promise.race([new Promise((r,o)=>{n=ye(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,o("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}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 dm=require("fs"),cm=require("readline"),ns=new Ye.ReduceableCache(25),Im=new Ye.ReduceableCache(20),Al=7,c0=1000,I0=1e4;async function um(e){let t={};for(let r=e.length-1;r>=0;r--){let o=e[r],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||p0(s)||A0(o))continue;if(!t[s])t[s]=[];t[s].push(o.lineno)}let i=Object.keys(t);if(i.length==0)return e;let n=[];for(let r of i){if(Im.get(r))continue;let o=t[r];if(!o)continue;o.sort((l,g)=>l-g);let s=f0(o);if(s.every((l)=>b0(r,l)))continue;let a=h0(ns,r,{});n.push(u0(r,s,a))}if(await Promise.all(n).catch(()=>{}),e&&e.length>0)m0(e,ns);return ns.reduce(),e}function u0(e,t,i){return new Promise((n)=>{let r=dm.createReadStream(e),o=cm.createInterface({input:r});function s(){r.destroy(),n()}let a=0,l=0,g=t[l];if(g===void 0)return void s();let d=g[0],c=g[1];function u(){Im.set(e,1),o.close(),o.removeAllListeners(),s()}r.on("error",u),o.on("error",u),o.on("close",s),o.on("line",(m)=>{if(a++,a<d)return;if(i[a]=Z0(m,0),a>=c){if(l===t.length-1){o.close(),o.removeAllListeners();return}l++;let p=t[l];if(p===void 0){o.close(),o.removeAllListeners();return}d=p[0],c=p[1]}})})}function m0(e,t){for(let i of e)if(i.filename&&i.context_line===void 0&&typeof i.lineno=="number"){let n=t.get(i.filename);if(n===void 0)continue;C0(i.lineno,i,n)}}function C0(e,t,i){if(t.lineno===void 0||i===void 0)return;t.pre_context=[];for(let r=mm(e);r<e;r++){let o=i[r];if(o===void 0)return void lm(t);t.pre_context.push(o)}if(i[e]===void 0)return void lm(t);t.context_line=i[e];let n=Cm(e);t.post_context=[];for(let r=e+1;r<=n;r++){let o=i[r];if(o===void 0)break;t.post_context.push(o)}}function lm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function p0(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function A0(e){if(e.lineno!==void 0&&e.lineno>I0)return!0;if(e.colno!==void 0&&e.colno>c0)return!0;return!1}function b0(e,t){let i=ns.get(e);if(i===void 0)return!1;for(let n=t[0];n<=t[1];n++)if(i[n]===void 0)return!1;return!0}function f0(e){if(!e.length)return[];let t=0,i=e[0];if(typeof i!="number")return[];let n=gm(i),r=[];while(!0){if(t===e.length-1){r.push(n);break}let o=e[t+1];if(typeof o!="number")break;if(o<=n[1])n[1]=o+Al;else r.push(n),n=gm(o);t++}return r}function gm(e){return[mm(e),Cm(e)]}function mm(e){return Math.max(1,e-Al)}function Cm(e){return e+Al}function h0(e,t,i){let n=e.get(t);if(n===void 0)return e.set(t,i),i;return n}function Z0(e,t){let i=e,n=i.length;if(n<=150)return i;if(t>n)t=n;let r=Math.max(t-60,0);if(r<5)r=0;let o=Math.min(r+140,n);if(o>n-5)o=n;if(o===n)r=Math.max(o-140,0);if(i=i.slice(r,o),r>0)i=`...${i}`;if(o<n)i+="...";return i}var an=require("path");function pm(e=process.cwd()){let t=an.sep==="\\",i=(r)=>t?r.replace(/\\/g,"/"):r,n=i(e);return async(r)=>{for(let o of r)if(!(!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:"))){if(an.isAbsolute(o.filename))o.filename=i(an.relative(n,i(o.filename)))}return r}}var Am="5.46.1";var kt={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class bi{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 i=this._flags[t];if(i)e[t]=i}return this._cloneWith(e)}only(e){let t={},i=[];for(let n of e){let r=this._flags[n];if(r)t[n]=r;else i.push(n)}if(i.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,n]of Object.entries(this._flags)){let r=n.enabled===!1?!1:n.variant??!0;if(e[`$feature/${i}`]=r,n.enabled)t.push(i)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new bi({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],i=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,n={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$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 r=[];if(this._errorsWhileComputing)r.push(kt.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)r.push(kt.QUOTA_LIMITED);if(t===void 0)r.push(kt.FLAG_MISSING);if(r.length>0)n.$feature_flag_error=r.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:n})}}async function bm(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let i=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(i)).map((r)=>r.toString(16).padStart(2,"0")).join("")}var y0=60000,W0=1152921504606847000,V0=["is_not","is_set"];class ln extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,ln.prototype)}}function ym(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class U extends Error{constructor(e){super(e);ym(this,U)}}class At extends Error{constructor(e){super(e);ym(this,At)}}class bl{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:n,host:r,customHeaders:o,...s}){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=i,this.host=r,this.poller=void 0,this.fetch=s.fetch||fetch,this.onError=s.onError,this.customHeaders=o,this.onLoad=s.onLoad,this.onMinimalFlagCalledEvents=s.onMinimalFlagCalledEvents,this.cacheProvider=s.cacheProvider,this.strictLocalEvaluation=s.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}createEvaluationContext(e,t={},i={},n={},r={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:n,evaluationCache:r}}async getFeatureFlag(e,t,i={},n={},r={}){await this.loadFeatureFlags();let o,s;if(!this.loadedSuccessfullyOnce)return o;if(s=this.featureFlagsByKey[e],s!==void 0){let a=this.createEvaluationContext(t,i,n,r);try{o=(await this.computeFlagAndPayloadLocally(s,a)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${o}`))}catch(l){if(l instanceof At||l instanceof U)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 o}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},n={},r=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,s={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(o.map(async(a)=>{try{let{value:l,payload:g}=await this.computeFlagAndPayloadLocally(a,s);if(i[a.key]=l,g)n[a.key]=g}catch(l){if(l instanceof At||l instanceof U)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}`));r=!0}})),{response:i,payloads:n,fallbackToFlags:r}}async computeFlagAndPayloadLocally(e,t,i={}){let{matchValue:n,skipLoadCheck:r=!1}=i;if(!r)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let o;o=n!==void 0?n:await this.computeFlagValueLocally(e,t);let s=this.getFeatureFlagPayload(e.key,o);return{value:o,payload:s}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:n,personProperties:r,groupProperties:o}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new U("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 U("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"&&(r?.$device_id===void 0||r?.$device_id===null||r?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let g=o[l];return await this.matchFeatureFlagProperties(e,n[l],g,t)}{let l=this.getBucketingValueForFlag(e,i,r);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 U(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,l,r,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let n=i?.$device_id;if(n==null||n==="")return;return n}return t}getFeatureFlagPayload(e,t){let i=null;if(t!==!1&&t!=null){if(typeof t=="boolean")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null;else if(typeof t=="string")i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null;if(i!=null){if(typeof i=="object")return i;if(typeof i=="string")try{return JSON.parse(i)}catch{}return i}}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:n}=i,r=e.key;if(!this.featureFlagsByKey)throw new U("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new U(`Flag dependency property for '${r}' is missing required 'dependency_chain' field`);let o=e.dependency_chain;if(!Array.isArray(o))throw new U(`Flag dependency property for '${r}' has an invalid 'dependency_chain' (expected array, got ${typeof o})`);if(o.length===0)throw new U(`Circular dependency detected for flag '${r}' (empty dependency chain)`);for(let a of o){if(!(a in n)){let g=this.featureFlagsByKey[a];if(g)if(g.active)try{let d=await this.computeFlagValueLocally(g,i);n[a]=d}catch(d){throw new U(`Error evaluating flag dependency '${a}' for flag '${r}': ${d}`)}else n[a]=!1;else throw new U(`Missing flag dependency '${a}' for flag '${r}'`)}if(n[a]==null)throw new U(`Dependency '${a}' could not be evaluated`)}let s=n[r];return this.flagEvaluatesToExpectedValue(e.value,s)}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,i,n){let r=e.filters||{},o=r.groups||[],s=r.aggregation_group_type_index,a=r.early_exit??!1,{groups:l,groupProperties:g}=n,d=!1,c;for(let u of o)try{let m=u.aggregation_group_type_index!==void 0?u.aggregation_group_type_index:s,p=i,b=t;if(m!==s){if(m!=null){let I=this.groupTypeMapping[String(m)];if(!I||!(I in l)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${m} not available`));continue}if(!(I in g)){d=!0;continue}p=g[I],b=l[I]}}let f=await this.isConditionMatch(e,b,u,p,n);if(f==="match"){let I=u.variant,C=r.multivariate?.variants||[];c=I&&C.some((h)=>h.key===I)?I:await this.getMatchingVariant(e,b)||!0;break}if(a&&f==="out_of_rollout_bound")return!1}catch(m){if(m instanceof At)throw m;if(m instanceof U)d=!0;else throw m}if(c!==void 0)return c;if(d)throw new U("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,n,r){let o=i.rollout_percentage,s=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((i.properties||[]).length>0){for(let a of i.properties){let l=a.type,g=!1;if(l==="cohort"){let d=await Vm(a,n,this.cohorts,this.debugMode,(c)=>this.evaluateFlagDependency(c,n,r));g=a.operator==="not_in"?!d:d}else g=l==="flag"?await this.evaluateFlagDependency(a,n,r):Wm(a,n,s);if(!g)return"no_match"}if(o==null)return"match"}if(o!=null&&await fm(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){let i=await fm(e.key,t,"variant"),n=this.variantLookupTable(e).find((r)=>i>=r.valueMin&&i<r.valueMax);if(n)return n.key}variantLookupTable(e){let t=[],i=0,n=0;return((e.filters||{}).multivariate?.variants||[]).forEach((s)=>{n=i+s.rollout_percentage/100,t.push({valueMin:i,valueMax:n,key:s.key}),i=n}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,i)=>(t[i.key]=i,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((i)=>i.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((i)=>i.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(y0,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(i){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${i}`))}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 ln(`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 ln(`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 ln(`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 i=await t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let n={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:i.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(r){this.onError?.(Error(`Failed to store in cache: ${r}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(n.flags);break}default:return}}catch(e){if(e instanceof ln)this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)i["If-None-Match"]=t;return{method:e,headers:i}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&typeof this.timeout=="number"){let n=new AbortController;i=ye(()=>{n.abort()},this.timeout),t.signal=n.signal}try{let n=this.fetch;return n(e,t)}finally{clearTimeout(i)}}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((i,n)=>setTimeout(()=>n(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}async function fm(e,t,i=""){let n=await bm(`${e}.${t}${i}`);return parseInt(n.slice(0,15),16)/W0}function Wm(e,t,i){let{key:n,value:r}=e,o=e.operator||"exact";if(n in t){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new U(`Property ${n} not found in propertyValues`)}let s=t[n];if(s==null&&!V0.includes(o)){if(i)i(`Property ${n} cannot have a value of null/undefined with the ${o} operator`);return!1}function a(g,d){if(Array.isArray(g))return g.map((c)=>String(c).toLowerCase()).includes(String(d).toLowerCase());return String(g).toLowerCase()===String(d).toLowerCase()}function l(g,d,c){if(c==="gt")return g>d;if(c==="gte")return g>=d;if(c==="lt")return g<d;if(c==="lte")return g<=d;throw Error(`Invalid operator: ${c}`)}switch(o){case"exact":return a(r,s);case"is_not":return!a(r,s);case"is_set":return n in t;case"icontains":return String(s).toLowerCase().includes(String(r).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(r).toLowerCase());case"regex":return hm(String(r))&&String(s).match(String(r))!==null;case"not_regex":return hm(String(r))&&String(s).match(String(r))===null;case"gt":case"gte":case"lt":case"lte":{let g=typeof r=="number"?r:parseFloat(String(r)),d;if(d=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(g)&&Number.isFinite(d))return l(d,g,o);return l(String(s),String(r),o)}case"is_date_after":case"is_date_before":{if(typeof r=="boolean")throw new U("Date operations cannot be performed on boolean values");let g=F0(String(r));if(g==null)g=Zm(r);if(g==null)throw new U(`Invalid date: ${r}`);let d=Zm(s);if(["is_date_before"].includes(o))return d<g;return d>g}case"semver_eq":return Le(pe(String(s)),pe(String(r)))===0;case"semver_neq":return Le(pe(String(s)),pe(String(r)))!==0;case"semver_gt":return Le(pe(String(s)),pe(String(r)))>0;case"semver_gte":return Le(pe(String(s)),pe(String(r)))>=0;case"semver_lt":return Le(pe(String(s)),pe(String(r)))<0;case"semver_lte":return Le(pe(String(s)),pe(String(r)))<=0;case"semver_tilde":{let g=pe(String(s)),{lower:d,upper:c}=R0(String(r));return Le(g,d)>=0&&Le(g,c)<0}case"semver_caret":{let g=pe(String(s)),{lower:d,upper:c}=G0(String(r));return Le(g,d)>=0&&Le(g,c)<0}case"semver_wildcard":{let g=pe(String(s)),{lower:d,upper:c}=w0(String(r));return Le(g,d)>=0&&Le(g,c)<0}default:throw new U(`Unknown operator: ${o}`)}}function B0(e,t){if(!(e in t))throw new At(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Vm(e,t,i,n=!1,r){let o=String(e.value);B0(o,i);let s=i[o];return Bm(s,t,i,n,r)}async function Bm(e,t,i,n=!1,r){if(!e)return!0;let{type:o,values:s}=e;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let l of s)try{let g=await Bm(l,t,i,n,r);if(o==="AND"){if(!g)return!1}else if(g)return!0}catch(g){if(g instanceof At)throw g;if(g instanceof U){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new U("Can't match cohort without a given cohort property value");return o==="AND"}for(let l of s)try{let g;if(l.type==="cohort")g=await Vm(l,t,i,n,r);else if(l.type==="flag"){if(!r)throw new U(`Flag dependency '${l.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await r(l)}else g=Wm(l,t);let d=l.negation||!1;if(o==="AND"){if(!g&&!d)return!1;if(g&&d)return!1}else{if(g&&!d)return!0;if(!g&&d)return!0}}catch(g){if(g instanceof At)throw g;if(g instanceof U){if(n)console.debug(`Failed to compute property ${l} locally: ${g}`);a=!0}else throw g}if(a)throw new U("can't match cohort without a given cohort property value");return o==="AND"}function hm(e){try{return new RegExp(e),!0}catch(t){return!1}}function Rm(e,t){if(!/^\d+$/.test(e))throw new U(`Invalid semver: ${t}`);if(e.length>1&&e[0]==="0")throw new U(`Invalid semver: ${t}`);return parseInt(e,10)}function pe(e){let i=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!i||i.startsWith("."))throw new U(`Invalid semver: ${e}`);let n=i.split("."),r=(l)=>{if(l===void 0||l==="")return 0;return Rm(l,e)},o=r(n[0]),s=r(n[1]),a=r(n[2]);return[o,s,a]}function Le(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}function R0(e){let t=pe(e),i=[t[0],t[1],t[2]],n=[t[0],t[1]+1,0];return{lower:i,upper:n}}function G0(e){let t=pe(e),[i,n,r]=t,o=[i,n,r],s;return s=i>0?[i+1,0,0]:n>0?[0,n+1,0]:[0,0,r+1],{lower:o,upper:s}}function w0(e){let i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new U(`Invalid wildcard semver: ${e}`);let n=i.split("."),r=(l)=>{try{return Rm(l,e)}catch{throw new U(`Invalid wildcard semver: ${e}`)}},o=r(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let l=r(n[1]);s=[o,l,0],a=[o,l+1,0]}return{lower:s,upper:a}}function Zm(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 U(`${e} is in an invalid date format`)}throw new U(`The date provided ${e} must be a string, number, or date object`)}function F0(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,i=e.match(t),n=new Date(new Date().toISOString());if(!i)return null;{if(!i.groups)return null;let r=parseInt(i.groups.number);if(r>=1e4)return null;let o=i.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-r);else if(o=="d")n.setUTCDate(n.getUTCDate()-r);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*r);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-r);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-r)}return n}}function H0(e,t){let i=!1;return Object.assign((n)=>{let o=global.process.listeners("uncaughtException").filter((s)=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;if(e(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!i&&o)i=!0,t(n)},{_posthogErrorHandler:!0})}function Gm(e,t){globalThis.process?.on("uncaughtException",H0(e,t))}function wm(e){globalThis.process?.on("unhandledRejection",(t)=>e(t,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var v0=2000;class bt{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new Ma({...bu(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return dr(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,i,n,r){let o={...r},s=e.buildFromUnknown(t,i);return s.$exception_list=await e.modifyFrames(s.$exception_list),{event:"$exception",distinctId:n,properties:{...s,...o},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Gm(this.onException.bind(this),this.onFatalError.bind(this)),wm(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!bt.isPreviouslyCapturedError(e)){let i=await bt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(r))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:r});return this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(v0),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class fl{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function k0(e){return e==="v0"||e==="v1"}function Fm(){let e=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return k0(e)?e:"v0"}var br="analytics",fr="ai";function Hm(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class gn extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:n}){super(gn.buildMessage(e,t,i,n)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=n}static buildMessage(e,t,i,n){let r=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;if(n instanceof Error)r+=` (${n.message})`;return r}}function hl(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 P0(e){return typeof e=="string"?e:void 0}var N0=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:hl},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:hl},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:hl},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:P0}],S0=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function x0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Y0(e){if(typeof e=="string"){let i=new Date(e);return Number.isNaN(i.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 vm(e,t,i){if(i!==void 0&&!(t in e))e[t]=i}function E0(e){let i={...x0(e.properties)?e.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of N0)if(o in i){let l=a(i[o]);if(l!==void 0)n[s]=l;delete i[o]}let r={};for(let{property:o,field:s}of S0)if(o in i){let a=i[o];if(typeof a=="string")r[s]=a;delete i[o]}return delete i.$lib,delete i.$lib_version,vm(i,"$set",e.$set),vm(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:Y0(e.timestamp),...r,options:n,properties:i}}function km(e,{createdAt:t,historicalMigration:i}){let n={created_at:t,batch:e.map(E0)};if(i)n.historical_migration=!0;return n}var T0="/i/v1/analytics/events",X0=30000,O0=new Set([408,500,502,503,504]);class Zl{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??X0,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((i)=>new Promise((n)=>ye(n,i))),this.generateRequestId=t.generateRequestId??je,this.compress=t.compress??ui}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:n}=km(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),r=`${this.config.host}${T0}`,o=[],s=n,a=Math.max(1,this.config.maxAttempts);for(let l=1;l<=a;l++){let g=l===a,d=tn({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:s}),c;try{c=await this.sendOnce(r,d,l,t)}catch(f){if(g)return this.surfaceBatchFailure(t,o,s,f);await this.sleep(this.backoffDelay(l));continue}let{status:u}=c;if(u<200||u>=300){if(!g&&O0.has(u)){let I=this.parseRetryAfter(c);await this.cancelBody(c),await this.sleep(this.backoffDelay(l,I));continue}let f=await this.buildHttpError(c,u);return this.surfaceBatchFailure(t,o,s,f)}let m;try{m=await this.parseResponse(c)}catch{return this.surfaceBatchFailure(t,o,s,Error(`Capture V1 returned an unparseable ${u} response body`))}let p=this.classify(s,m,o);if(p.length===0)return this.surfacePartialDrops(t,o);if(g)return void this.onError(new gn({requestId:t,drops:o,retryExhausted:p.map((f)=>f.uuid)}));s=p;let b=this.parseRetryAfter(c);await this.sleep(this.backoffDelay(l,b))}}async sendOnce(e,t,i,n){let r=this.buildHeaders(i,n),o=t;if(this.config.compressionEnabled){let l=await this.compress(t,this.config.isDebug);if(l!==null)o=l,r["Content-Encoding"]="gzip"}let s=new AbortController,a=ye(()=>s.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:r,body:o,signal:s.signal})}finally{clearTimeout(a)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,n={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"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,i){let n=t.results??{},r=[];for(let o of e){let s=n[o.uuid];if(s){if(s.result==="drop")i.push({uuid:o.uuid,details:s.details??void 0});else if(s.result==="retry")r.push(o)}}return r}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return i;return Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let o=parseInt(i,10);return Number.isFinite(o)&&o>0?1000*o:void 0}let n=Date.parse(i);if(Number.isNaN(n))return;let r=n-this.now();return r>0?r:void 0}async parseResponse(e){let t=await e.text(),i=JSON.parse(t);if(typeof i!="object"||i===null||Array.isArray(i))throw Error("unexpected response shape");let n=i.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 i="";try{i=(await e.text()).slice(0,512)}catch{}let n=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${n}`)}surfaceBatchFailure(e,t,i,n){this.onError(new gn({requestId:e,drops:t,retryExhausted:i.map((r)=>r.uuid),cause:n}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new gn({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}var U0=100,Pm=30000,J0=50000,j0=50,z0=500,D0="https://us.i.posthog.com",Nm=new Set;function rs(e,t){if(Nm.has(e))return;Nm.add(e),console.warn(`[PostHog] ${t}`)}function _0(e){return typeof e=="string"?e.trim():""}function Q0(e){return(typeof e=="string"?e.trim():"")||void 0}function K0(e){return(typeof e=="string"?e.trim():"")||D0}function L0(e){return(Array.isArray(e)?e:[e]).filter((i)=>typeof i=="string"&&i.trim().length>0)}function M0(e){if(!e)return{};let t={};for(let[n,r]of Object.entries(e))t[`$feature/${n}`]=r;let i=Object.keys(e).filter((n)=>e[n]!==!1).sort();if(i.length>0)t.$active_feature_flags=i;return t}class yl extends is{constructor(e,t={}){let i=_0(e),n={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:K0(t.host),personalApiKey:Q0(t.secretKey??t.personalApiKey)};if(super(i,n),this._memoryStorage=new fl,this._minimalFlagCalledEvents=!1,this.options=n,this.captureMode=Fm(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof n.featureFlagsPollingInterval=="number"?Math.max(n.featureFlagsPollingInterval,U0):Pm,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 bl({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:n.personalApiKey,projectApiKey:i,timeout:n.requestTimeout??1e4,host:this.host,fetch:n.fetch,onError:(o)=>{this._events.emit("error",o)},onLoad:(o)=>{this._events.emit("localEvaluationFlagsLoaded",o)},onMinimalFlagCalledEvents:(o)=>{this._minimalFlagCalledEvents=o},customHeaders:this.getCustomHeaders(),cacheProvider:n.flagDefinitionCacheProvider,strictLocalEvaluation:n.strictLocalEvaluation})}this.errorTracking=new bt(this,n,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=n.maxCacheSize||J0}enqueue(e,t,i){super.enqueue(e,t,i),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 o,s=new Promise((a)=>{o=a});try{e(s)}catch{return}this._waitUntilCycle={resolve:o,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??z0,n=t>=i;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(n)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??j0;this._waitUntilCycle.timer=ye(()=>{this.resolveWaitUntilFlush()},r)}_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"&&Hm(e)?fr:br}persistedQueueKeyForRoute(e){return e===fr?Je.AiQueue:Je.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[br,fr]:[br]}async sendBatch(e,t,i=br){if(this.captureMode!=="v1"||i===fr)return super.sendBatch(e,t,i);let n=e.filter((r)=>r!==void 0);await this.getV1Sender().sendV1Batch(n)}getV1Sender(){if(!this._v1Sender)this._v1Sender=new Zl({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 Am}get metrics(){if(!this._metrics)this._metrics=new zo(this,jo(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,i){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(i)}_sendPreparedEvent(e,t,i,n){return this.addPendingPromise(this._prepareEventMessage(t,n).then(({distinctId:r,event:o,properties:s,options:a})=>{let l={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},g={distinctId:r,event:o,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,g,l):this.enqueue(e,g,l)}).catch((r)=>{if(r)console.error(r)}))}_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:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,g={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:n,$set_once:r,$anon_distinct_id:o,...s}=t,g={$set:n||s,$set_once:r||{},$anon_distinct_id:o??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:g,disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(Object.keys(t).length===0&&Object.keys(i).length===0)return;let n={};if(Object.keys(t).length>0)n.$set=t;if(Object.keys(i).length>0)n.$set_once=i;this.capture({distinctId:e,event:"$set",properties:n})}unsetPersonProperties({distinctId:e,properties:t}){let i=L0(t);if(i.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}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=Pm){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let i=setTimeout(()=>{n(),t(!1)},e),n=this._events.on("localEvaluationFlagsLoaded",(r)=>{clearTimeout(i),n(),t(r>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,i={},n){if(this.disabled)return void this._logger.warn("The client is disabled");let r=i.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let B=this._flagOverrides[e];if(B===void 0)return;let F=this._payloadOverrides?.[e];return{key:e,enabled:B!==!1,variant:typeof B=="string"?B:void 0,payload:F}}let{groups:o,disableGeoip:s}=i,{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=i,d=this.addLocalPersonAndGroupProperties(t,o,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(t,o,this.personPropertiesForLocalEvaluation(t,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u,m=!1,p,b,f,I,C,h,Z;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let B=this.featureFlagsPoller?.featureFlagsByKey[e];if(B)try{let F=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(B,c,{matchValue:n});if(F){m=!0;let x=F.value;I=B.id,h="Evaluated locally",Z=B.has_experiment,u={key:e,enabled:x!==!1,variant:typeof x=="string"?x:void 0,payload:F.payload??void 0}}}catch(F){if(F instanceof At||F instanceof U)this._logger?.info(`${F.name} when computing flag locally: ${e}: ${F.message}`);else throw F}}if(!m&&!a){let B=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,s,[e]);if(B===void 0)f=kt.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=B.minimalFlagCalledEvents===!0,p=B.requestId,b=B.evaluatedAt;let F=[];if(B.errorsWhileComputingFlags)F.push(kt.ERRORS_WHILE_COMPUTING);if(B.quotaLimited?.includes("feature_flags"))F.push(kt.QUOTA_LIMITED);let x=B.flags[e];if(x===void 0)F.push(kt.FLAG_MISSING);else{I=x.metadata?.id,C=x.metadata?.version,h=x.reason?.description??x.reason?.code,Z=x.metadata?.has_experiment;let v;if(x.metadata?.payload!==void 0)try{v=JSON.parse(x.metadata.payload)}catch{v=x.metadata.payload}u={key:e,enabled:x.enabled,variant:x.variant,payload:v}}if(F.length>0)f=F.join(",")}}if(r){let B=u===void 0?void 0:u.enabled===!1?!1:u.variant??!0,F={$feature_flag:e,$feature_flag_response:B,$feature_flag_id:I,$feature_flag_version:C,$feature_flag_reason:h,locally_evaluated:m,[`$feature/${e}`]:B,$feature_flag_request_id:p,$feature_flag_evaluated_at:m?Date.now():b};if(Z!==void 0)F.$feature_flag_has_experiment=Z;if(m&&this.featureFlagsPoller){let x=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(x!==void 0)F.$feature_flag_definitions_loaded_at=x}if(f)F.$feature_flag_error=f;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:B,groups:o,disableGeoip:s,properties:F})}if(u!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)u={...u,payload:this._payloadOverrides[e]};return u}async getFeatureFlag(e,t,i){rs("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,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(n===void 0)return;if(n.enabled===!1)return!1;return n.variant??!0}async getFeatureFlagPayload(e,t,i,n){if(rs("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 r=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:!1},i);if(r===void 0)return;return r.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:n,options:r}=this._resolveDistinctId(t,i);if(!n)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,n,{...r,sendFeatureFlagEvents:r?.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 i=await t.json();if(typeof i=="string")try{return JSON.parse(i)}catch(n){}return i}async isFeatureEnabled(e,t,i){rs("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,{...i,sendFeatureFlagEvents:i?.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:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(i,n)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)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:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),m={},p={},b=!0;if(u)m=u.response,p=u.payloads,b=u.fallbackToFlags;if(b&&!a){let f=await super.getFeatureFlagsAndPayloadsStateless(c.distinctId,c.groups,l,g,o,s);m={...m,...f.flags||{}},p={...p,...f.payloads||{}}}if(this._flagOverrides!==void 0)m={...m,...this._flagOverrides};if(this._payloadOverrides!==void 0)p={...p,...this._payloadOverrides};return{featureFlags:m,featureFlagPayloads:p}}async evaluateFlags(e,t){let{distinctId:i,options:n}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new bi({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new bi({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,flags:{}});let{groups:r,disableGeoip:o,flagKeys:s}=n||{},{onlyEvaluateLocally:a,personProperties:l,groupProperties:g}=n||{},d=this.addLocalPersonAndGroupProperties(i,r,l,g);l=d.allPersonProperties,g=d.allGroupProperties;let c=this.createFeatureFlagEvaluationContext(i,r,this.personPropertiesForLocalEvaluation(i,l),g);if(a==null)a=this.options.strictLocalEvaluation??!1;let u={},m,p,b=!1,f=!1,I=await this.featureFlagsPoller?.getAllFlagsAndPayloads(c,s),C=new Set;if(I)for(let[Z,W]of Object.entries(I.response)){let B=this.featureFlagsPoller?.featureFlagsByKey[Z];u[Z]={key:Z,enabled:W!==!1,variant:typeof W=="string"?W:void 0,payload:I.payloads[Z],id:B?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:B?.has_experiment},C.add(Z)}if((I?I.fallbackToFlags:!0)&&!a){let Z=await super.getFeatureFlagDetailsStateless(c.distinctId,c.groups,l,g,o,s);if(Z){this._minimalFlagCalledEvents=Z.minimalFlagCalledEvents===!0,m=Z.requestId,p=Z.evaluatedAt,b=Boolean(Z.errorsWhileComputingFlags),f=Array.isArray(Z.quotaLimited)&&Z.quotaLimited.includes("feature_flags");for(let[W,B]of Object.entries(Z.flags)){if(C.has(W))continue;let F;if(B.metadata?.payload!==void 0)try{F=JSON.parse(B.metadata.payload)}catch{F=B.metadata.payload}u[W]={key:W,enabled:B.enabled,variant:B.variant,payload:F,id:B.metadata?.id,version:B.metadata?.version,reason:B.reason?.description??B.reason?.code,locallyEvaluated:!1,hasExperiment:B.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[Z,W]of Object.entries(this._flagOverrides)){if(W===void 0){delete u[Z];continue}let B=u[Z];u[Z]={key:Z,enabled:W!==!1,variant:typeof W=="string"?W:void 0,payload:B?.payload,id:B?.id,version:B?.version,reason:B?.reason,locallyEvaluated:B?.locallyEvaluated??!1,hasExperiment:B?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[Z,W]of Object.entries(this._payloadOverrides)){let B=u[Z];if(B)u[Z]={...B,payload:W}}return new bi({host:this._getFeatureFlagEvaluationsHost(),distinctId:i,groups:r,disableGeoip:o,flags:u,requestId:m,evaluatedAt:p,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:b,quotaLimited:f})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:n,groups:r,disableGeoip:o,properties:s}=e,a=r&&Object.keys(r).length>0?`_${JSON.stringify(Object.entries(r).sort(([g],[d])=>g<d?-1:g>d?1:0))}`:"",l=`${i}_${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:s,groups:r,disableGeoip:o})}_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:i,distinctId:n,disableGeoip:r}){this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:n,disableGeoip:r}){await this._sendPreparedEvent("capture",{distinctId:n||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:r},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(i)=>Object.fromEntries(i.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 i=t.flags;if(i===!1||Array.isArray(i)||typeof i=="object"&&i!==null)return!0}if("payloads"in t){let i=t.payloads;if(i===!1||typeof i=="object"&&i!==null)return!0}return!1}withContext(e,t,i){if(!this.context)return t();return this.context.run(e,t,i)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),i=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await Promise.race([this._metrics.flush().catch(()=>{}),new Promise((n)=>ye(n,Math.max(0,t-Date.now())))]),this._metrics.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}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)}`,i={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 r=new AbortController;n=ye(()=>{r.abort()},this.options.requestTimeout),i.signal=r.signal}try{return await this.fetch(t,i)}catch(r){this._events.emit("error",r);return}finally{if(n)clearTimeout(n)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},n={};for(let[r,o]of Object.entries(e))if(Au(o)&&t&&r in t){let s={};for(let[a,l]of Object.entries(o))s[String(a)]=String(l);n[String(r)]=s}else i[String(r)]=String(o);return{personProperties:i,groupProperties:n}}async getFeatureFlagsForEvent(e,t,i,n){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let r=n?.personProperties||{},o=n?.groupProperties||{},s=n?.flagKeys;if(n?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let l={};for(let[g,d]of Object.entries(t||{}))l[g]=String(d);return await this.getAllFlags(e,{groups:l,personProperties:r,groupProperties:o,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:s})}return(await super.getFeatureFlagsStateless(e,t,r,o,i)).flags}addLocalPersonAndGroupProperties(e,t,i,n){let r={...i||{}},o={};if(t)for(let s of Object.keys(t))o[s]={$group_key:t[s],...n?.[s]||{}};return{allPersonProperties:r,allGroupProperties:o}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,n){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:n||{},evaluationCache:{}}}captureException(e,t,i,n,r){if(!bt.isPreviouslyCapturedError(e)){let o=Error("PostHog syntheticException");this.addPendingPromise(bt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,i).then((s)=>this._capturePreparedEvent({...s,uuid:n,flags:r},!1)))}}async captureExceptionImmediate(e,t,i,n){if(!bt.isPreviouslyCapturedError(e)){let r=Error("PostHog syntheticException");return this.addPendingPromise(bt.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:r},t,i).then((o)=>this.captureImmediate({...o,flags:n})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:n,properties:r,groups:o,flags:s,sendFeatureFlags:a,timestamp:l,disableGeoip:g,uuid:d}=e,c=this.context?.get(),u=t.includeContextProperties??!0,m=i||c?.distinctId,p=u?{...this.props,...c?.properties||{},...r||{}}:{...r||{}};if(!m)m=je(),p.$process_person_profile=!1;if(u&&c?.sessionId&&!p.$session_id)p.$session_id=c.sessionId;let b=this._shouldSendMinimalFlagCalledEvent(n,p)?lr(p):p,f=this._runBeforeSend({distinctId:m,event:n,properties:b,groups:o,flags:s,sendFeatureFlags:a,timestamp:l,disableGeoip:g,uuid:d});if(!f)return Promise.reject(null);let I=await Promise.resolve().then(async()=>{if(s){if(a)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return s._getEventProperties()}if(a){rs("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 C=typeof a=="object"?a:void 0,h=await this.getFeatureFlagsForEvent(f.distinctId,o,g,C);return M0(h)}return{}}).catch(()=>({})).then((C)=>{let h=f.groups||o;return{...C,...f.properties||{},...h!==void 0&&Object.keys(h).length>0?{$groups:h}:{}}});if(f.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof I.$raw_user_agent=="string"){if(du(I.$raw_user_agent,this.options.custom_blocked_useragents||[]))f.event="$bot_pageview",I.$browser_type="bot"}return{distinctId:f.distinctId,event:f.event,properties:I,options:{timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],n=e;for(let r of i){if(n=r(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 o=`Event '${n.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(o)}}return n}}var Sm=require("async_hooks");class Wl{constructor(){this.storage=new Sm.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}function $0(e,{organization:t,projectId:i,prefix:n,severityAllowList:r=["error"],sendExceptionsToPostHog:o=!0}={}){return(s)=>{if(!(r==="*"||r.includes(s.level)))return s;if(!s.tags)s.tags={};let l=s.tags[xm.POSTHOG_ID_TAG];if(l===void 0)return s;let g=e.options.host??"https://us.i.posthog.com",d=new URL(`/project/${e.apiKey}/person/${l}`,g).toString();s.tags["PostHog Person URL"]=d;let c=s.exception?.values||[],u=c.map((p)=>({...p,stacktrace:p.stacktrace?{...p.stacktrace,type:"raw",frames:(p.stacktrace.frames||[]).map((b)=>({...b,platform:"node:javascript"}))}:void 0})),m={$exception_message:c[0]?.value||s.message,$exception_type:c[0]?.type,$exception_level:s.level,$exception_list:u,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:c[0]?.value||s.message,$sentry_exception_type:c[0]?.type,$sentry_tags:s.tags};if(t&&i)m.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+s.event_id;if(o)e.capture({event:"$exception",distinctId:l,properties:m});return s}}class xm{static#i=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,n,r){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(o,s){let a=s()?.getClient()?.getDsn()?.projectId;o($0(e,{organization:t,projectId:a,prefix:i,severityAllowList:n,sendExceptionsToPostHog:r??!0}))}}}class Vl extends yl{getLibraryId(){return"posthog-node"}initializeContext(){return new Wl}createErrorPropertiesBuilder(){return new Ye.ErrorPropertiesBuilder([new Ye.EventCoercer,new Ye.ErrorCoercer,new Ye.ObjectCoercer,new Ye.StringCoercer,new Ye.PrimitiveCoercer],Ye.createStackParser("node:javascript",Ye.nodeStackLineParser),[au(),um,pm()])}}class K extends Error{code;status;body;requestId;constructor(e,t,i,n,r){super(e);this.name="PotatoApiError",this.code=t,this.status=i,this.body=n,this.requestId=r}static fromResponse(e,t,i){let n=i===void 0?"":` (request id: ${i})`;return new K(`Potato API request failed with status ${e}${n}`,"http",e,t,i)}static waitTimeout(e){return new K(`Potato API job did not reach a terminal status within ${e} ms`,"wait_timeout",void 0,{timeoutMs:e})}}class fi 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:i,reason:n})=>`- ${i}: ${n}`).join(`
|
|
37
37
|
`);return new fi(`Pipeline graph validation failed
|
|
38
38
|
${t}`,e)}}var He=require("fs/promises"),Xm=require("os"),hi=require("path");class H extends Error{hint;constructor(e,t){super(e,t.cause===void 0?void 0:{cause:t.cause});this.name="TolokaCliError",this.hint=t.hint}}function A(e,t,i){if(!e)throw new H(t,i)}var Ym=(e)=>("disabled"in e)?void 0:`Hint: ${e.description}`,k={description:"This looks like a defect in the CLI or the platform. Write a report as the toloka-report-issue skill describes, then send it with toloka report <report.md>."},Pt={description:"Retry the command; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>."},Ae={description:"Reinstall @toloka-platform/sdk to restore the bundled files."};class hr extends H{constructor(e,t){super(e,t);this.name="CredentialsError"}}var Om=(e)=>e.HOME??Xm.homedir(),q0=(e)=>e.XDG_CONFIG_HOME??hi.join(Om(e),".config"),Me=(e=process.env)=>e.TOLOKA_CREDENTIALS_FILE??hi.join(q0(e),"toloka","credentials.json"),Um=(e=process.env)=>hi.join(Om(e),".toloka","credentials.json"),ss=(e=process.env)=>hi.dirname(Me(e)),Em=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t-=1;return t===e.length?e:e.slice(0,t)},ft=(e)=>{let t=Em(e.trim());try{let i=new URL(t);return i.hash="",i.search="",Em(i.toString())}catch{return t}},os=(e,t)=>typeof e==="object"&&e!==null?Reflect.get(e,t):void 0,eG=(e)=>{if(typeof e!=="object"||e===null)return;let t=Reflect.get(e,"id");if(typeof t!=="string"||t.length===0)return;let i=Reflect.get(e,"name");if(i!==void 0&&typeof i!=="string")return;return i===void 0?{id:t}:{id:t,name:i}},tG=(e)=>{if(e===void 0||typeof e!=="object"||e===null||Array.isArray(e))return;let t=Object.create(null);for(let[i,n]of Object.entries(e)){if(i.length===0)return;let r=eG(n);if(r===void 0)return;Object.defineProperty(t,i,{value:r,writable:!0,enumerable:!0,configurable:!0})}return t},iG=(e,t)=>{let i=tG(e);if(i===void 0)return;if(typeof t==="string"){if(t.length===0||!Object.hasOwn(i,t))return;return{current:t,projects:i}}if(t!==void 0)return;return Object.keys(i).length===0?{}:{projects:i}},nG=(e)=>{let t=os(e,"baseUrl"),i=os(e,"apiKey");if(typeof t!=="string"||t.length===0)return;if(i!==void 0&&(typeof i!=="string"||i.length===0))return;let n=i===void 0?{baseUrl:t}:{baseUrl:t,apiKey:i},r=os(e,"current"),o=os(e,"projects");if(r===void 0&&o===void 0)return n;let s=iG(o,r);if(s===void 0)return;return{...n,...s}};async function Zr(e){let t;try{t=await He.readFile(e,"utf8")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return"missing";return"invalid"}try{let i=nG(JSON.parse(t));return i===void 0?"invalid":{credentials:i}}catch{return"invalid"}}async function Bl(e=process.env){let t=Me(e),i=await Zr(t);if(i!=="missing"){if(i==="invalid")throw new hr(`Invalid credentials file at ${t}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:i.credentials,path:t,legacy:!1}}if(e.TOLOKA_CREDENTIALS_FILE!==void 0)return;let n=Um(e),r=await Zr(n);if(r==="missing")return;if(r==="invalid")throw new hr(`Invalid credentials file at ${n}. Run toloka logout, then toloka login.`,{hint:{disabled:!0}});return{credentials:r.credentials,path:n,legacy:!0}}async function dn(e,t){try{return{found:await Bl(e)}}catch(i){if(!(i instanceof hr)||t===void 0)throw i;return{found:void 0,warning:i.message}}}async function Jm(e=process.env){return(await Bl(e))?.credentials}async function jt(e=process.env){let t=await Bl(e);if(t!==void 0)return t;throw new hr(`No stored credentials found at ${Me(e)}. Run toloka login.`,{hint:{disabled:!0}})}var rG=(e)=>{let t=e.projects,i=t!==void 0&&Object.keys(t).length>0;return{baseUrl:e.baseUrl,...e.apiKey===void 0?{}:{apiKey:e.apiKey},...e.current===void 0?{}:{current:e.current},...i?{projects:t}:{}}},Tm=async(e)=>{try{let t=await He.lstat(e);A(!t.isSymbolicLink(),`Refusing to write through symbolic link ${e}.`,{hint:{description:"Replace the symbolic link with a regular file or directory, then retry."}})}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;throw t}};async function Nt(e){let t=hi.dirname(e);await Tm(t),await Tm(e),await He.mkdir(t,{recursive:!0,mode:448}),await He.chmod(t,448)}async function yr(e,t=process.env){let i=Me(t);return await Nt(i),await He.writeFile(i,`${JSON.stringify(rG(e),null,2)}
|
|
39
|
-
`,{mode:384}),await He.chmod(i,384),i}var oG=async(e)=>{try{return await He.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},Rl=(e=process.env)=>[Me(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Um(e)]:[]];async function jm(e=process.env){let t=[];for(let i of Rl(e)){if(!await oG(i))continue;await He.rm(i,{force:!0}),t.push(i)}return t}var sG=16,zm=(e)=>e.length>sG?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var $e=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},cn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var Gl={name:"@toloka-platform/sdk",version:"0.17.
|
|
39
|
+
`,{mode:384}),await He.chmod(i,384),i}var oG=async(e)=>{try{return await He.stat(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}},Rl=(e=process.env)=>[Me(e),...e.TOLOKA_CREDENTIALS_FILE===void 0?[Um(e)]:[]];async function jm(e=process.env){let t=[];for(let i of Rl(e)){if(!await oG(i))continue;await He.rm(i,{force:!0}),t.push(i)}return t}var sG=16,zm=(e)=>e.length>sG?`${e.slice(0,4)}${"*".repeat(e.length-8)}${e.slice(-4)}`:"*".repeat(e.length);var $e=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"},cn=(e)=>{if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"};var Gl={name:"@toloka-platform/sdk",version:"0.17.2",private:!1,description:"Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",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","./testing":"./src/testing/index.ts","./checks":"./src/checks/index.ts","./examples/face-image-collection":"./examples/face-image-collection/pipeline.ts"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/",tag:"latest"},scripts:{build:"bun ./scripts/build-cli.ts ./dist/cli",generate:"orval --config ./openapi/orval.config.js","generate:check":"bun ./scripts/check-generated-client.ts",prepack:"bun run build","sync-skill-catalog":"bun ./scripts/sync-skill-catalog.ts","sync-task-ui-declarations":"bun ./scripts/sync-task-ui-declarations.ts",test:"vitest run","test:browser":"vitest run --config vitest.browser.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@inquirer/select":"5.2.1","@typescript/vfs":"1.6.2",ajv:"8.17.1","ajv-formats":"3.0.1",commander:"15.0.0","es-toolkit":"1.42.0","jsonpath-rfc9535":"1.3.0","oxc-parser":"0.138.0","posthog-node":"5.46.1","typescript-api":"npm:typescript@6.0.3"},devDependencies:{"@types/node":"24.10.1",orval:"8.40.0",playwright:"1.56.1",typescript:"7.0.2",vitest:"4.1.0",yaml:"2.9.0"},peerDependencies:{playwright:">=1.56.1 <2",vitest:">=4.1.0 <5"},peerDependenciesMeta:{playwright:{optional:!0},vitest:{optional:!0}},engines:{bun:">=1.4.0"},tolokaBuild:{commit:"7aada2f0e0f63c9f8dc17c6d4486bca906c62468"}};var We=Gl.name,ae=Gl.version,wl=(e)=>{let t=/^(\d+)\.(\d+)\.(\d+)(?:-preview\.(\d+))?$/u.exec(e);if(t===null)return;let[,i,n,r,o]=t;return[Number(i),Number(n),Number(r),o===void 0?Number.POSITIVE_INFINITY:Number(o)]},Dm=(e)=>{let t=wl(e);if(t===void 0)return;return t[3]===Number.POSITIVE_INFINITY?"latest":"preview"},Fl=(e,t)=>{let i=wl(e),n=wl(t);if(i===void 0||n===void 0)return;let r=Math.max(i.length,n.length);for(let o=0;o<r;o+=1){let s=i[o]??0,a=n[o]??0;if(s<a)return-1;if(s>a)return 1}return 0};var Zi=(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},lG=(e)=>{if(e.code==="wait_timeout")return"Hint: The job is still running. Check it later with its status command; commands that accept --timeout can wait longer.";if(e.status===401||e.status===403)return"Hint: Run toloka whoami to see which key and platform are in use; toloka login stores a new key.";if(e.status===404)return"Hint: Check the id against toloka project current and the matching list command; ids belong to one project on one platform.";if(e.status===429)return"Hint: The platform is rate limiting this key; wait a moment and retry.";if(e.status===503&&e.body==="Tunnel unavailable; the request was not sent")return"Hint: The sandbox lost its connection to the platform (usually a platform restart) and it was not restored within 90 seconds; the request was not sent. Retry in a minute.";if(e.status!==void 0&&e.status>=500)return"Hint: The platform failed to handle the request. Retry; if it keeps failing, write a report as the toloka-report-issue skill describes and send it with toloka report <report.md>.";return},_m=(e)=>e.filter((t)=>t!==void 0&&t.length>0).join(`
|
|
40
40
|
`),In=(e)=>{if(e instanceof K)return e;if(e instanceof AggregateError)for(let t of e.errors){let i=In(t);if(i!==void 0)return i}return e instanceof Error?In(e.cause):void 0},zt=(e)=>{if(e instanceof H){let t=In(e.cause),i=t===void 0?[]:t.message===e.message?[Zi(t)]:[t.message,Zi(t)];return _m([e.message,...i,Ym(e.hint)])}if(e instanceof K)return _m([e.message,Zi(e),lG(e)]);return e instanceof Error?e.message:String(e)};var gG="phc_kqHt0f53B5MVqURyzWpW1aNlbOmYt1YbUYza0JPcg19",dG="https://eu.posthog.com",cG={"--source-root":!0,"--api-key":!0,"--base-url":!0,"--project-id":!0};function IG(e){let t=e.TOLOKA_TELEMETRY??process.env.TOLOKA_TELEMETRY;if(cn(t))return!1;if($e(t))return!0;if($e(e.DO_NOT_TRACK??process.env.DO_NOT_TRACK))return!1;if($e(e.CI??process.env.CI))return!1;if($e(process.env.VITEST))return!1;return!0}var uG={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,create:!0,fields:!0,load:!0,upload:!0},"delivery-order":{list:!0},audience:{specialization:{list:!0}},training:{list:!0,get:!0,create:!0,update:!0,cost:!0,run:!0,runs:!0,status:!0,resume:!0,cancel:!0,metrics:!0,logs:!0},"batch-inference":{run:!0,list:!0,status:!0,confirm:!0,resume:!0,cancel:!0},"base-model":{list:!0,get:!0},"generation-model":{list:!0},model:{list:!0,get:!0,versions:!0,create:!0,archive:!0,version:{download:!0}},secret:{set:!0},skill:{list:!0,search:!0,install:!0},config:{get:!0,set:!0}},mG={apply:!0,check:!0,"auth-status":!0,config:!0,help:!0,import:!0,init:!0,login:!0,logout:!0,plan:!0,status:!0,validate:!0,report:!0,version:!0,whoami:!0},Km=(e)=>{let t=e[0];if(t===void 0)return"help";let i=uG[t];if(i===void 0)return mG[t]===!0?t:"unknown";let n=e[1],r=n===void 0?void 0:i[n];if(r===void 0)return t;if(r===!0)return`${t} ${n}`;let o=e[2];return o!==void 0&&r[o]===!0?`${t} ${n} ${o}`:`${t} ${n}`};function ls(e){if(e.includes("-v")||e.includes("--version"))return"version";let t=[];for(let i=0;i<e.length;i+=1){let n=e[i];if(n===void 0)continue;if(n==="--help"||n==="-h")break;if(n.startsWith("-")){if(cG[n]===!0)i+=1;continue}t.push(n)}return Km(t)}function CG(e){if(e===void 0)return{error_code:"command_failed"};let t=In(e);if(t!==void 0)return{error_code:t.code};if(e instanceof fi)return{error_code:e.code};return{error_code:e instanceof Error?"error":"unknown"}}var pG=(e)=>{let t=In(e);return t===void 0?{}:{status_code:t.status,request_id:t.requestId}},AG=(e)=>as.join(as.dirname(Me(e)),"anonymous-id"),bG=async(e)=>{let t=AG(e);await Nt(t);try{let n=(await yi.readFile(t,"utf8")).trim();if(n.length>0)return await yi.chmod(t,384),n}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ENOENT"))throw n}let i=Qm.randomUUID();return await yi.writeFile(t,`${i}
|
|
41
41
|
`,{mode:384}),await yi.chmod(t,384),i},fG=()=>({shouldIdentify:!1,issueReportingEnabled:!1,identifyCurrentUser(){},captureCommand(){},async submitIssueReport(){A(!1,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}})},async shutdown(){}});function Lm(e){let{environment:t}=e;if(e.client===void 0&&!IG(t))return fG();let{client:i,distinctId:n}=e,r,o=[],s=(d)=>{o.push(d)};i?.on?.("error",s);let a=async()=>{if(i!==void 0&&n!==void 0)return;if(i===void 0){let d=new Vl(gG,{host:dG,flushAt:1,flushInterval:0});d.on("error",s),i=d}n??=await bG(t)},l=()=>({sdk_version:ae,bun_version:typeof process.versions.bun==="string"?process.versions.bun:void 0,actor:"user",channel:"cli"}),g=a().catch(()=>{});return{issueReportingEnabled:!0,shouldIdentify:!0,identifyCurrentUser(d){g=g.then(()=>{if(i===void 0||n===void 0)return;if(r===d.id)return;if(r=d.id,n!==d.id)i.alias({distinctId:d.id,alias:n});n=d.id}).catch(()=>{})},captureCommand(d){g=g.then(()=>{if(i===void 0||n===void 0)return;let c=l(),u=Km(d.command.split(" "));if(d.outcome==="failed"){let m=CG(d.error),p=pG(d.error);if(d.error!==void 0){let b=new H(`CLI command failed: ${m.error_code}`,{hint:{disabled:!0}});b.name="PotatoCliError",i.captureException(b,n,{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,$process_person_profile:!1,$geoip_disable:!0,...m,...p})}i.capture({distinctId:n,event:"sdk_cli_command_failed",disableGeoip:!0,properties:{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,...m,...p}});return}i.capture({distinctId:n,event:"sdk_cli_command_completed",disableGeoip:!0,properties:{...c,command:u,duration_ms:d.durationMs,exit_code:d.exitCode,outcome:d.outcome}})}).catch(()=>{})},submitIssueReport(d){let c=g.then(async()=>{A(i&&n,"PostHog issue reporting could not be initialized.",{hint:{description:"Set TOLOKA_TELEMETRY=1 and check that this machine can reach PostHog, then retry."}}),o.length=0,i.capture({distinctId:n,event:"sdk_cli_issue_report_submitted",disableGeoip:!0,properties:{...l(),report_id:d.reportId,report_text:d.reportText,report_length_bytes:new TextEncoder().encode(d.reportText).length,authored_by:d.authoredBy,platform:d.platform,$process_person_profile:!1}}),await i.flush();let u=o[0];if(o.length=0,u!==void 0)throw u});return g=c.catch(()=>{}),c},async shutdown(){try{await g,await i?.shutdown(2000)}catch{}}}}var Yn=require("crypto"),oa=require("child_process"),so=require("events"),Tt=require("fs"),Q=require("fs/promises"),de=require("path"),sa=require("stream"),Af=require("stream/promises");var Br=require("fs"),Vi=require("path");var Wi=()=>Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0,Wr=(e,t=Wi())=>t?{...e,BUN_BE_BUN:"1"}:e;var Mm=Vi.join("bin","toloka.js"),$m=(e)=>{try{return Br.realpathSync(e)}catch{return e}},Vr=(e)=>{let t=Vi.join(e,Mm);if(Br.existsSync(t))return t;let i=Vi.dirname(e);return i===e?void 0:Vr(i)},qm=(e=process.argv[1])=>(e===void 0?void 0:Vr(Vi.dirname($m(e))))??Vr(process.cwd()),hG=(e=process.argv[1])=>{let t=e===void 0?void 0:$m(e);if(t!==void 0&&Br.existsSync(t)&&Vr(Vi.dirname(t))!==void 0)return t;let i=Vr(process.cwd());return A(i!==void 0,`Cannot locate the toloka CLI entry point. An installed @toloka-platform/sdk ships ${Mm} in a directory above its runtime entry, but none exists above ${e??"the unset process.argv[1]"} or above ${process.cwd()}. Reinstall @toloka-platform/sdk.`,{hint:{disabled:!0}}),i},gs=(e,t,i={})=>{let n=i.executable??process.execPath;if(!(i.native??Wi()))return{executable:i.executable??(Reflect.get(process.versions,"bun")?process.execPath:"bun"),args:[hG(i.runtimeEntry),...e],environment:t};let r={...t};return delete r.BUN_BE_BUN,{executable:n,args:[...e],environment:r}};var mn=require("fs/promises"),eC=require("path");var un="auto-update",tC={autoUpdate:!0};class ds extends H{constructor(e,t){super(e,t);this.name="SettingsError"}}var iC=(e=process.env)=>eC.join(ss(e),"settings.json"),ZG=(e)=>{let t=typeof e==="object"&&e!==null?Reflect.get(e,"autoUpdate"):void 0;if(typeof t!=="boolean")return tC;return{autoUpdate:t}};async function Rr(e=process.env){try{return ZG(JSON.parse(await mn.readFile(iC(e),"utf8")))}catch{return tC}}async function yG(e,t=process.env){let i=iC(t);return await Nt(i),await mn.writeFile(i,`${JSON.stringify({autoUpdate:e.autoUpdate},null,2)}
|
|
42
42
|
`,{mode:384}),await mn.chmod(i,384),i}var WG=(e)=>{if($e(e))return!0;if(cn(e))return!1;throw new ds(`Expected a boolean (true or false), got ${JSON.stringify(e)}.`,{hint:{description:"Run toloka config set auto-update true or false."}})},VG=(e)=>`${un}=${e.autoUpdate}`,Hl=(e,t)=>{if(t===void 0||t.length===0)return{output:VG(e)};if(t!==un)throw new ds(`Unknown setting "${t}". Known settings: ${un}.`,{hint:{disabled:!0}});return{output:String(e.autoUpdate)}};async function nC(e,t,i){if(t!==un)throw new ds(`Unknown setting "${t}". Known settings: ${un}.`,{hint:{disabled:!0}});let n={autoUpdate:WG(i)};return await yG(n,e),{settings:n,output:`Set ${un} to ${n.autoUpdate}.`}}var gf=require("fs"),df=require("child_process"),cf=require("module"),If=require("events"),ri=require("fs/promises"),ec=require("os"),ni=require("path");var sC=require("oxc-parser");var rC=require("oxc-parser"),vl=(e,t,i)=>{let n=rC.parseSync(e,t,{lang:i,preserveParens:!1});return n.errors.some((r)=>r.severity==="Error")?null:n.program},oC=(e)=>{let t=e?.value;if(!t)return null;if(t.type==="Literal")return typeof t.value==="string"?t.value:null;if(t.type==="JSXExpressionContainer"){let i=t.expression;if(i.type==="Literal"&&typeof i.value==="string")return i.value;if(i.type==="TemplateLiteral"&&i.expressions.length===0)return i.quasis[0]?.value.cooked??null}return null};var kl=(e)=>{let t=RG(e.postprocess);if(!t||t.size===0)return[];let i=BG(e.code);if(!i||i.size===0)return[];return[...i].filter(([n])=>t.has(n)).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let o=r===n?`path="${r}"`:`path="${r}" \u2014 a dotted path binds its top-level key "${n}"`;return{severity:"error",text:`Postprocess returns the key "${n}", but a Field component is bound to it (${o}). Every submission of this interface fails at runtime with: Postprocess cannot write key '${n}' because a component is bound to it. Fix: bind the Field to a raw key (e.g. path="raw_${n}") and derive "${n}" in postprocess, or remove "${n}" from the postprocess return.`}})},BG=(e)=>{let t=vl("code.tsx",`(
|
|
@@ -357,7 +357,7 @@ ${o}`}}async function Zy(e,t){let i=await Ay(e,t.projectId);if(i.length===0)retu
|
|
|
357
357
|
`)}}async function tV(e,t){let i=await e.runs.cancel({runId:t.runId,pendingHumanQa:t.acceptWithoutReview?"accept_without_review":void 0});return{outcome:"canceled",output:`Requested cancellation of run ${i.id}; it is now ${i.status}.`}}var cO=(e)=>{let t=` ${e.index} ${e.id} ${e.state.status}`;if(e.state.status!=="failed")return t;if(!("error"in e.state))return`${t}
|
|
358
358
|
${nO}`;return e.state.error===null?t:`${t}
|
|
359
359
|
${e.state.error}`};async function iV(e,t){let i=t.limit??20,n=t.itemScanLimit??Math.max(500,i),r=[],o=0;for await(let l of e.runs.listAllItems({runId:t.runId})){if(o+=1,t.failedOnly!==!0||l.state.status==="failed")r.push(l);if(r.length>=i||o>=n)break}if(r.length===0)return{outcome:"reported",output:t.failedOnly===!0&&o>=n?`No failed items in the first ${n} items.`:t.failedOnly===!0?"No failed items.":"No items yet."};return{outcome:"reported",output:[o>=n&&r.length<i?`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length} after scanning ${n}, limit ${i}):`:`${t.failedOnly===!0?"Failed items":"Items"} for run ${t.runId} (showing ${r.length}, limit ${i}):`,...r.map(cO)].join(`
|
|
360
|
-
`)}}var nV=(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},IO=(e)=>{let t=[0,0,0];for(let i of e)for(let n=0;n<3;n+=1){let r=i[n];t[n]=Math.max(t[n]??0,r?.length??0)}return e.map((i)=>i.map((n,r)=>r===0?n.padEnd(t[0]??0):n.padStart(t[r]??0)).join(" "))},rV=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let r of e.subLines??[])if(nV(r))n.push(...rV(r,t+1));return n},uO=(e)=>{let t=[],i=[]
|
|
360
|
+
`)}}var nV=(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},IO=(e)=>{let t=[0,0,0];for(let i of e)for(let n=0;n<3;n+=1){let r=i[n];t[n]=Math.max(t[n]??0,r?.length??0)}return e.map((i)=>i.map((n,r)=>r===0?n.padEnd(t[0]??0):n.padStart(t[r]??0)).join(" "))},rV=(e,t)=>{let n=[[`${" ".repeat(t)}${e.label}`,e.expectedTotal,e.maxTotal]];for(let r of e.subLines??[])if(nV(r))n.push(...rV(r,t+1));return n},uO=(e)=>{let t=[],i=[];for(let n of e){if(n.kind==="priced"){t.push([n.nodeNameDisplay,n.expectedTotal,n.maxTotal]);for(let r of n.displayBreakdown)if(nV(r))t.push(...rV(r,1));continue}i.push(n.kind==="validation-errors"?` ${n.nodeNameDisplay} skipped (validation errors)`:` ${n.nodeNameDisplay} not billed`)}return{billed:t,unpriced:i}},mO=(e)=>{let t=e.expected===e.worstCase?[["Run cost",e.expected,""]]:[["Expected run cost",e.expected,""],["Maximum run cost","",e.worstCase]];if(e.bestCase!=null)t.push(["Best case",e.bestCase,"N/A"]);if(e.perItemExpected!=null)t.push(["Per item",e.perItemExpected,e.perItemWorstCase??""]);return t},CO=(e,t)=>{let{billed:i,unpriced:n}=uO(e.nodes),r=mO(e.total),o=IO([["Item","Expected","Maximum"],...i,...r]),s=o.slice(0,1+i.length),a=o.slice(1+i.length),l=[`Cost estimate for ${t} ${e.dataset.itemCount} item${e.dataset.itemCount===1?"":"s"}`,"",...s];if(i.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(`
|
|
361
361
|
`)};async function oV(e,t){let i=await $n({client:e,...t}),n=await e.pipelines.estimateCost({pipelineId:i.pipelineId,...t.itemLimit===void 0?{}:{itemLimit:t.itemLimit}});return{output:CO(n,i.name)}}var sV=(e,t)=>{let{context:i,exitCode:n,globals:r}=t,o="pipeline name or id; required unless a TTY picker can choose among several",s=e.command("pipeline").description("operate on a live pipeline in the selected project");s.command("list").option("--limit <n>","maximum pipelines to list",ge).description("list live pipelines in the selected project").action(async(a)=>{let{client:l,projectId:g,state:d}=await R(r(),i);S(g);let c=await _W({client:l,projectId:g,state:d,...a.limit===void 0?{}:{limit:a.limit}});i.io.stdout(c.output)}),s.command("run").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--wait","wait for the run to reach a terminal state",!1).option("--timeout <ms>","how long the command may wait in total, for the lints and, with --wait, for the run",ge).description("start a run on an applied pipeline").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await R(r(),i);S(c);let u=await $W(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},wait:l.wait,...l.timeout===void 0?{}:{timeoutMs:l.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(u.output),n.value=uo(u.outcome)}),s.command("lint").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--wait","wait for the lints to finish",!1).option("--timeout <ms>","how long to wait",ge).description("run the pipeline's lints that have no current result").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await R(r(),i);S(c);let u=await MW(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},wait:l.wait,...l.timeout===void 0?{}:{timeoutMs:l.timeout},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(u.output),n.value=uo(u.outcome)}),s.command("status").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").description("report the latest run's state and item counts").action(async(a)=>{let{client:l,state:g,projectId:d}=await R(r(),i);S(d);let c=await eV(l,{projectId:d,state:g,...a===void 0?{}:{pipeline:a},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(c.output),n.value=uo(c.outcome)}),s.command("runs").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--limit <n>","how many runs to list",ge).description("list recent runs").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await R(r(),i);S(c);let u=await qW(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},...l.limit===void 0?{}:{limit:l.limit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(u.output)}),s.command("cost").argument("[name]","pipeline name or id; required unless a TTY picker can choose among several").option("--item-limit <n>","cap how many items to price",ge).description("forecast what a run of this pipeline would bill").action(async(a,l)=>{let{client:g,state:d,projectId:c}=await R(r(),i);S(c);let u=await oV(g,{projectId:c,state:d,...a===void 0?{}:{pipeline:a},...l.itemLimit===void 0?{}:{itemLimit:l.itemLimit},...i.io.select===void 0?{}:{select:i.io.select}});i.io.stdout(u.output)}),s.command("cancel").argument("<runId>","run to cancel").option("--accept-without-review","accept items in Human QA without review now; you pay for them as for completed items",!1).description("request cancellation of a run").action(async(a,l)=>{let{client:g}=await R(r(),i),d=await tV(g,{runId:a,acceptWithoutReview:l.acceptWithoutReview});i.io.stdout(d.output)}),s.command("results").argument("<runId>","run to read").option("--limit <n>","how many items to scan",ge).option("--failed","only report failed items",!1).description("report a run's items").action(async(a,l)=>{let{client:g}=await R(r(),i),d=await iV(g,{runId:a,failedOnly:l.failed,...l.limit===void 0?{}:{limit:l.limit}});i.io.stdout(d.output),n.value=uo(d.outcome)})};var pO=["read","write","deploy","labeling-read","labeling-write","labeling-deploy"],aV=(e,t)=>{let{context:i,exitCode:n,globals:r}=t,o=e.command("project").description("select and manage the current platform project");o.command("list").option("--limit <n>","maximum projects to list",ge).description("list remote projects this key can see").action(async(a)=>{let l=r(),{client:g,stored:d,state:c}=await R(l,i),u=Aa(l,i,d,c);await iZ({client:g,io:i.io,...u===void 0?{}:{context:u},...a.limit===void 0?{}:{limit:a.limit}})}),o.command("add").argument("[alias]","local name for this project").argument("[projectId]","platform project id").description("register a live project and select it").action(async(a,l)=>{let g=r(),d=await jt(i.environment),{client:c}=await Ti(g,i,void 0,d.credentials);await rZ({environment:i.environment,flags:g,client:c,io:i.io,afterPreflight:async()=>Ei(c,i.analytics),...a===void 0?{}:{alias:a},...l===void 0?{}:{projectId:l}})}),o.command("switch").argument("<alias>","local project alias").description("select a registered project").action(async(a)=>{await oZ({environment:i.environment,flags:r(),alias:a,io:i.io})}),o.command("current").description("show the project this command would use").action(async()=>{let a=r(),l=await Jc(a,i),g=await Ie(a,i.io),d=await he(g);if(aZ({flags:a,environment:i.environment,stored:l,...d===void 0?{}:{state:d},io:i.io}).project===void 0)n.value=1}),o.command("url").description("print the current project URL").action(async()=>{let{baseUrl:a,client:l,projectId:g}=await R(r(),i);S(g);let d=await l.projects.get({projectId:g}),c=new URL(`/teams/${encodeURIComponent(d.teamId)}/projects/${encodeURIComponent(d.id)}`,a);i.io.stdout(c.href)}),o.command("remove").argument("<alias>","local project alias").description("forget a local project alias").action(async(a)=>{await sZ({environment:i.environment,flags:r(),alias:a,io:i.io})}),o.command("untrack").argument("<type>","pipeline or dataset").argument("<name>","tracked resource name").option("--confirm","confirm untracking in a non-interactive environment",!1).description("remove a pipeline or dataset from local tracking without deleting it").action(async(a,l,g)=>{A(a==="pipeline"||a==="dataset","Resource type must be pipeline or dataset.",{hint:{description:"Run toloka project untrack pipeline <name> or toloka project untrack dataset <name>."}});let d=await Ie(r(),i.io);await nZ({sourceRoot:d,type:a,name:l,confirm:g.confirm,io:i.io})}),o.command("token").addOption(new Ii("--preset <name>","permission preset").choices(pO).default("write")).option("--permissions <list>","comma-separated resource:operation pairs instead of a preset").option("--expires-in <seconds>","lifetime in seconds (60..21600)",ge).option("--projects <list>","comma-separated ids of further projects the token may act in (same team)").description("mint a project-scoped token for agents and scripts; printed once, never stored").action(async(a)=>{let{client:l,credential:g,projectId:d}=await R(r(),i);S(d);let c=g.type==="scopedToken"||g.type==="apiKey"&&g.apiKey.startsWith(oc);A(!c,"A scoped token cannot issue tokens.",{hint:{disabled:!0}});let u=a.permissions===void 0?{preset:a.preset}:{permissions:a.permissions.split(",").map((b)=>b.trim())},{token:m,expiresAt:p}=await l.projects.createToken({projectId:d,...u,...a.expiresIn===void 0?{}:{expiresInSeconds:a.expiresIn},...a.projects===void 0?{}:{projectIds:a.projects.split(",").map((b)=>b.trim())}});i.io.stdout(m),i.io.stderr(`Token expires at ${p}. Use it as TOLOKA_SCOPED_TOKEN.`)}),o.command("tokens").description("list live project-scoped tokens").action(async()=>{let{client:a,projectId:l}=await R(r(),i);S(l);let g=[];for await(let d of a.projects.listAllTokens({projectId:l}))g.push(d);i.io.stdout(g.length===0?"No live tokens.":_([["Id","User","Expires","Projects","Permissions"],...g.map((d)=>[d.id,d.userId,d.expiresAt,d.projectIds.join(","),d.permissions.join(",")])]))}),o.command("revoke-token").argument("<tokenId>","token id from toloka project tokens").description("revoke a project-scoped token; it stops working immediately").action(async(a)=>{let{client:l,projectId:g}=await R(r(),i);S(g),await l.projects.revokeToken({projectId:g,tokenId:a}),i.io.stdout(`Revoked ${a}.`)}),o.command("revoke-tokens").description("revoke every live project-scoped token of the project; they stop working immediately").action(async()=>{let{client:a,projectId:l}=await R(r(),i);S(l);let{revokedCount:g}=await a.projects.revokeAllTokens({projectId:l});i.io.stdout(`Revoked ${g} token${g===1?"":"s"}.`)});let s=o.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");s.option("--delivery-order-id <id>","Sunday delivery order id (required when the owning team is internal)"),s.action(async(a,l)=>{let g=r(),d=await jt(i.environment),{client:c}=await Ti(g,i,void 0,d.credentials),u=await Ie(g,i.io);await lZ({environment:i.environment,flags:g,client:c,io:i.io,sourceRoot:u,afterPreflight:async()=>Ei(c,i.analytics),...a===void 0?{}:{alias:a},...l.name===void 0?{}:{name:l.name},...l.teamId===void 0?{}:{teamId:l.teamId},...l.deliveryOrderId===void 0?{}:{deliveryOrderId:l.deliveryOrderId}})})};var lV=require("crypto"),EI=require("fs"),Xa=require("fs/promises"),ut=require("path");var AO=262144,bO=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),fO=async(e,t)=>{let i=ut.relative(t,e);if(i===""||i===".."||i.startsWith(`..${ut.sep}`)||ut.isAbsolute(i))return;let n=i.split(ut.sep);for(let r=1;r<n.length;r+=1){let o=ut.join(t,...n.slice(0,r)),s=await Xa.lstat(o);A(!s.isSymbolicLink(),`Report file ${e} is inside the symbolic link ${o}; select a path that does not traverse symbolic links.`,{hint:{disabled:!0}})}},hO=async(e,t,i)=>{let n=ut.resolve(i,e);await fO(n,t);let r;try{r=await Xa.open(n,EI.constants.O_RDONLY|EI.constants.O_NOFOLLOW)}catch(o){throw A(!(o instanceof Error&&("code"in o)&&o.code==="ELOOP"),`Report file ${n} is a symbolic link; select the file it points to directly.`,{hint:{disabled:!0}}),o}try{let o=await r.stat();return A(o.isFile(),`Report file ${n} is not a regular file.`,{hint:{description:"Pass the path of a Markdown or text file."}}),A(o.size>0,`Report file ${n} is empty.`,{hint:{description:"Write the report first; the toloka-report-issue skill describes the format."}}),A(o.size<=AO,`Report file ${n} is ${o.size} bytes; the limit is 256 KiB.`,{hint:{description:"Trim the report to under 256 KiB, for example by shortening logs."}}),{handle:r,absolutePath:n,size:o.size}}catch(o){throw await r.close(),o}},ZO=async(e,t,i)=>{let n=await hO(e,t,i);try{let r=await n.handle.readFile();A(r.byteLength===n.size,`${n.absolutePath} changed while it was being read.`,{hint:{description:"Re-run toloka report once the file is no longer being written."}});try{return bO.decode(r)}catch{throw new H(`Report file ${n.absolutePath} is not valid UTF-8.`,{hint:{description:"Save the report as UTF-8 text."}})}}finally{await n.handle.close()}},yO=async(e,t)=>{if(t)return!0;if(e.prompt===void 0)return!1;let i=(await e.prompt("Send this report to Toloka? [y/N] ")).trim().toLowerCase();return i==="y"||i==="yes"};async function gV(e){let{analytics:t,io:i}=e;A(t.issueReportingEnabled,"Issue reporting is disabled. Re-run with TOLOKA_TELEMETRY=1.",{hint:{disabled:!0}});let n=await ZO(e.path,e.sourceRoot,e.cwd);if(i.stdout("Issue report preview:"),i.stdout(""),i.stdout(n.replace(/(?![\t\n])(?!\r\n)(?:\p{Cc}|\p{Bidi_Control})/gu,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)),i.stdout(""),i.stdout(`Authored by: ${e.authoredBy}`),i.stdout(`Platform: ${e.platform}`),i.stdout(""),!await yO(i,e.confirm))return i.stderr("Refusing to submit without confirmation in a non-interactive environment. Pass --confirm after reviewing the preview above."),1;let r=lV.randomUUID();return await t.submitIssueReport({reportId:r,reportText:n,authoredBy:e.authoredBy,platform:e.platform}),i.stdout(`Submitted issue report: ${r}`),0}var dV=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.command("report").argument("<markdownPath>","path to a UTF-8 Markdown report").option("--authored-by <who>","human or agent",IZ,"human").option("--confirm","confirm submission in a non-interactive environment",!1).description("preview and send an issue report to Toloka through PostHog").action(async(o,s)=>{A(i.analytics,"Issue reporting requires CLI analytics.",{hint:{description:"Set TOLOKA_TELEMETRY=1 to enable analytics, then re-run toloka report."}});let a=pa(r()),l=r().baseUrl??i.environment.TOLOKA_BASE_URL??gi(i.environment)??Yi;n.value=await gV({path:o,authoredBy:s.authoredBy,platform:new URL(l).origin,confirm:s.confirm,sourceRoot:a,cwd:process.cwd(),analytics:i.analytics,io:i.io})})};var cV=(e,t)=>{let{context:i,exitCode:n,globals:r}=t;e.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(s,a)=>{let{client:l,projectId:g}=await R(r(),i);S(g);let d=a.fromEnv===void 0?(await i.io.readStdin()).replace(/\r?\n$/u,""):i.environment[a.fromEnv];A(d!==void 0,`Missing secret value. Set ${a.fromEnv??"the named environment variable"} or pipe it to stdin.`,{hint:{disabled:!0}});try{let c=await Wy(l,{projectId:g,name:s,value:d});i.io.stdout(c.output)}catch{i.io.stderr(`Failed to set secret ${s}.`),n.value=1}})};var AV=require("crypto"),oe=require("fs/promises"),Ze=require("path");var IV=require("fs/promises"),uV=require("path");var Oa=(e,...t)=>e instanceof Error&&("code"in e)&&typeof e.code==="string"&&t.includes(e.code),Ua=(e)=>Oa(e,"ENOENT"),qn=async(e)=>{try{return await IV.lstat(e)}catch(t){if(Ua(t))return;throw t}},Ro=async(e,t,i="write")=>{let n=e;for(let r of t.split("/")){n=uV.join(n,r);let o=await qn(n);if(o===void 0)return;A(!o.isSymbolicLink(),`Refusing to ${i} through symbolic link ${n}.`,{hint:{description:"Replace the symbolic link with a regular directory, or point the command at the real path."}})}};var Ja="catalog.json",tr=".agents/skills",er="SKILL.md",XI="skills",mV=500,CV=1048576,bV=64,WO=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,VO=/^[a-f0-9]{64}$/u,fV="rerun the CLI installer to update",hV=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),pV=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"),TI=(e)=>typeof e==="string"&&e.trim().length>0,BO=(e)=>typeof e==="string"&&e.length<=bV&&WO.test(e),RO=(e)=>!e.includes("\\")&&!e.includes("\x00")&&e.split("/").every((t)=>t.length>0&&t!=="."&&t!==".."),GO=(e,t)=>{A(hV(e),t("every skill must be an object."),{hint:Ae});let{id:i,name:n,description:r,tags:o,version:s,digest:a,files:l}=e;return A(BO(i),t(`skill id ${JSON.stringify(i)} must be at most ${bV} lowercase letters, digits, and single hyphens.`),{hint:Ae}),A(TI(n),t(`skill ${i} needs a name.`),{hint:Ae}),A(TI(r),t(`skill ${i} needs a description.`),{hint:Ae}),A(pV(o),t(`skill ${i} tags must be strings.`),{hint:Ae}),A(TI(s),t(`skill ${i} needs a version.`),{hint:Ae}),A(typeof a==="string"&&VO.test(a),t(`skill ${i} digest must be the sha256 hex digest of its files.`),{hint:Ae}),A(pV(l)&&l.includes(er),t(`skill ${i} files must include ${er}.`),{hint:Ae}),A(l.every(RO),t(`skill ${i} files must be relative paths inside its directory.`),{hint:Ae}),A(new Set(l).size===l.length,t(`skill ${i} lists a file more than once.`),{hint:Ae}),{id:i,name:n,description:r,tags:o,version:s,digest:a,files:l}},wO=(e,t)=>{try{return JSON.parse(e)}catch(i){throw new H(`Invalid skill catalog ${t}: ${zt(i)}`,{cause:i,hint:Ae})}},FO=async(e)=>{try{return(await oe.stat(e)).isFile()}catch(t){if(Oa(t,"ENOENT","ENOTDIR"))return!1;throw t}},OI=async(e)=>{let t=Ze.join(e,XI);if(await FO(Ze.join(t,Ja)))return t;let i=Ze.dirname(e);return i===e?void 0:OI(i)};async function HO(e=process.argv[1]){if(Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0)return Ze.join(Ze.dirname(process.argv[1]),"skills");let t=e===void 0?void 0:await oe.realpath(e),i=t===void 0?void 0:await OI(Ze.dirname(t));if(i!==void 0)return i;let n=await OI(process.cwd()),r=t===void 0?"process.argv[1] names no runtime entry":`none exists between ${t} and the filesystem root`;return A(n!==void 0,`Cannot locate the bundled skill catalog. An installed @toloka-platform/sdk must ship ${XI}/${Ja} in a directory above its runtime entry, but ${r}, and no ${XI}/${Ja} exists above ${process.cwd()} either. Reinstall @toloka-platform/sdk.`,{hint:{disabled:!0}}),n}var UI=async()=>vO(await HO());async function vO(e){let t=Ze.join(e,Ja),i=(a)=>`Invalid skill catalog ${t}: ${a}`,{size:n}=await oe.stat(t);A(n<=CV,i(`the manifest is ${n} bytes; the limit is ${CV} bytes.`),{hint:Ae});let r=wO(await oe.readFile(t,"utf8"),t);A(hV(r)&&Array.isArray(r.skills),i("expected an object with a skills array."),{hint:Ae}),A(r.skills.length<=mV,i(`${r.skills.length} skills exceed the limit of ${mV}.`),{hint:Ae});let o=r.skills.map((a)=>GO(a,i)),s=new Set;for(let a of o)A(!s.has(a.id),i(`skill id ${a.id} appears more than once.`),{hint:Ae}),s.add(a.id);return{root:e,manifestPath:t,skills:o}}async function ZV(e,t){let i=AV.createHash("sha256");for(let n of t.toSorted())i.update(n),i.update("\x00"),i.update(await oe.readFile(Ze.join(e,n))),i.update("\x00");return i.digest("hex")}var kO=(e,t)=>{let i=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);if(i.length===0)return[];return e.map((n,r)=>{let o=[n.id,n.name,n.description,...n.tags].join(`
|
|
362
362
|
`).toLowerCase();return{skill:n,index:r,score:i.filter((s)=>o.includes(s)).length}}).filter(({score:n})=>n>0).toSorted((n,r)=>r.score-n.score||n.index-r.index).map(({skill:n})=>n)};async function PO(e,t){let i=Ze.join(e,tr,t.id);if(await qn(i)===void 0)return"not-installed";try{return await ZV(i,t.files)===t.digest?"current":"stale"}catch(n){if(Oa(n,"ENOENT","ENOTDIR"))return"stale";throw n}}var yV=({sourceRoot:e,skills:t})=>Promise.all(t.map(async(i)=>({...i,status:await PO(e,i)}))),NO=async(e,t,i,n)=>{await e(i,n);try{await e(t,i)}catch(r){try{await e(n,i)}catch(o){throw new H(`Failed to replace ${i}; the previous version is preserved at ${n}. ${zt(o)}`,{cause:r,hint:{description:`Move ${n} back to ${i} by hand, then re-run toloka skill install <skill-id> --force.`}})}throw r}await oe.rm(n,{recursive:!0,force:!0})};async function SO({catalog:e,sourceRoot:t,skillId:i,force:n=!1,rename:r=oe.rename}){let o=e.skills.find((c)=>c.id===i);A(o,`Skill ${JSON.stringify(i)} is not in the catalog bundled with ${We} ${ae}. Run \`toloka skill list\` to see the available skills; a newer release may ship it (${fV}).`,{hint:{disabled:!0}});let s=`${tr}/${o.id}`;await Ro(t,s);let a=Ze.join(t,s),l=await qn(a);A(l===void 0||n,`${s} already exists. Re-run with --force to replace it with the catalog version of ${o.id}.`,{hint:{disabled:!0}});let g=Ze.dirname(a);await oe.mkdir(g,{recursive:!0});let d=await oe.mkdtemp(Ze.join(g,`.${o.id}.tmp-`));try{for(let c of o.files){let u=Ze.join(d,c);await oe.mkdir(Ze.dirname(u),{recursive:!0});let m=Ze.join(e.root,o.id,c);if(Reflect.get(globalThis,"Bun")?.isStandaloneExecutable===!0)await oe.writeFile(u,await oe.readFile(m));else await oe.copyFile(m,u)}if(A(await ZV(d,o.files)===o.digest,`Skill ${o.id} failed its digest check: the packaged files do not match the catalog digest ${o.digest}. Nothing was installed.`,{hint:Ae}),l===void 0)await r(d,a);else await NO(r,d,a,`${d}.backup`)}catch(c){throw await oe.rm(d,{recursive:!0,force:!0}),c}return{skill:o,directory:a,replaced:l!==void 0}}var WV=(e,t)=>{if(t)return JSON.stringify(e,void 0,2);let i=Math.max(...e.map((r)=>r.id.length)),n=Math.max(...e.map((r)=>r.status.length));return e.flatMap((r)=>[`${r.id.padEnd(i)} ${r.status.padEnd(n)} ${r.name}`,` ${r.description}`]).join(`
|
|
363
363
|
`)};async function VV({sourceRoot:e,json:t,io:i}){let n=await UI();i.stdout(WV(await yV({sourceRoot:e,skills:n.skills}),t))}async function BV({sourceRoot:e,query:t,json:i,io:n}){let r=await UI(),o=await yV({sourceRoot:e,skills:kO(r.skills,t)});if(i||o.length>0){n.stdout(WV(o,i));return}n.stdout(`No skills match ${JSON.stringify(t)} in the catalog bundled with ${We} ${ae}. Run \`toloka skill list\` to see it; a newer release may add more (${fV}).`)}async function RV({sourceRoot:e,skillId:t,force:i,io:n}){let r=await UI(),o=await SO({catalog:r,sourceRoot:e,skillId:t,force:i}),s=`${tr}/${o.skill.id}`,a=o.skill.files.length;n.stdout(`${o.replaced?"Replaced":"Installed"} ${o.skill.id} in ${s} (${a} ${a===1?"file":"files"}). Start with ${s}/${er}.`)}var GV=(e,t)=>{let{context:i,globals:n}=t,r=e.command("skill").description("discover bundled agent skills and install them into .agents/skills");r.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(o)=>{let s=await Ie(n(),i.io);await VV({sourceRoot:s,json:o.json,io:i.io})}),r.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(o,s)=>{let a=await Ie(n(),i.io);await BV({sourceRoot:a,query:o,json:s.json,io:i.io})}),r.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(o,s)=>{let a=await Ie(n(),i.io);await RV({sourceRoot:a,skillId:o,force:s.force,io:i.io})})};var YV=require("fs/promises");var me=require("fs/promises"),Fe=require("path");var DI="toloka-bootstrap",FV=`.claude/skills/${DI}/SKILL.md`,HV=`.cursor/rules/${DI}.mdc`,$i="AGENTS.md",xO=[FV,HV,$i],ir={begin:"<toloka>",end:"</toloka>"},JI={begin:"<!-- toloka:begin -->",end:"<!-- toloka:end -->"},jI=/<!-- toloka:sdk-version ([^\s>]+) -->/u,vV=["toloka-build","toloka-pipeline-as-code"].flatMap((e)=>[{file:`.claude/skills/${e}/SKILL.md`,directory:`.claude/skills/${e}`},{file:`.cursor/rules/${e}.mdc`}]),nr=async(e)=>{try{return await me.readFile(e,"utf8")}catch(t){if(Ua(t))return;throw t}},zI=async(e)=>{try{return(await me.lstat(e)).isDirectory()}catch(t){if(Ua(t))return!1;throw t}},_I=(e)=>jI.test(e),kV=`Generated by \`${We}\` version \`${ae}\`.
|
|
@@ -411,7 +411,7 @@ ${i}${n}`},oB=async(e,t,i)=>{let n=await e.trainings.getRunMetrics({trainingRunI
|
|
|
411
411
|
|
|
412
412
|
`),IB=async({sourceRoot:e,names:t,json:i,io:n,describe:r})=>{let o=await r({resolveFrom:e,...t.length===0?{}:{names:[...t]}});if(i){n.stdout(JSON.stringify(o,void 0,2));return}n.stdout(t.length===0?pU(o):AU(o))};var uB=(e,t)=>{let{context:i,globals:n}=t;e.command("ui").description("inspect the Task UI components the launcher renders").command("components").argument("[names...]","component names such as Field.RadioGroup; omit to list every component").option("--json","print the component contracts as JSON",!1).description("list Task UI components, or print the props, value shape, and example of the named ones").action(async(o,s)=>{let a=await Ie(n(),i.io);await IB({sourceRoot:a,names:o,json:s.json,io:i.io,describe:i.taskUiComponents??cB})})};var mB=require("crypto");var bU=600000,fU=new Set(["awaiting_confirmation","blocked","completed","failed","canceled"]),hU=(e)=>new Promise((t)=>{setTimeout(t,e)}),Ho=(e)=>_([["ID",e.id],["Status",e.status],["Dataset",e.datasetId],["Model",e.model.type==="base_model"?e.model.baseModelId:e.model.modelVersionId],["Output",e.output.type==="field"?`field ${e.output.fieldId} on dataset ${e.output.datasetId}`:`new dataset ${e.output.datasetId}`],...e.quote?[["Rows",String(e.quote.requests)],["Skipped rows",String(e.quote.skippedRows)],["Maximum charge",`$${e.quote.maximumCharge}`],...e.quote.confirmBefore?[["Confirm before",e.quote.confirmBefore]]:[]]:[],...e.progress?.requests?[["Progress",`${e.progress.requests.done}/${e.progress.requests.total} rows`]]:[],...e.chargedAmount?[["Charged",`$${e.chargedAmount}`]]:[],...e.result?[["Written",String(e.result.written)],["Failed",String(e.result.failed)],["Cut at max tokens",String(e.result.truncated)],["Tokens",`${e.result.inputTokens} in, ${e.result.outputTokens} out`]]:[],...e.message?[["Message",e.message]]:[]]),CB=async(e,t,i,n,r)=>{let o=Date.now()+r;for(;;){let s=await e.batchInference.getRun({batchInferenceRunId:t});if(i(s))return s;A(Date.now()<o,`Batch Inference Run ${s.id} is still ${s.status}.`,{hint:{description:`Check it later with toloka batch-inference status ${s.id}.`}}),await hU(n)}},ZU=async(e,t)=>{A(t.splitColumn===void 0||t.parts!==void 0,"--split-column needs --parts.",{hint:{description:"Pass --parts test to answer the rows of the test part."}});let i={...t.filter!==void 0&&await Dn(e,{datasetId:t.datasetId,name:t.datasetId,nameIsUnique:!1},[t.filter]),...t.slice!==void 0&&{slice:{sliceId:t.slice}},...t.parts!==void 0&&{parts:await Py(e,t.datasetId,{splitColumn:t.splitColumn,parts:t.parts})}};return Object.keys(i).length>0?i:void 0},pB=async(e,t,i)=>{A(t.baseModel===void 0!==(t.modelVersion===void 0),"Pass exactly one of --base-model or --model-version.",{hint:{description:"Run toloka base-model list or toloka model versions <model> to pick one."}}),A(t.outputField===void 0!==(t.outputDataset===void 0),"Pass exactly one of --output-field or --output-dataset.",{hint:{description:"--output-field writes a column on the dataset; --output-dataset creates a new dataset with the prompts and answers."}});let n=await ZU(e,t),r=t.baseModel?{type:"base_model",baseModelId:t.baseModel}:{type:"model_version",modelVersionId:(await dI(e,t.projectId,t.modelVersion)).id},o=await e.batchInference.createRun({projectId:t.projectId,idempotencyKey:t.idempotencyKey??mB.randomUUID(),datasetId:t.datasetId,...n&&{itemFilter:n},model:r,sampling:{maxOutputTokens:t.maxOutputTokens,...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP},...t.stop.length>0&&{stop:t.stop},...t.seed!==void 0&&{seed:t.seed},...t.samplesPerRow!==void 0&&{samplesPerRow:t.samplesPerRow}},output:t.outputField===void 0?{type:"dataset",name:t.outputDataset}:{type:"field",fieldName:t.outputField}}),s=await CB(e,o.id,(l)=>l.status!=="preparing",t.pollIntervalMs??1000,bU);if(A(s.status==="awaiting_confirmation",Ho(s),{hint:{description:"Fix the selection or the model, then start a new run."}}),!t.yes){z(i,t.json,s,`${Ho(s)}
|
|
413
413
|
|
|
414
|
-
Confirm the maximum charge with: toloka batch-inference confirm ${s.id}`);return}let a=await e.batchInference.confirmRun({batchInferenceRunId:s.id});z(i,t.json,a,Ho(a))},AB=async(e,t,i)=>{let n=await e.batchInference.listRunsPage({projectId:t.projectId,limit:100,offset:0});z(i,t.json,n.batchInferenceRuns,n.batchInferenceRuns.length===0?"No Batch Inference Runs found.":_([["ID","STATUS","DATASET","MAXIMUM CHARGE","CHARGED"],...n.batchInferenceRuns.map((r)=>[r.id,r.status,r.datasetId,r.quote?`$${r.quote.maximumCharge}`:"-",r.chargedAmount?`$${r.chargedAmount}`:"-"])]))},bB=async(e,t,i)=>{let n=t.wait?await CB(e,t.batchInferenceRunId,(r)=>fU.has(r.status),t.pollIntervalMs??5000,Number.POSITIVE_INFINITY):await e.batchInference.getRun({batchInferenceRunId:t.batchInferenceRunId});z(i,t.json,n,Ho(n))},fB=async(e,t,i)=>{let n={batchInferenceRunId:t.batchInferenceRunId},r=t.action==="confirm"?await e.batchInference.confirmRun(n):t.action==="cancel"?await e.batchInference.cancelRun(n):await e.batchInference.resumeRun(n);z(i,t.json,r,Ho(r))};var hB=(e,t)=>{let{context:i,globals:n}=t,r=e.command("batch-inference").description("answer dataset rows with a base model or Model Version");r.command("run").requiredOption("--dataset <id>","Dataset whose chat messages are the prompts").option("--filter <field=value>","only rows whose field equals the value").option("--slice <id>","only rows of this ready Dataset Slice, with the prompts it froze").option("--parts <names>","only rows in these split parts, comma-separated, for example test",Io).option("--split-column <name-or-id>","split column that --parts names, when the dataset has more than one").option("--base-model <id>","catalog Base Model that answers",ci).option("--model-version <id>","Model Version that answers: mdv.<id> or Model@name").option("--output-field <name>","text column on the dataset that receives the answers").option("--output-dataset <name>","new dataset that receives the prompts and answers").requiredOption("--max-output-tokens <count>","token limit per answer, at most 8192",ge).option("--temperature <value>","sampling temperature from 0 to 2 (default 0)",mZ).option("--top-p <value>","nucleus sampling threshold above 0 and at most 1",CZ).option("--stop <text>","stop sequence; repeat for up to four",co,[]).option("--seed <number>","sampling seed",uZ).option("--samples-per-row <count>","answers per row, at most 16; above 1 needs --output-dataset and a temperature above 0",ge).option("--idempotency-key <key>","reuse the run of an earlier identical request").option("--yes","confirm the quoted maximum charge and start right away",!1).option("--json","print JSON",!1).description("quote a Batch Inference Run, then confirm it to start").action(async(o)=>{let{client:s,projectId:a}=await R(n(),i);S(a);let{dataset:l,...g}=o;await pB(s,{...g,projectId:a,datasetId:l},i.io)}),r.command("list").option("--json","print JSON",!1).description("list the selected project's Batch Inference Runs").action(async(o)=>{let{client:s,projectId:a}=await R(n(),i);S(a),await AB(s,{projectId:a,json:o.json},i.io)}),r.command("status").argument("<batch-inference-run-id>","Batch Inference Run ID").option("--wait","wait until the run finishes or needs you",!1).option("--json","print JSON",!1).description("show one Batch Inference Run").action(async(o,s)=>{let{client:a}=await R(n(),i);await bB(a,{batchInferenceRunId:o,...s},i.io)});for(let[o,s]of[["confirm","accept the quoted maximum charge and start the run"],["resume","resume a run blocked on funds or payment"],["cancel","cancel a run; answers already generated are kept and the GPU time used is charged"]])r.command(o).argument("<batch-inference-run-id>","Batch Inference Run ID").option("--json","print JSON",!1).description(s).action(async(a,l)=>{let{client:g}=await R(n(),i);await fB(g,{batchInferenceRunId:a,action:o,json:l.json},i.io)})};var ZB=require("fs"),yB=require("os"),Se=require("path");var yU=`${Se.sep}install${Se.sep}global${Se.sep}`,za=(e)=>{try{return ZB.realpathSync(e)}catch{return e}},WU=(e,t,i,n)=>{if(za(e).includes(yU))return"global-registry";if(za(n)===t)return"linked";if(Se.dirname(Se.resolve(e))===Se.resolve(i))return"linked";return"project-local"},WB=(e=process.argv[1],t={})=>{if(t.native??Wi())return{version:ae,commit:"
|
|
414
|
+
Confirm the maximum charge with: toloka batch-inference confirm ${s.id}`);return}let a=await e.batchInference.confirmRun({batchInferenceRunId:s.id});z(i,t.json,a,Ho(a))},AB=async(e,t,i)=>{let n=await e.batchInference.listRunsPage({projectId:t.projectId,limit:100,offset:0});z(i,t.json,n.batchInferenceRuns,n.batchInferenceRuns.length===0?"No Batch Inference Runs found.":_([["ID","STATUS","DATASET","MAXIMUM CHARGE","CHARGED"],...n.batchInferenceRuns.map((r)=>[r.id,r.status,r.datasetId,r.quote?`$${r.quote.maximumCharge}`:"-",r.chargedAmount?`$${r.chargedAmount}`:"-"])]))},bB=async(e,t,i)=>{let n=t.wait?await CB(e,t.batchInferenceRunId,(r)=>fU.has(r.status),t.pollIntervalMs??5000,Number.POSITIVE_INFINITY):await e.batchInference.getRun({batchInferenceRunId:t.batchInferenceRunId});z(i,t.json,n,Ho(n))},fB=async(e,t,i)=>{let n={batchInferenceRunId:t.batchInferenceRunId},r=t.action==="confirm"?await e.batchInference.confirmRun(n):t.action==="cancel"?await e.batchInference.cancelRun(n):await e.batchInference.resumeRun(n);z(i,t.json,r,Ho(r))};var hB=(e,t)=>{let{context:i,globals:n}=t,r=e.command("batch-inference").description("answer dataset rows with a base model or Model Version");r.command("run").requiredOption("--dataset <id>","Dataset whose chat messages are the prompts").option("--filter <field=value>","only rows whose field equals the value").option("--slice <id>","only rows of this ready Dataset Slice, with the prompts it froze").option("--parts <names>","only rows in these split parts, comma-separated, for example test",Io).option("--split-column <name-or-id>","split column that --parts names, when the dataset has more than one").option("--base-model <id>","catalog Base Model that answers",ci).option("--model-version <id>","Model Version that answers: mdv.<id> or Model@name").option("--output-field <name>","text column on the dataset that receives the answers").option("--output-dataset <name>","new dataset that receives the prompts and answers").requiredOption("--max-output-tokens <count>","token limit per answer, at most 8192",ge).option("--temperature <value>","sampling temperature from 0 to 2 (default 0)",mZ).option("--top-p <value>","nucleus sampling threshold above 0 and at most 1",CZ).option("--stop <text>","stop sequence; repeat for up to four",co,[]).option("--seed <number>","sampling seed",uZ).option("--samples-per-row <count>","answers per row, at most 16; above 1 needs --output-dataset and a temperature above 0",ge).option("--idempotency-key <key>","reuse the run of an earlier identical request").option("--yes","confirm the quoted maximum charge and start right away",!1).option("--json","print JSON",!1).description("quote a Batch Inference Run, then confirm it to start").action(async(o)=>{let{client:s,projectId:a}=await R(n(),i);S(a);let{dataset:l,...g}=o;await pB(s,{...g,projectId:a,datasetId:l},i.io)}),r.command("list").option("--json","print JSON",!1).description("list the selected project's Batch Inference Runs").action(async(o)=>{let{client:s,projectId:a}=await R(n(),i);S(a),await AB(s,{projectId:a,json:o.json},i.io)}),r.command("status").argument("<batch-inference-run-id>","Batch Inference Run ID").option("--wait","wait until the run finishes or needs you",!1).option("--json","print JSON",!1).description("show one Batch Inference Run").action(async(o,s)=>{let{client:a}=await R(n(),i);await bB(a,{batchInferenceRunId:o,...s},i.io)});for(let[o,s]of[["confirm","accept the quoted maximum charge and start the run"],["resume","resume a run blocked on funds or payment"],["cancel","cancel a run; answers already generated are kept and the GPU time used is charged"]])r.command(o).argument("<batch-inference-run-id>","Batch Inference Run ID").option("--json","print JSON",!1).description(s).action(async(a,l)=>{let{client:g}=await R(n(),i);await fB(g,{batchInferenceRunId:a,action:o,json:l.json},i.io)})};var ZB=require("fs"),yB=require("os"),Se=require("path");var yU=`${Se.sep}install${Se.sep}global${Se.sep}`,za=(e)=>{try{return ZB.realpathSync(e)}catch{return e}},WU=(e,t,i,n)=>{if(za(e).includes(yU))return"global-registry";if(za(n)===t)return"linked";if(Se.dirname(Se.resolve(e))===Se.resolve(i))return"linked";return"project-local"},WB=(e=process.argv[1],t={})=>{if(t.native??Wi())return{version:ae,commit:"7aada2f0e0f6",channel:"native",path:za(t.executablePath??process.execPath)};A(e,"CLI entry path is unavailable",{hint:k});let i=t.globalBinDirectory??Se.resolve(process.env.BUN_INSTALL??Se.join(yB.homedir(),".bun"),"bin"),n=t.globalPackageDirectory??Se.resolve(i,"..","install","global","node_modules","@toloka-platform","sdk"),r=Se.resolve(Se.dirname(za(e)),".."),o=WU(e,r,i,n);return{version:ae,commit:"7aada2f0e0f6",channel:o,...o==="linked"?{path:r}:{}}};var VB=(e,t)=>{e.command("version").option("--json","print version and build provenance as JSON",!1).description("print the current CLI version").action((i)=>t.context.io.stdout(i.json?JSON.stringify(WB()):ae))};var RB=require("readline/promises");var BB=()=>new H("Standard input closed before an API key was entered.",{hint:{description:"Run toloka login in an interactive terminal, or pipe the key with toloka login --api-key-stdin."}}),VU=async()=>{process.stdin.setEncoding("utf8");let e=[];for await(let t of process.stdin)e.push(String(t));return e.join("")},BU=async(e)=>{process.stdout.write(e);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let{promise:i,resolve:n,reject:r}=Promise.withResolvers(),o="",s=()=>{process.stdin.off("data",d),process.stdin.off("end",l),process.stdin.off("error",g),process.stdin.setRawMode(t),process.stdin.pause()},a=()=>{s(),process.stdout.write(`
|
|
415
415
|
`)},l=()=>{a(),r(BB())},g=(c)=>{a(),r(c)},d=(c)=>{for(let u of c){if(u==="\r"||u===`
|
|
416
416
|
`){a(),n(o);return}if(u==="\x03"||u==="\x04"){a(),r(u==="\x03"?new H("Canceled.",{hint:{disabled:!0}}):BB());return}if(u==="\x7F"||u==="\b"){if(o.length>0)o=o.slice(0,-1),process.stdout.write("\b \b");continue}o+=u,process.stdout.write("*")}};process.stdin.on("data",d),process.stdin.once("end",l),process.stdin.once("error",g);try{return await i}finally{s()}},RU=async(e,t={})=>{if(t.mask===!0)return BU(e);let i=RB.createInterface({input:process.stdin,output:process.stdout,terminal:!0});try{return await i.question(e)}finally{i.close()}},GU=(e,t)=>Ya({message:e,choices:t}),qI=()=>({stdout:(e)=>console.log(e),stderr:(e)=>console.error(e),readStdin:VU,style:wZ(process.env,process.stdout.isTTY),...process.stdin.isTTY?{prompt:RU,choose:GU,select:DW}:{}});function wU(e){let t=new qi("toloka"),i={value:0},n=!1;t.description("Build and operate Toloka pipeline projects from TypeScript source. The public API may change between minor versions before 1.0.").version(ae,"-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",`
|
|
417
417
|
${cZ}`).configureOutput({writeOut:(s)=>e.io.stdout(s.replace(/\n$/u,"")),writeErr:(s)=>e.io.stderr(s.replace(/\n$/u,""))}).exitOverride();let r=()=>t.opts(),o={context:e,exitCode:i,globals:r};return t.hook("postAction",async(s,a)=>{if(n)return;let l=[];for(let c=a;c!==null;c=c.parent)l.push(c.name());if(l.includes("init")||l.includes("help")||l.includes("report")||l.includes("url")||l.includes("version")||l.includes("config"))return;let g=await Ie(r(),e.io),d=await SV(g).catch(()=>{return});if(d===void 0)return;n=!0,e.io.stderr(d)}),VB(t,o),DZ(t,o),zZ(t,o),aV(t,o),Xy(t,o),WZ(t,o),Ey(t,o),EV(t,o),cV(t,o),My(t,o),aB(t,o),hB(t,o),xy(t,o),sV(t,o),TV(t,o),dV(t,o),GV(t,o),uB(t,o),{program:t,exitCode:i}}var FU=(e,t)=>{for(let i=0;i<t.length;i+=1){let n=t[i];if(n===void 0)return;if(n==="--")return t[i+1];if(!n.startsWith("-"))return n;let r=e.options.find((o)=>o.short===n||o.long===n);if(r!==void 0&&(r.required||r.optional)&&!n.includes("="))i+=1}return},HU=(e,t)=>{let i=FU(e,t);if(i===void 0||i==="help")return;return e.commands.some((r)=>r.name()===i||r.aliases().includes(i))?void 0:i},vU=async(e,t,i,n)=>{let r=HU(e,i);if(r!==void 0)return n.stderr(`error: unknown command '${r}'
|
package/dist/cli/toloka.js.jsc
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
d7f726420d48b48e7d4f4ce66a1a7044fc047f8992bed3bdcf80b3a096254669 toloka.js.jsc
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
fea1d1164e4e1373e1fa59d237fecbd76724a87f35c5fade4c74dafaf711a413 toloka.js
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toloka-platform/sdk",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Build, inspect, and operate Toloka pipeline projects as TypeScript source. The public API may change between minor versions before 1.0.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -77,6 +77,6 @@
|
|
|
77
77
|
"bun": ">=1.4.0"
|
|
78
78
|
},
|
|
79
79
|
"tolokaBuild": {
|
|
80
|
-
"commit": "
|
|
80
|
+
"commit": "7aada2f0e0f63c9f8dc17c6d4486bca906c62468"
|
|
81
81
|
}
|
|
82
82
|
}
|
package/skills/catalog.json
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
"testing",
|
|
12
12
|
"checks"
|
|
13
13
|
],
|
|
14
|
-
"version": "0.17.
|
|
15
|
-
"digest": "
|
|
14
|
+
"version": "0.17.2",
|
|
15
|
+
"digest": "d30e63074f5eb9e78a6a643da7d0bd88a3da02640da7d727f08bf9bb1d8c55d7",
|
|
16
16
|
"files": [
|
|
17
17
|
"SKILL.md",
|
|
18
18
|
"references/human-work.md",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"bug",
|
|
34
34
|
"report"
|
|
35
35
|
],
|
|
36
|
-
"version": "0.17.
|
|
36
|
+
"version": "0.17.2",
|
|
37
37
|
"digest": "70f0bd2c80b32f87896aeb27c363b8a2d37f40e22424f57fe1aad142e125ad67",
|
|
38
38
|
"files": [
|
|
39
39
|
"SKILL.md",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"getting-started",
|
|
51
51
|
"agent"
|
|
52
52
|
],
|
|
53
|
-
"version": "0.17.
|
|
53
|
+
"version": "0.17.2",
|
|
54
54
|
"digest": "2278adeb46a792356579395fcf73c42322cb23bcd0c61e20856ccabdad6762d1",
|
|
55
55
|
"files": [
|
|
56
56
|
"SKILL.md"
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"sft",
|
|
68
68
|
"models"
|
|
69
69
|
],
|
|
70
|
-
"version": "0.17.
|
|
70
|
+
"version": "0.17.2",
|
|
71
71
|
"digest": "3ce10dee5d3c283d8b5fdea15134a58fc738c7af2c1bb19eb5a0bf70ea0bca13",
|
|
72
72
|
"files": [
|
|
73
73
|
"SKILL.md"
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"prompt",
|
|
85
85
|
"models"
|
|
86
86
|
],
|
|
87
|
-
"version": "0.17.
|
|
87
|
+
"version": "0.17.2",
|
|
88
88
|
"digest": "be8bce8d9cf7241ccb60d2b2a9b7cc07d7755a76e8ff8ec1b0847c49efbb3469",
|
|
89
89
|
"files": [
|
|
90
90
|
"SKILL.md"
|
|
@@ -49,7 +49,7 @@ Write at least one criterion for every output entity. Each criterion needs an au
|
|
|
49
49
|
|
|
50
50
|
Use `llmQaInstruction` only when the evaluator needs a specific verification method, authoritative source, tool, or pinned edge case beyond the thresholds. It is evaluator guidance, not labeler guidance, and has no effect in `human_only` mode.
|
|
51
51
|
|
|
52
|
-
Default QA is `qualityAssurance: { qaMode: 'llm_only' }`. Keep it when it fits the task. `hybrid` adds sampled Human QA while retaining LLM review; `human_only` is appropriate when LLM grading is prohibited or human review alone is required. Recommend a mode based on the user's quality and privacy requirements, explaining cost and turnaround implications before changing it. Human-bearing modes require `humanQaTimeForTask` in whole seconds: at least 30 and at least 3 per quality criterion of the node, whichever is larger, and at most 359,999 (99:59:59). A reviewer keeps a Human QA task for `humanQaTimeForTask` plus 1 hour, and for at least 8 hours. A dropped task stays with that reviewer until this time ends, then another reviewer can take it; `smartSamplingPercent` defaults to 30 for hybrid and 100 for human-only. Use those defaults unless the task justifies a different rate. Human QA on a node is capped at the
|
|
52
|
+
Default QA is `qualityAssurance: { qaMode: 'llm_only' }`. Keep it when it fits the task. `hybrid` adds sampled Human QA while retaining LLM review; `human_only` is appropriate when LLM grading is prohibited or human review alone is required. Recommend a mode based on the user's quality and privacy requirements, explaining cost and turnaround implications before changing it. Human-bearing modes require `humanQaTimeForTask` in whole seconds: at least 30 and at least 3 per quality criterion of the node, whichever is larger, and at most 359,999 (99:59:59). A reviewer keeps a Human QA task for `humanQaTimeForTask` plus 1 hour, and for at least 8 hours. A dropped task stays with that reviewer until this time ends, then another reviewer can take it; `smartSamplingPercent` defaults to 30 for hybrid and 100 for human-only. Use those defaults unless the task justifies a different rate. Human QA on a node is capped at the Maximum of its Human QA line in the frozen estimate: 3 reviews for each item of the run. The cap counts every item of the run, so a branch behind a `match` that receives more than its even share still gets Human QA. Before deploy, the platform counts the QA pool: experts who match the node's audience and hold the platform QA qualification and were active in the last 14 days, or have recent QA experience (at least 1 completed QA task and a recent visit; Smart Search invites these at deploy, except on a node that reuses an earlier audience or keeps its workforce request closed). The data is rebuilt once a day. With none, validation returns a blocking error and the deploy is rejected. The reviewers come from the node's own audience, because a node has no separate reviewer audience. So for that error, offer to widen the audience (drop specializations first, then countries) or to switch to `llm_only`; do not suggest waiting, because the count is refreshed once a day and nothing shows whether more reviewers will become active. When the count is too small for the node's expected reviews (the platform assumes that 1 of 10 of these experts reviews, for up to 12 hours each), `toloka validate` returns a `severity: 'warning'` issue on the node whose message starts with `Human QA on "<node name>" may stall`. The warning does not block the deploy. Tell the user the numbers in the message and offer its remedies: widen the audience or switch to `llm_only` (or to `hybrid` when the node is `human_only`); change none of them without the user's approval. A node that reuses the human reviewers of an earlier deployment skips this count. QA mode applies to the whole node, not individual criteria. The redo cap is platform-controlled and is not an SDK setting.
|
|
53
53
|
|
|
54
54
|
The platform also writes annotator fields on human-expert generation nodes. `<snake_cased node name>_annotator_id` is an optional string: the ID of the expert whose answer was accepted, not of earlier rejected attempts. `<snake_cased node name>_qa_annotator_id` exists only in `human_only` and `hybrid` modes: the ID of the expert who made the last human review decision, missing when sampling skipped human review. Both are missing on canceled items and on items completed before they existed; synthetic nodes have neither. The platform also writes one `*_evaluation_result` field per quality criterion with LLM or Human QA verdicts, `<snake_cased node name>_qa_metadata`, and, on a synthetic node with LLM QA, `<snake_cased node name>_evaluation_summary`. Never declare any of these with `field()`: the platform owns them, and an authored field with that name collides with it. Read them from the dataset with `toloka dataset load`.
|
|
55
55
|
|
|
@@ -108,9 +108,9 @@ Configure entities for one labeler's contribution, not for the outer array. A si
|
|
|
108
108
|
|
|
109
109
|
When a quorum output entity is `optional: true`, its outer field's `items` schema must also accept `null`, for example `{ type: 'array', items: { type: ['string', 'null'] } }`. The platform reserves a null annotation slot when that labeler omits the value and rejects an optional entity backed by non-nullable items.
|
|
110
110
|
|
|
111
|
-
Quorum does not aggregate. It writes all raw annotations back, including rejected
|
|
111
|
+
Quorum does not aggregate. It writes all raw annotations back, including ones that LLM QA rejected. Only an annotation that the platform's anti-fraud screening rejects is dropped. Add a downstream `code` node when the requested deliverable needs one consensus value, and make it tolerate arrays longer than `overlap`.
|
|
112
112
|
|
|
113
|
-
The platform also writes an annotator field, `<snake_cased node name>_annotator_ids`, on every quorum node in both QA modes. It is an optional array of annotator ID strings, one per
|
|
113
|
+
The platform also writes an annotator field, `<snake_cased node name>_annotator_ids`, on every quorum node in both QA modes. It is an optional array of annotator ID strings, one per annotation in the output arrays, aligned by position with every output array and every `*_evaluation_result` array. Annotations that LLM QA rejects keep their positions, and the verdicts at the same position show the review outcome. An annotation that the anti-fraud screening rejects leaves every array together with its annotator ID, and a replacement annotation is added at the end unless the item is canceled first. One labeler can hold more than one position. The field is missing on items completed before it existed and on canceled items with no annotations; a canceled item with some annotations carries their IDs. Never declare it with `field()`: the platform owns it, and an authored field with that name collides with it. Read it from the dataset with `toloka dataset load`.
|
|
114
114
|
|
|
115
115
|
#### Explanation-driven quality
|
|
116
116
|
|
|
@@ -122,7 +122,7 @@ With `qaMode: 'none'`, no LLM reads the explanation. Do not require an explanati
|
|
|
122
122
|
|
|
123
123
|
Default to `qualityAssurance: { qaMode: 'llm_only' }`. The LLM accepts or rejects each annotation. If all initial annotations are rejected, the platform adds fresh annotations one at a time until one is accepted or the total reaches `2 × overlap`. Therefore result arrays may be longer than `overlap`.
|
|
124
124
|
|
|
125
|
-
**Quorum has no redo cycle.** A rejected annotation is never reopened or sent back to the same expert. Escalation adds a fresh annotation, and
|
|
125
|
+
**Quorum has no redo cycle.** A rejected annotation is never reopened or sent back to the same expert. Escalation adds a fresh annotation, and every annotation that LLM QA accepted or rejected remains in the output arrays. Hitting the cap with zero accepted annotations still returns the collected results.
|
|
126
126
|
|
|
127
127
|
Use `qaMode: 'none'` when agreement-based quality control fits the task better than LLM grading, explaining the tradeoff before changing an existing QA strategy. This mode requires:
|
|
128
128
|
|
|
@@ -42,7 +42,7 @@ Run `toloka --help` and `toloka <command> --help` for the exact commands and opt
|
|
|
42
42
|
|
|
43
43
|
`toloka generation-model list` prints the synthetic generation models: `ID`, `NAME`, the supported `REASONING EFFORT` values with the default marked, and the `TYPICAL`, `MIN` and `MAX` cost of one attempt, followed by `Default model:` and, when there are any, `Recommended:` lines (`--json` adds descriptions). Run it before configuring a synthetic node.
|
|
44
44
|
|
|
45
|
-
`toloka pipeline cost [name] [--item-limit <n>]` forecasts what a run of a live, validated pipeline would bill. It does not start a run or change the graph. If any billed node is marked `skipped`, the displayed total is incomplete and must not be presented as the pipeline price. Compute and label a labor floor for each skipped billed node as `items × pricePerTask × annotations per item`, using `1` for generation and `overlap` for quorum. Also report `maxEntities`, quality-criteria count, and only exclusions applicable to the authored QA and workflow. Apply accepting a rate does not prove its final billed value.
|
|
45
|
+
`toloka pipeline cost [name] [--item-limit <n>]` forecasts what a run of a live, validated pipeline would bill. It does not start a run or change the graph. If any billed node is marked `skipped`, the displayed total is incomplete and must not be presented as the pipeline price. Compute and label a labor floor for each skipped billed node as `items × pricePerTask × annotations per item`, using `1` for generation and `overlap` for quorum. Also report `maxEntities`, quality-criteria count, and only exclusions applicable to the authored QA and workflow. Apply accepting a rate does not prove its final billed value.
|
|
46
46
|
|
|
47
47
|
## Manage model checkpoints
|
|
48
48
|
|
package/src/cli/cost.ts
CHANGED
|
@@ -56,10 +56,9 @@ const collectLineRows = (line: CostLine, depth: number): TableRow[] => {
|
|
|
56
56
|
|
|
57
57
|
const collectNodeRows = (
|
|
58
58
|
nodes: PipelineCostEstimate["nodes"],
|
|
59
|
-
): { billed: TableRow[]; unpriced: string[]
|
|
59
|
+
): { billed: TableRow[]; unpriced: string[] } => {
|
|
60
60
|
const billed: TableRow[] = [];
|
|
61
61
|
const unpriced: string[] = [];
|
|
62
|
-
const warnings: string[] = [];
|
|
63
62
|
|
|
64
63
|
for (const node of nodes) {
|
|
65
64
|
if (node.kind === "priced") {
|
|
@@ -67,7 +66,6 @@ const collectNodeRows = (
|
|
|
67
66
|
for (const line of node.displayBreakdown) {
|
|
68
67
|
if (isCostLine(line)) billed.push(...collectLineRows(line, 1));
|
|
69
68
|
}
|
|
70
|
-
if (node.warning !== undefined) warnings.push(` ${node.nodeNameDisplay}: ${node.warning}`);
|
|
71
69
|
continue;
|
|
72
70
|
}
|
|
73
71
|
|
|
@@ -78,7 +76,7 @@ const collectNodeRows = (
|
|
|
78
76
|
);
|
|
79
77
|
}
|
|
80
78
|
|
|
81
|
-
return { billed, unpriced
|
|
79
|
+
return { billed, unpriced };
|
|
82
80
|
};
|
|
83
81
|
|
|
84
82
|
const collectTotalRows = (total: PipelineCostEstimate["total"]): TableRow[] => {
|
|
@@ -102,7 +100,7 @@ export const formatCostEstimate = (
|
|
|
102
100
|
estimate: PipelineCostEstimate,
|
|
103
101
|
pipelineName: string,
|
|
104
102
|
): string => {
|
|
105
|
-
const { billed, unpriced
|
|
103
|
+
const { billed, unpriced } = collectNodeRows(estimate.nodes);
|
|
106
104
|
const totals = collectTotalRows(estimate.total);
|
|
107
105
|
const table = formatTable([["Item", "Expected", "Maximum"], ...billed, ...totals]);
|
|
108
106
|
const billedRows = table.slice(0, 1 + billed.length);
|
|
@@ -124,10 +122,6 @@ export const formatCostEstimate = (
|
|
|
124
122
|
output.push("", "Not billed", ...unpriced);
|
|
125
123
|
}
|
|
126
124
|
|
|
127
|
-
if (warnings.length > 0) {
|
|
128
|
-
output.push("", "Warnings", ...warnings);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
125
|
if (estimate.isInternalPricing === true) {
|
|
132
126
|
output.push("", "Internal-team pricing.");
|
|
133
127
|
}
|