apify-cli 1.6.3-beta.19 → 1.6.3-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as te,rmSync as w,statSync as T,unlinkSync as ne,writeFileSync as E}from"node:fs";import D,{basename as re,dirname as O,isAbsolute as ie,join as k,relative as ae,resolve as A,sep as j}from"node:path";import oe from"string-width";import se from"strip-ansi";import{once as ce}from"node:events";import{homedir as le,platform as ue}from"node:os";import de from"ci-info";import{ACTOR_ENV_VARS as M,ACTOR_JOB_STATUSES as N,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as P,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{createHmacSignature as Ce,cryptoRandomObjectId as we}from"@apify/utilities";import{execSync as Te,spawn as Ee}from"node:child_process";import{access as De,lstat as Oe,mkdir as F,readFile as I,readdir as L,rename as ke,rm as Ae,stat as R,symlink as je,unlink as Me,writeFile as z}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as B}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as V}from"apify-client";import{ZipArchive as He}from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as H,ok as nt,some as rt}from"@sapphire/result";import it from"configparser";import at from"@inquirer/input";import ot from"is-ci";import{execa as st}from"execa";import ct from"which";import{calculateRunDynamicMemory as lt}from"@apify/actor-memory-expression";import{Separator as ut,createPrompt as dt,isEnterKey as ft,makeTheme as pt,useKeypress as mt,usePrefix as ht,useState as gt}from"@inquirer/core";import{MemoryStorage as _t}from"@crawlee/memory-storage";import{compile as vt}from"json-schema-to-typescript";import{cloneDeep as yt}from"es-toolkit";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import Tt from"cli-table3";import{downloadTemplate as Et}from"giget";import Dt from"jju";import Ot from"open";import{fetchManifest as kt,manifestUrl as At,wrapperManifestUrl as jt}from"@apify/actor-templates";import Mt from"computer-name";import Nt from"cors";import Pt from"express";import Ft from"@inquirer/password";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.6.3-beta.19`,hash:`3ccf4d37cf5bf783700e54cb8e6b4d79edc30b03`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=O(process.execPath)),Ut}let Wt;function getMaxLineWidth(){if(Wt)return Wt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Wt=e;else if(!process.stdout.isTTY)Wt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Wt=e<1?80:e<40?40:e}return Wt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
1
+ import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as te,rmSync as w,statSync as T,unlinkSync as ne,writeFileSync as E}from"node:fs";import D,{basename as re,dirname as O,isAbsolute as ie,join as k,relative as ae,resolve as A,sep as j}from"node:path";import oe from"string-width";import se from"strip-ansi";import{once as ce}from"node:events";import{homedir as le,platform as ue}from"node:os";import de from"ci-info";import{ACTOR_ENV_VARS as M,ACTOR_JOB_STATUSES as N,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as P,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{createHmacSignature as Ce,cryptoRandomObjectId as we}from"@apify/utilities";import{execSync as Te,spawn as Ee}from"node:child_process";import{access as De,lstat as Oe,mkdir as F,readFile as I,readdir as L,rename as ke,rm as Ae,stat as R,symlink as je,unlink as Me,writeFile as z}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as B}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as V}from"apify-client";import{ZipArchive as He}from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as H,ok as nt,some as rt}from"@sapphire/result";import it from"configparser";import at from"@inquirer/input";import ot from"is-ci";import{execa as st}from"execa";import ct from"which";import{calculateRunDynamicMemory as lt}from"@apify/actor-memory-expression";import{Separator as ut,createPrompt as dt,isEnterKey as ft,makeTheme as pt,useKeypress as mt,usePrefix as ht,useState as gt}from"@inquirer/core";import{MemoryStorage as _t}from"@crawlee/memory-storage";import{compile as vt}from"json-schema-to-typescript";import{cloneDeep as yt}from"es-toolkit";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import Tt from"cli-table3";import{downloadTemplate as Et}from"giget";import Dt from"jju";import Ot from"open";import{fetchManifest as kt,manifestUrl as At,wrapperManifestUrl as jt}from"@apify/actor-templates";import Mt from"computer-name";import Nt from"cors";import Pt from"express";import Ft from"@inquirer/password";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.6.3-beta.20`,hash:`69d32fe6973896035dd0f51bf98da9bb5914292c`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=O(process.execPath)),Ut}let Wt;function getMaxLineWidth(){if(Wt)return Wt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Wt=e;else if(!process.stdout.isTTY)Wt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Wt=e<1?80:e<40?40:e}return Wt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
2
2
  `)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=n(i(this.command.description,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushExamples(e){let{examples:r}=this.command;if(r?.length){e.push(t.bold(`EXAMPLES`));for(let a of r){if(a.description){let r=n(i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
3
3
  `).map(e=>`# ${e}`).join(`
4
4
  `),2);e.push(t.dim(r))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=n(i(this.command.interactiveNote||`This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.`,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){oe(e.join(` `).split(`
@@ -82,41 +82,43 @@ just as if the command were run from that directory with no argument.`;static gr
82
82
  - If options.contentType is set, value is taken as is.`})};static flags={contentType:Y.string({char:`c`,description:`Specifies a custom MIME content type of the record. By default "application/json" is used.`,required:!1})};async run(){let{key:e,value:t}=this.args,{contentType:n=`application/json; charset=utf-8`}=this.flags,r=t||process.stdin,i=(await getApifyStorageClient()).keyValueStore(getDefaultStorageId(Yn.KEY_VALUE_STORE));r==null||r===``||r===`null`||r===`undefined`?await i.deleteRecord(e):await i.setRecord({key:e,value:r,contentType:n})}},ActorIndexCommand=class extends ApifyCommand{static name=`actor`;static description=`Runtime data operations intended to be called from inside a running Actor: read input, push data, get/set records in the default key-value store, charge pay-per-event, generate schema types.
83
83
 
84
84
  For platform-level management (deploy, list, call Actors), see 'apify actors' (plural).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actor`;static subcommands=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand];async run(){this.printHelp()}};function OverrideClassName(e){return e}const Zn=new Set(fe);function isTerminalStatus(e){return!!e&&Zn.has(e)}function exitCodeForJobStatus(e,t){switch(e){case`SUCCEEDED`:return 0;case`TIMED-OUT`:case`TIMING-OUT`:return 2;case`ABORTED`:case`ABORTING`:return 3;default:return 1}}function exitCodeForWaitResult(e,t){return e.timedOutWaiting?6:exitCodeForJobStatus(e.job.status,t)}async function waitForTerminalStatus(e){let{apifyClient:t,jobId:n,kind:r,pollIntervalMillis:i=2e3,maxWaitMillis:a}=e,s=Date.now();for(;;){let e=r===`build`?await t.build(n).get():await t.run(n).get();if(!e)throw Error(`${r===`build`?`Build`:`Run`} with ID "${n}" was not found.`);if(isTerminalStatus(e.status))return{job:e,timedOutWaiting:!1};if(a&&Date.now()-s>=a)return{job:e,timedOutWaiting:!0};let c=a?Math.min(i,a-(Date.now()-s)):i;await new Promise(e=>setTimeout(e,Math.max(0,c)))}}async function fetchLogTail(e,t,n=20){try{let r=await e.log(t).get();return r?r.split(`
85
- `).filter(e=>e.length>0).slice(-n):[]}catch{return[]}}function consoleRunUrl(e,t){return`https://console.apify.com/actors/${e}/runs/${t}`}function consoleBuildUrl(e,t){return`https://console.apify.com/actors/${e}#/builds/${t}`}function consoleDatasetUrl(e){return`https://console.apify.com/storage/datasets/${e}`}function statusColor(e){return e===`SUCCEEDED`?t.green(e):e===`RUNNING`||e===`READY`?t.blue(e):t.red(e)}function formatResultSummary(e){let n=[];n.push(`${t.bold(e.resultLabel)}: ${statusColor(e.overallStatus)}`),n.push(``);for(let t of e.lines)n.push(`${t.label}: ${t.value}`);if(e.links?.length){n.push(``);for(let r of e.links)n.push(`${r.label}: ${t.blue(r.url)}`)}if(e.errorReason?.length){n.push(``),n.push(t.red(`Reason:`));for(let t of e.errorReason)n.push(t)}return n.join(`
85
+ `).filter(e=>e.length>0).slice(-n):[]}catch{return[]}}function consoleRunUrl(e,t){return`https://console.apify.com/actors/${e}/runs/${t}`}function consoleBuildUrl(e,t){return`https://console.apify.com/actors/${e}#/builds/${t}`}function statusColor(e){return e===`SUCCEEDED`?t.green(e):e===`RUNNING`||e===`READY`?t.blue(e):t.red(e)}function formatResultSummary(e){let n=[];n.push(`${t.bold(e.resultLabel)}: ${statusColor(e.overallStatus)}`),n.push(``);for(let t of e.lines)n.push(`${t.label}: ${t.value}`);if(e.links?.length){n.push(``);for(let r of e.links)n.push(`${r.label}: ${t.blue(r.url)}`)}if(e.errorReason?.length){n.push(``),n.push(t.red(`Reason:`));for(let t of e.errorReason)n.push(t)}return n.join(`
86
86
  `)}async function resolveActorContext({providedActorNameOrId:t,client:n}){let r=await getLocalUserInfo(),i=r.username||r.id,a=getLocalConfig(e.cwd())||{};if(t?.includes(`/`)){let e=await n.actor(t).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let e=await n.actor(t).get();if(e)return{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id};let r=await n.actor(`${i}/${t.toLowerCase()}`).get();return r?{valid:!0,userFriendlyId:`${r.username}/${r.name}`,id:r.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(a.name){let e=await n.actor(`${i}/${a.name}`).get();return e?{valid:!0,userFriendlyId:`${e.username}/${e.name}`,id:e.id}:{valid:!1,reason:`Actor with name "${a.name}" was not found`}}return{valid:!1,reason:`Unable to detect what Actor to create a build for`}}function useSignalHandler({signals:e,handler:t,cleanTerminalLine:n=!0,once:r=!0}){let i=!1,wrapped=a=>{if(!i){if(r){i=!0;for(let t of e)process.off(t,wrapped)}n&&process.stderr.isTTY&&process.stderr.write(`\r\x1B[2K\x1B[0m`),cliDebugPrint(`useSignalHandler`,{event:`fired`,signal:a,once:r}),(async()=>{try{await t(a)}catch(e){cliDebugPrint(`useSignalHandler`,{event:`handler-threw`,signal:a,err:e})}})()}};for(let t of e)process.on(t,wrapped);return cliDebugPrint(`useSignalHandler`,{event:`registered`,signals:e,once:r}),{[Symbol.dispose](){if(!i){i=!0;for(let t of e)process.off(t,wrapped);cliDebugPrint(`useSignalHandler`,{event:`disposed`,signals:e})}}}}function useAbortJobOnSignal(e){let{apifyClient:n,silent:r=!1}=e,i=0;return useSignalHandler({signals:nn,once:!1,handler:async a=>{if(i+=1,e.kind===`build`){if(i>1)return;r||info({message:t.gray(`Received ${t.yellow(a)}, aborting build "${t.yellow(e.jobId)}" on the Apify platform...`),stdout:!0});try{await n.build(e.jobId).abort()}catch(t){error({message:`Failed to abort build "${e.jobId}": ${t.message}`,stdout:!0})}return}if(i>2)return;let s=i===1,c=`${e.runType.toLowerCase()} run`;if(!r){let n=s?`Received ${t.yellow(a)}, gracefully aborting ${c} "${t.yellow(e.jobId)}" on the Apify platform... ${t.dim(`(press Ctrl+C again to abort immediately)`)}`:`Received ${t.yellow(a)} again, aborting ${c} "${t.yellow(e.jobId)}" immediately...`;info({message:t.gray(n),stdout:!0})}try{await n.run(e.jobId).abort({gracefully:s})}catch(t){error({message:`Failed to abort run "${e.jobId}": ${t.message}`,stdout:!0})}}})}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function o(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function d(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}var BuildsCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new build of the Actor.`;static examples=[{description:`Build the Actor in the current directory with the default "latest" tag.`,command:`apify builds create`},{description:`Build a specific Actor with a custom tag and stream the build log.`,command:`apify builds create apify/hello-world --tag beta --log`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-create`;static flags={tag:Y.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:Y.string({description:`Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.`,required:!1}),log:Y.boolean({description:`Whether to print out the build log after the build is triggered.`}),wait:Y.boolean({description:`Wait for the build to reach a terminal status. Returns exit code 0 only when the build SUCCEEDED.`,default:!1})};static args={actorId:Z.string({description:`Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{tag:n,version:r,json:i,log:a,wait:s}=this.flags,{actorId:c}=this.args,l=await getLoggedClientOrThrow(),u=await resolveActorContext({providedActorNameOrId:c,client:l});if(!u.valid){error({message:`${u.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let f=await l.actor(u.id).get(),p=objectGroupBy(f.versions,e=>e.buildTag??`latest`)[n??`latest`],m=f.versions.find(e=>e.versionNumber===r),h,g=n;if(m){if(n&&(!p||!p.some(e=>e.versionNumber===r))){error({message:`The Actor Version "${r}" does not have the tag "${n}".`,stdout:!0});return}h=r,g=m.buildTag??`latest`}else if(p&&(h=p[0].versionNumber,g=n??`latest`,p.length>1&&!r)){error({message:`Multiple Actor versions with the tag "${n}" found. Please specify the version number using the "--version" flag.\n Available versions for this tag: ${p.map(e=>t.yellow(e.versionNumber)).join(`, `)}`,stdout:!0});return}if(!h){error({message:`No Actor versions with the tag "${n}" found. You can push a new version with this tag by using "apify push --build-tag=${n}".`,stdout:!0});return}let _=await l.actor(u.id).build(h,{tag:n}),v=`${f?.username?`${f.username}/`:``}${f?.name??`unknown-actor`}`,y=consoleBuildUrl(_.actId,_.buildNumber);if(a)try{var b=_usingCtx();b.u(useAbortJobOnSignal({apifyClient:l,kind:`build`,jobId:_.id}));try{await outputJobLog({job:_,apifyClient:l})}catch(e){error({message:`Failed to print log for build with ID "${_.id}": ${e.message}`,stdout:!0})}let t=await l.build(_.id).get();if(!t){error({message:`Could not refresh build status for build "${_.id}".`}),e.exitCode=1;return}_=t}catch(e){b.e=e}finally{b.d()}else if(s)try{var x=_usingCtx();x.u(useAbortJobOnSignal({apifyClient:l,kind:`build`,jobId:_.id}));let{job:e}=await waitForTerminalStatus({apifyClient:l,jobId:_.id,kind:`build`});_=e}catch(e){x.e=e}finally{x.d()}if(a||s){let t=_.status===`SUCCEEDED`,n=exitCodeForJobStatus(_.status,`build`),r=t?[]:await fetchLogTail(l,_.id);if(i){printJsonToStdout({ok:t,operation:`builds.create`,waited:!0,actor:{id:_.actId,name:v},build:{id:_.id,number:_.buildNumber,status:_.status,url:y},...t?{}:{error:{phase:`build`,message:`Actor build did not succeed`,logTail:r}},exitCode:n}),e.exitCode=n;return}simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:_.status,lines:[{label:`Build`,value:_.status},{label:`Build ID`,value:_.id},{label:`Build number`,value:_.buildNumber},{label:`Actor ID`,value:_.actId}],links:[{label:`Build URL`,url:y}],errorReason:t?void 0:r}),stdout:!0}),e.exitCode=n;return}if(i){printJsonToStdout({ok:!0,operation:`builds.create`,waited:!1,actor:{id:_.actId,name:v},build:{id:_.id,number:_.buildNumber,status:_.status,url:y},next:{wait:`apify builds wait ${_.id} --json`,log:`apify builds log ${_.id}`,info:`apify builds info ${_.id} --json`},exitCode:0});return}simpleLog({message:[`${t.yellow(`Actor`)}: ${v} (${t.gray(_.actId)})`,` ${t.yellow(`Version`)}: ${h} (tagged with ${t.yellow(g)})`,``,`${t.greenBright(`Build Started`)} (ID: ${t.gray(_.id)})`,` ${t.yellow(`Build Number`)}: ${_.buildNumber} (will get tagged once finished)`,` ${t.yellow(`Status`)}: ${_.status}`,` ${t.yellow(`Started`)}: ${G.display(_.startedAt)}`,``,`${t.blue(`View in Apify Console`)}: ${y}`,``,t.gray(`This command does not wait for the build to finish.`),``,`To wait for the final status:`,` apify builds wait ${_.id} --json`,``,`To inspect logs:`,` apify builds log ${_.id}`,``,`To inspect build metadata:`,` apify builds info ${_.id} --json`].join(`
87
87
  `),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(Je.getExtension(t.contentType)===`json`?(n=JSON.parse(t.body.toString(`utf8`)),r=`application/json`):(n=t.body,r=t.contentType))}return!n||!r?null:{inputToUse:n,contentType:r}}async function getInputOverride(t,n,r){let i,a;if(!n&&!r){let t=pn;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=n,a=`stdin`}catch(t){return error({message:`Cannot parse JSON input from standard input.\n ${t.message}`}),e.exitCode=5,!1}}if(n)switch(n[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),e.exitCode=5,!1;default:{let r=await De(A(t,n)).then(()=>!0).catch(()=>!1),s=n.endsWith(`.json`)||n.endsWith(`.json5`)||D.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.includes(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||s)return error({message:`Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead`}),e.exitCode=5,!1;try{let t=JSON.parse(n);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=`input`}catch(t){return error({message:`Cannot parse JSON input.\n ${t.message}`}),e.exitCode=5,!1}}}else if(r)switch(r[0]){case`-`:return error({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),e.exitCode=5,!1;default:{let n=A(t,r),s;try{let t=await I(n,`utf8`),s=JSON.parse(t);if(Array.isArray(s))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=s,a=r}catch(e){s=e}if(s)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:`The provided input is invalid. It should be an object, not an array.`}),e.exitCode=5,!1;i=t,a=r}catch{return error({message:`Cannot read input file at path "${n}".\n ${s.message}`}),e.exitCode=5,!1}}}return i?{input:i,source:a}:void 0}const Qn=[N.SUCCEEDED,N.ABORTED,N.FAILED,N.TIMED_OUT];async function*runActorOrTaskOnCloud(n,r){try{var i=_usingCtx();let a=e.cwd(),{actorOrTaskData:s,runOptions:c,type:l,waitForFinishMillis:u,inputOverride:f,silent:p,waitForRunToFinish:m,printRunLogs:h,suppressFinalStatus:g}=r,_=l===`Actor`?`actor`:`task`,v=resolveInput(a,f);p||(l===`Actor`?run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}):s.title?run({message:`Calling ${l} ${s.title} (${s.userFriendlyId}, ${t.gray(s.id)})\n`}):run({message:`Calling ${l} ${s.userFriendlyId} (${t.gray(s.id)})\n`}));let y;try{y=v&&l===`Actor`?await n[_](s.id).start(v.inputToUse,{...c,contentType:v.contentType}):await n[_](s.id).start(void 0,c)}catch(e){if(e.type===`record-not-found`)throw Error(`${l} ${s.userFriendlyId} (${s.id}) not found!`);if(e.type===`full-permission-actor-not-approved`){let n=e.data?.approvalUrl,r=[`${l} ${s.userFriendlyId} requires full access to your Apify account and has not been approved yet.`];throw n&&r.push(``,`Approve here: ${t.blue(n)}`),Error(r.join(`
88
- `))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:y.id,runType:l,silent:p})),yield y,!p&&h)try{await outputJobLog({job:y,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(y=await n.run(y.id).get(),m)for(;!Qn.includes(y.status)&&(y=await n.run(y.id).get(),!Qn.includes(y.status));)await new Promise(e=>{setTimeout(e,1e3)});g||(y.status===N.SUCCEEDED?p||success({message:`${l} finished.`}):y.status===N.RUNNING?p||warning({message:`${l} is still running!`}):y.status===N.ABORTED||y.status===N.ABORTING?(p||warning({message:`${l} was aborted!`}),e.exitCode=3):(p||error({message:`${l} failed!`}),e.exitCode=1)),yield y}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})});var $n=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
89
- Reads input from local key-value store by default.`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({char:`f`,description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]}),silent:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both the --json and --output-dataset flags when running this command.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=!1,h,g=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of g)if(h=e,!m&&(m=!0,!this.flags.silent)){let n=`https://console.apify.com/actors/${c}/runs/${e.id}`,r=[`${t.yellow(`Started`)}: ${G.display(e.startedAt)}`];e.containerUrl&&r.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let i=h.buildNumber.split(`.`).slice(0,2).join(`.`),a=u.versions.find(e=>e.versionNumber===i),s=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],l=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];s?l.push(`(${t.yellow(s)})`):l.push(`(${t.gray(`N/A`)})`),a&&l.push(`| ${t.gray(`Actor version:`)} ${t.cyan(a.versionNumber)} (${t.yellow(a.buildTag)})`),r.push(l.join(` `)),r.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),r.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),r.push(`${t.blue(`View on Apify Console`)}: ${n}`,``),simpleLog({message:r.join(`
90
- `),stdout:!this.flags.json})}if(!h){error({message:`Actor run did not start.`}),e.exitCode=1;return}let _=h,v=consoleRunUrl(c,_.id),y=consoleDatasetUrl(_.defaultDatasetId),b=_.status===`SUCCEEDED`,x=exitCodeForJobStatus(_.status,`run`),S=b?[]:await fetchLogTail(i,_.id);if(this.flags.json){printJsonToStdout({ok:b,operation:`call`,actor:{id:c,url:`https://console.apify.com/actors/${c}`},run:{id:_.id,status:_.status,exitCode:_.exitCode??null,url:v},storage:{defaultDatasetId:_.defaultDatasetId,defaultKeyValueStoreId:_.defaultKeyValueStoreId,datasetUrl:y},...b?{}:{error:{phase:`run`,message:`Actor run did not succeed`,logTail:S}},exitCode:x}),e.exitCode=x;return}if(this.flags.silent||simpleLog({message:formatResultSummary({resultLabel:`Apify call result`,overallStatus:_.status,lines:[{label:`Run`,value:_.status},{label:`Actor ID`,value:c},{label:`Run ID`,value:_.id},{label:`Build number`,value:_.buildNumber},...typeof _.exitCode==`number`?[{label:`Exit code`,value:String(_.exitCode)}]:[],{label:`Dataset ID`,value:_.defaultDatasetId},{label:`Key-value store ID`,value:_.defaultKeyValueStoreId}],links:[{label:`Run URL`,url:v},{label:`Dataset URL`,url:y}],errorReason:b?void 0:S}),stdout:!0}),e.exitCode=x,this.flags.outputDataset){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(V.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const er={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const tr=process.stdout.columns??100,nr=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=er[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===nr)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new Tt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return tr<100}};function formatEventPrice(e){return e===0?`$0.00`:e>=.01?`$${e.toFixed(2)}`:`$${Number(e.toPrecision(2))}`}const rr=`​​`,ir=new Q({allColumns:[`​`,rr],mandatoryColumns:[`​`,rr],columnAlignments:{"​":`left`,[rr]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=c.pricingInfos;if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=kn.format(n);u.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n){let n=e.eventPriceUsd,r=e.eventTieredPricingUsd,i;i=typeof n==`number`?formatEventPrice(n):r&&Object.keys(r).length>0?`from ${formatEventPrice(Math.min(...Object.values(r).map(e=>e.tieredEventPriceUsd)))} (tiered)`:`N/A`,ir.pushRow({"​":e.eventTitle,[rr]:t.bold(i)})}let r=ir.render(0).split(`
88
+ `))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:`run`,jobId:y.id,runType:l,silent:p})),yield y,!p&&h)try{await outputJobLog({job:y,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(y=await n.run(y.id).get(),m)for(;!Qn.includes(y.status)&&(y=await n.run(y.id).get(),!Qn.includes(y.status));)await new Promise(e=>{setTimeout(e,1e3)});g||(y.status===N.SUCCEEDED?p||success({message:`${l} finished.`}):y.status===N.RUNNING?p||warning({message:`${l} is still running!`}):y.status===N.ABORTED||y.status===N.ABORTING?(p||warning({message:`${l} was aborted!`}),e.exitCode=3):(p||error({message:`${l} failed!`}),e.exitCode=1)),yield y}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})}),$n={call:`Apify call`,"task-run":`Apify task run`},er=`https://console.apify.com`;function actorUrl(e){return`${er}/actors/${e}`}function runUrl(e,t){return`${er}/actors/${e}/runs/${t}`}function datasetUrl(e){return`${er}/storage/datasets/${e}`}function isSucceeded(e){return e.status===N.SUCCEEDED}function getRunExitCode(e){switch(e.status){case N.SUCCEEDED:return 0;case N.ABORTED:case N.ABORTING:return 3;case N.TIMED_OUT:case N.TIMING_OUT:return 2;default:return e.exitCode&&e.exitCode!==0?e.exitCode:1}}function genericReason(e){switch(e.status){case N.ABORTED:case N.ABORTING:return`Actor run was aborted`;case N.TIMED_OUT:case N.TIMING_OUT:return`Actor run timed out`;default:return`Actor run failed`}}async function fetchRunLogTail(e,t){if(isSucceeded(t))return[];let n;try{n=await e.log(t.id).get()}catch{return[]}return n?n.split(`
89
+ `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10):[]}function buildRunResultJson({run:e,operation:t,logTail:n}){let r=isSucceeded(e),i={ok:r,operation:t,actor:{id:e.actId,url:actorUrl(e.actId)},run:{id:e.id,status:e.status,url:runUrl(e.actId,e.id)},storage:{defaultDatasetId:e.defaultDatasetId,defaultKeyValueStoreId:e.defaultKeyValueStoreId,datasetUrl:datasetUrl(e.defaultDatasetId)},exitCode:getRunExitCode(e)};return r||(i.error={phase:`run`,message:e.statusMessage||genericReason(e),logTail:n}),i}function printRunResultSummary({run:e,operation:n,logTail:r}){let i=isSucceeded(e),a=i?t.green:t.red,s=[`${$n[n]} result: ${a(e.status)}`,``,`${t.yellow(`Run`)}: ${a(e.status)}`,`${t.yellow(`Actor ID`)}: ${e.actId}`,`${t.yellow(`Run ID`)}: ${e.id}`,`${t.yellow(`Build number`)}: ${e.buildNumber}`];!i&&e.exitCode!=null&&s.push(`${t.yellow(`Exit code`)}: ${e.exitCode}`),s.push(`${t.yellow(`Dataset ID`)}: ${e.defaultDatasetId}`,`${t.yellow(`Key-value store ID`)}: ${e.defaultKeyValueStoreId}`,``,`${t.blue(`Run URL`)}: ${runUrl(e.actId,e.id)}`,`${t.blue(`Dataset URL`)}: ${datasetUrl(e.defaultDatasetId)}`),i||s.push(``,`${t.yellow(`Reason`)}:`,e.statusMessage||genericReason(e),...r),simpleLog({message:s.join(`
90
+ `),stdout:!0})}async function finalizeRun({apifyClient:t,run:n,operation:r,json:i,silent:a}){if(e.exitCode=getRunExitCode(n),a)return;let s=await fetchRunLogTail(t,n);if(i){printJsonToStdout(buildRunResultJson({run:n,operation:r,logTail:s}));return}printRunResultSummary({run:n,operation:r,logTail:s})}var tr=class ActorsCallCommand extends ApifyCommand{static name=`call`;static description=`Executes Actor remotely using your authenticated account.
91
+ Reads input from local key-value store by default.`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({char:`f`,description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]}),silent:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both the --json and --output-dataset flags when running this command.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=!1,h,g=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of g)if(h=e,!m&&(m=!0,!this.flags.silent)){let n=runUrl(c,e.id),r=[`${t.yellow(`Started`)}: ${G.display(e.startedAt)}`];e.containerUrl&&r.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let i=h.buildNumber.split(`.`).slice(0,2).join(`.`),a=u.versions.find(e=>e.versionNumber===i),s=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],l=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];s?l.push(`(${t.yellow(s)})`):l.push(`(${t.gray(`N/A`)})`),a&&l.push(`| ${t.gray(`Actor version:`)} ${t.cyan(a.versionNumber)} (${t.yellow(a.buildTag)})`),r.push(l.join(` `)),r.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),r.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),r.push(`${t.blue(`View on Apify Console`)}: ${n}`,``),simpleLog({message:r.join(`
92
+ `),stdout:!this.flags.json})}if(await finalizeRun({apifyClient:i,run:h,operation:`call`,json:this.flags.json,silent:this.flags.silent}),!this.flags.json&&this.flags.outputDataset&&h.status===N.SUCCEEDED){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(V.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const nr={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const rr=process.stdout.columns??100,ir=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=nr[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===ir)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new Tt({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return rr<100}};function formatEventPrice(e){return e===0?`$0.00`:e>=.01?`$${e.toFixed(2)}`:`$${Number(e.toPrecision(2))}`}const ar=`​​`,or=new Q({allColumns:[`​`,ar],mandatoryColumns:[`​`,ar],columnAlignments:{"​":`left`,[ar]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}let l=c.taggedBuilds?.latest;if(n){if(!l){error({message:`No README found for this Actor.`,stdout:!0});return}if(!l.build?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.readme,stdout:!0});return}if(r){if(!l){error({message:`No input schema found for this Actor.`,stdout:!0});return}if(!l.build?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:l.build.inputSchema,stdout:!0});return}let u=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&u.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&u.push(`${t.yellow(`Description:`)} ${c.description}`),u.push(`${t.yellow(`Created at:`)} ${t.cyan(G.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(G.display(c.modifiedAt))}`),c.actorMaker&&(u.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(u[u.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?u.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):u.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&u.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let f=c.pricingInfos;if(f?.length){let e=f.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=kn.format(n);u.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n){let n=e.eventPriceUsd,r=e.eventTieredPricingUsd,i;i=typeof n==`number`?formatEventPrice(n):r&&Object.keys(r).length>0?`from ${formatEventPrice(Math.min(...Object.values(r).map(e=>e.tieredEventPriceUsd)))} (tiered)`:`N/A`,or.pushRow({"​":e.eventTitle,[ar]:t.bold(i)})}let r=or.render(0).split(`
91
93
  `);r.splice(1,1),u.push(r.join(`
92
94
  `));break}case`FREE`:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:{let n=e.pricingModel;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(n)})`)}`)}}}else u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);if((c.seoTitle||c.seoDescription)&&(u.push(``,t.yellow(`SEO information:`)),c.seoTitle&&u.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&u.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`)),c.taggedBuilds){u.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&u.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&u.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:u.join(`
93
- `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const ar={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},or=new Q({allColumns:[`Name`,`Runs`,`Last run started at`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run status`,`Last run duration`],columnAlignments:{Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},hiddenColumns:[`_Small_LastRunText`],breakpointOverrides:{small:{"Last run status":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}}),sr=new Q({allColumns:[`Name`,`Modified at`,`Builds`,`Default build`,`Runs`,`Last run`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run`,`Last run duration`],hiddenColumns:[`_Small_LastRunText`],columnAlignments:{Builds:`right`,Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},breakpointOverrides:{small:{"Last run":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}});var ActorsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints a list of recently executed Actors or Actors you own.`;static examples=[{description:`List Actors you recently interacted with.`,command:`apify actors ls`},{description:`List Actors you own, newest first.`,command:`apify actors ls --my --desc`},{description:`List the next page of 50 Actors.`,command:`apify actors ls --limit 50 --offset 50`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-ls`;static flags={my:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?sr:or,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?Dn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(ar[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Le.Week?n.push(`
95
+ `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const sr={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},cr=new Q({allColumns:[`Name`,`Runs`,`Last run started at`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run status`,`Last run duration`],columnAlignments:{Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},hiddenColumns:[`_Small_LastRunText`],breakpointOverrides:{small:{"Last run status":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}}),lr=new Q({allColumns:[`Name`,`Modified at`,`Builds`,`Default build`,`Runs`,`Last run`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run`,`Last run duration`],hiddenColumns:[`_Small_LastRunText`],columnAlignments:{Builds:`right`,Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},breakpointOverrides:{small:{"Last run":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}});var ActorsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints a list of recently executed Actors or Actors you own.`;static examples=[{description:`List Actors you recently interacted with.`,command:`apify actors ls`},{description:`List Actors you own, newest first.`,command:`apify actors ls --my --desc`},{description:`List the next page of 50 Actors.`,command:`apify actors ls --limit 50 --offset 50`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-ls`;static flags={my:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?lr:cr,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?Dn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(sr[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<Le.Week?n.push(`
94
96
  `,t.gray(`${K.format(r)} ago`)):n.push(`
95
- `,t.gray(`On`,On.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?nr:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":Dn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?nr:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await Ue.get(e,{responseType:`arraybuffer`}),r=new ze(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:k(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${O(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Dt.parse(e);n.name=f.name,E(`${g}/${t.name}`,Dt.update(e,n))}else E(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h;try{await Et(`git:${e}`,{dir:g})}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const cr=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>cr)throw Error(`Secret value has to be string with maximum length ${cr}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
97
+ `,t.gray(`On`,On.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?ir:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":Dn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?ir:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await Ue.get(e,{responseType:`arraybuffer`}),r=new ze(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:k(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${O(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Dt.parse(e);n.name=f.name,E(`${g}/${t.name}`,Dt.update(e,n))}else E(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h;try{await Et(`git:${e}`,{dir:g})}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const ur=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>ur)throw Error(`Secret value has to be string with maximum length ${ur}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
96
98
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
97
99
  If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},transformEnvToEnvVars=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r=[],i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r.push({name:n,value:t[a],isSecret:!0}):i.push(a)}else r.push({name:n,value:e[n]})}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
98
100
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
99
- If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},lr=`temp_file.zip`,ur={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case N.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case N.READY:return{resultLabel:`PENDING`,ok:!0};case N.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case N.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case N.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case N.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case N.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case N.FAILED:return{resultLabel:`FAILED`,exitCode:1,ok:!1,errorMessage:`Build failed`};default:return{resultLabel:`UNKNOWN`,exitCode:1,ok:!1,errorMessage:`Build finished with unexpected status "${e}"`}}}var ActorsPushCommand=class extends ApifyCommand{static name=`push`;static description=`Deploys Actor to Apify platform using settings from '${W}'.\nFiles under '${ve/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
101
+ If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},dr=`temp_file.zip`,fr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case N.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case N.READY:return{resultLabel:`PENDING`,ok:!0};case N.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case N.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case N.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case N.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case N.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case N.FAILED:return{resultLabel:`FAILED`,exitCode:1,ok:!1,errorMessage:`Build failed`};default:return{resultLabel:`UNKNOWN`,exitCode:1,ok:!1,errorMessage:`Build finished with unexpected status "${e}"`}}}var ActorsPushCommand=class extends ApifyCommand{static name=`push`;static description=`Deploys Actor to Apify platform using settings from '${W}'.\nFiles under '${ve/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
100
102
  Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
101
103
  Use --force to override newer remote versions.`;static group=`Local Actor Development`;static examples=[{description:`Deploy the current Actor to the Apify platform.`,command:`apify push`},{description:`Deploy to a specific Actor by ID, overriding newer remote versions.`,command:`apify push E2jjCZBezvAZnX8Rb --force`},{description:`Deploy without waiting for the build to finish.`,command:`apify push --no-wait-for-finish`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-push`;static enableJsonFlag=!0;static flags={version:Y.string({char:`v`,description:`Actor version number to which the files should be pushed. By default, it is taken from the '${W}' file.`,required:!1}),"build-tag":Y.string({char:`b`,description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${W}' file.`,required:!1}),"wait-for-finish":Y.string({char:`w`,description:`In seconds, how long to wait for the build to finish. If no value passed, it waits forever. To return as soon as the build is queued (fire-and-forget), pass 0. The exit code reflects the build outcome only — if the wait elapses with the build still running, the command exits 0; check status via the printed link or --json output.`,required:!1}),open:Y.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:Y.boolean({char:`f`,description:`Push an Actor even when the local files are older than the Actor on the platform.`,default:!1,required:!1}),dir:Y.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":Y.boolean({description:`Allow the command to continue even when secret values are not found in the local secrets storage.`,required:!1,default:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to push (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will create or modify the Actor with the name specified in '${W}' file.`})};async run(){try{var t=_usingCtx();let n=A(e.cwd(),this.flags.dir??`.`),r=await getActorLocalFilePaths(n);if(!r.length){error({message:`You need to call this command from a folder that has an Actor in it!`}),e.exitCode=4;return}if(![`apify.json`,`actor.json`,`.actor/actor.json`,`.actor`].some(e=>r.some(t=>t===e||t.startsWith(e)))){error({message:[`A valid Actor could not be found in the current directory. Please make sure you are in the correct directory.`,"You can also turn this directory into an Actor by running `apify init`."].join(`
102
- `)}),e.exitCode=4;return}let i=await getLoggedClientOrThrow(),a=await useActorConfig({cwd:n});if(a.isErr()){error({message:a.unwrapErr().message}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=await getLocalUserInfo(),l=c.organizationOwnerUserId?`/organization/${c.id}`:``,u,f,p=!1,m=this.flags.version||s?.version||`0.0`,h=this.flags.buildTag||s?.buildTag;!h&&m===`0.0`&&(h=`latest`);let g=parseWaitForFinishMillis(this.flags.waitForFinish),_=this.args.actorId;if(_){if(f=await i.actor(_).get(),!f)throw Error(`Cannot find Actor with ID '${_}' in your account.`);u=f.id}else{let e=c.username||c.id;if(f=await i.actor(`${e}/${s.name}`).get(),f)u=f.id;else{let{templates:e}=await kt(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||ur,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:m,buildTag:h,sourceType:me.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),f=await i.actors().create(n),u=f.id,p=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:u,wasCreated:p};let v=i.actor(u);info({message:`Deploying Actor '${s.name}' to Apify.`});let y=await sumFilesSizeInBytes(r,n),b,x,C;if(y<ve){let e=await v.get();if(!p){let t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=T(k(n,t)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&t<i&&(s?.name||_))throw Error(`Actor with identifier "${s?.name||_}" is already on the platform and was modified there since modified locally.
103
- Skipping push. Use --force to override.`)}x=await createSourceFiles(r,n),b=me.SOURCE_FILES}else{run({message:`Zipping Actor files`}),await createActZip(lr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${u}-source`),t=`version-${m}.zip`,a=S(lr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),ne(lr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Ce(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}C=s.toString(),b=me.TARBALL}let ee=await v.version(m).get(),te=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(ee){let e={tarballUrl:C,sourceFiles:x,buildTag:h,sourceType:b,envVars:te};await v.version(m).update(e),run({message:`Updated version ${m} for Actor ${f.name}.`})}else{let e={versionNumber:m,tarballUrl:C,sourceFiles:x,buildTag:h,sourceType:b,envVars:te};await v.versions().create({...e}),run({message:`Created version ${m} for Actor ${f.name}.`})}if(!p&&!!s.usesStandbyMode!=!!f.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await v.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${f.name}.`})}run({message:`Building Actor ${f.name}`});let w=g===void 0?1/0:Date.now()+g,E=await v.build(m,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:E.id}));try{let e=Number.isFinite(w)?Math.max(0,w-Date.now()):void 0;await outputJobLog({job:E,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let D=await i.build(E.id).get();if(!D){error({message:`Could not fetch build with ID "${E.id}" after deployment.`}),e.exitCode=1;return}for(E=D;!fe.includes(E.status)&&Date.now()<w;)await new Promise(e=>setTimeout(e,1e3)),E=await i.build(E.id).get();if(E.status===N.SUCCEEDED&&h&&g!==0){run({message:`Applying build tag "${h}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await v.get())?.taggedBuilds?.[h]?.buildId===E.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${h}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let re=E.status,O=resolvePushOutcome(re),ie=`https://console.apify.com${l}/actors/${E.actId}`,ae=`${ie}#/builds/${E.buildNumber}`,j=[];if(O.errorMessage)try{let e=await i.log(E.id).get();e&&(j=e.split(`
104
+ `)}),e.exitCode=4;return}let i=await getLoggedClientOrThrow(),a=await useActorConfig({cwd:n});if(a.isErr()){error({message:a.unwrapErr().message}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=await getLocalUserInfo(),l=c.organizationOwnerUserId?`/organization/${c.id}`:``,u,f,p=!1,m=this.flags.version||s?.version||`0.0`,h=this.flags.buildTag||s?.buildTag;!h&&m===`0.0`&&(h=`latest`);let g=parseWaitForFinishMillis(this.flags.waitForFinish),_=this.args.actorId;if(_){if(f=await i.actor(_).get(),!f)throw Error(`Cannot find Actor with ID '${_}' in your account.`);u=f.id}else{let e=c.username||c.id;if(f=await i.actor(`${e}/${s.name}`).get(),f)u=f.id;else{let{templates:e}=await kt(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||fr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:m,buildTag:h,sourceType:me.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),f=await i.actors().create(n),u=f.id,p=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:u,wasCreated:p};let v=i.actor(u);info({message:`Deploying Actor '${s.name}' to Apify.`});let y=await sumFilesSizeInBytes(r,n),b,x,C;if(y<ve){let e=await v.get();if(!p){let t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=T(k(n,t)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&t<i&&(s?.name||_))throw Error(`Actor with identifier "${s?.name||_}" is already on the platform and was modified there since modified locally.
105
+ Skipping push. Use --force to override.`)}x=await createSourceFiles(r,n),b=me.SOURCE_FILES}else{run({message:`Zipping Actor files`}),await createActZip(dr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${u}-source`),t=`version-${m}.zip`,a=S(dr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),ne(dr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Ce(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}C=s.toString(),b=me.TARBALL}let ee=await v.version(m).get(),te=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(ee){let e={tarballUrl:C,sourceFiles:x,buildTag:h,sourceType:b,envVars:te};await v.version(m).update(e),run({message:`Updated version ${m} for Actor ${f.name}.`})}else{let e={versionNumber:m,tarballUrl:C,sourceFiles:x,buildTag:h,sourceType:b,envVars:te};await v.versions().create({...e}),run({message:`Created version ${m} for Actor ${f.name}.`})}if(!p&&!!s.usesStandbyMode!=!!f.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await v.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${f.name}.`})}run({message:`Building Actor ${f.name}`});let w=g===void 0?1/0:Date.now()+g,E=await v.build(m,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:E.id}));try{let e=Number.isFinite(w)?Math.max(0,w-Date.now()):void 0;await outputJobLog({job:E,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let D=await i.build(E.id).get();if(!D){error({message:`Could not fetch build with ID "${E.id}" after deployment.`}),e.exitCode=1;return}for(E=D;!fe.includes(E.status)&&Date.now()<w;)await new Promise(e=>setTimeout(e,1e3)),E=await i.build(E.id).get();if(E.status===N.SUCCEEDED&&h&&g!==0){run({message:`Applying build tag "${h}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await v.get())?.taggedBuilds?.[h]?.buildId===E.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${h}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let re=E.status,O=resolvePushOutcome(re),ie=`https://console.apify.com${l}/actors/${E.actId}`,ae=`${ie}#/builds/${E.buildNumber}`,j=[];if(O.errorMessage)try{let e=await i.log(E.id).get();e&&(j=e.split(`
104
106
  `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}O.exitCode&&(e.exitCode=O.exitCode);let oe={ok:O.ok,operation:`push`,actor:{id:E.actId,url:ie},build:{id:E.id,number:E.buildNumber,status:re,url:ae}};if(O.exitCode!==void 0&&(oe.exitCode=O.exitCode),O.errorMessage&&(oe.error={phase:`build`,message:O.errorMessage,logTail:j}),this.flags.json){printJsonToStdout(oe);return}simpleLog({stdout:!0,message:[`Apify push result: ${O.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${re}`,`Actor ID: ${E.actId}`,`Build ID: ${E.id}`,`Build number: ${E.buildNumber}`,...O.exitCode?[`Exit code: ${O.exitCode}`]:[],``,`Actor URL: ${ie}`,`Build URL: ${ae}`,...O.errorMessage&&j.length?[``,`Reason:`,...j]:[]].join(`
105
- `)}),this.flags.open&&await Ot(ie)}catch(e){t.e=e}finally{t.d()}}},ActorsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes an Actor from your account.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete an Actor by its full name (prompts for confirmation).`,command:`apify actors rm my-username/my-actor`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-rm`;static args={actorId:Z.string({description:`The Actor ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow();if(!await n.actor(e).get()){error({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await X({message:`Are you sure you want to delete this Actor?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of Actor "${e}" was canceled.`});return}try{await n.actor(e).delete(),success({message:`Actor with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete Actor "${e}".\n ${n.message||n}`})}}};const dr={FREE:`Free`,FLAT_PRICE_PER_MONTH:`Subscription`,PRICE_PER_DATASET_ITEM:`Pay per result`,PAY_PER_EVENT:`Pay per event`};function formatPricingModel(e){return e?dr[e]??e:t.gray(`Unknown`)}function truncateDescription(e,t=60){return e?e.length<=t?e:`${e.slice(0,t-1)}…`:``}var ActorsSearchCommand=class extends ApifyCommand{static name=`search`;static description=`Searches Actors in the Apify Store.
107
+ `)}),this.flags.open&&await Ot(ie)}catch(e){t.e=e}finally{t.d()}}},ActorsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes an Actor from your account.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete an Actor by its full name (prompts for confirmation).`,command:`apify actors rm my-username/my-actor`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-rm`;static args={actorId:Z.string({description:`The Actor ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow();if(!await n.actor(e).get()){error({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await X({message:`Are you sure you want to delete this Actor?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of Actor "${e}" was canceled.`});return}try{await n.actor(e).delete(),success({message:`Actor with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete Actor "${e}".\n ${n.message||n}`})}}};const pr={FREE:`Free`,FLAT_PRICE_PER_MONTH:`Subscription`,PRICE_PER_DATASET_ITEM:`Pay per result`,PAY_PER_EVENT:`Pay per event`};function formatPricingModel(e){return e?pr[e]??e:t.gray(`Unknown`)}function truncateDescription(e,t=60){return e?e.length<=t?e:`${e.slice(0,t-1)}…`:``}var ActorsSearchCommand=class extends ApifyCommand{static name=`search`;static description=`Searches Actors in the Apify Store.
106
108
 
107
109
  Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static examples=[{description:`Search the Apify Store for "web scraper" Actors.`,command:`apify actors search "web scraper"`},{description:`Search for TikTok Actors sorted by popularity, limit to 5 results.`,command:`apify actors search "tiktok" --limit 5 --sort-by popularity`},{description:`Find free AI Actors.`,command:`apify actors search "ai" --category AI --pricing-model FREE`},{description:`Output results as JSON for scripting.`,command:`apify actors search "web scraper" --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-search`;static args={query:Z.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":Y.string({description:`Sort order for the results.`,options:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:Y.string({description:`Filter by category (e.g. AI).`}),username:Y.string({description:`Filter by Actor author username.`}),"pricing-model":Y.string({description:`Filter by pricing model.`,options:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:Y.integer({description:`Maximum number of results to return.`,default:20}),offset:Y.integer({description:`Number of results to skip for pagination.`,default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:n,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l}=this.flags,u=await getApifyClientOptions();delete u.token;let f=new Ve(u),p;try{p=await f.store().list({search:e,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l})}catch(e){process.exitCode=1,error({message:`Failed to search Apify Store: ${e instanceof Error?e.message:String(e)}`,stdout:!0});return}if(p.count===0){if(n){printJsonToStdout(p);return}info({message:`No Actors found matching your search.`,stdout:!0});return}if(n){printJsonToStdout(p);return}let m=new Q({allColumns:[`Name`,`Description`,`Users (30d)`,`Pricing`],mandatoryColumns:[`Name`,`Pricing`],columnAlignments:{"Users (30d)":`right`,Name:`left`}});for(let e of p.items)m.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Description:truncateDescription(e.description),"Users (30d)":t.cyan(`${e.stats?.totalUsers30Days??0}`),Pricing:formatPricingModel(e.currentPricingInfo?.pricingModel)});simpleLog({message:m.render(1),stdout:!0})}},ActorsStartCommand=class extends ApifyCommand{static name=`start`;static description=`Starts Actor remotely and returns run details immediately.
108
- Uses authenticated account and local key-value store for input.`;static examples=[{description:`Start the Actor defined in the current directory and return immediately.`,command:`apify actors start`},{description:`Start a specific Actor with inline JSON input.`,command:`apify actors start apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Start with input from a file and custom memory/timeout.`,command:`apify actors start apify/web-scraper --input-file ./input.json --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-start`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]})};static enableJsonFlag=!0;static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id,{id:c,userFriendlyId:l,actorData:u}=await $n.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),h;for await(let e of m)h=e;if(!h){simpleLog({message:`Actor run did not start.`,stdout:!1}),e.exitCode=1;return}let g=consoleRunUrl(c,h.id),_=`https://console.apify.com/storage/datasets/${h.defaultDatasetId}`;if(this.flags.json){printJsonToStdout({ok:!0,operation:`actors.start`,waited:!1,actor:{id:c,name:l},run:{id:h.id,status:h.status,url:g},next:{wait:`apify runs wait ${h.id} --json`,log:`apify runs log ${h.id}`,info:`apify runs info ${h.id} --json`},exitCode:0});return}let v=[`${t.gray(`Run:`)} Calling Actor ${l} (${t.gray(c)})`,``,`${t.yellow(`Run ID`)}: ${h.id}`,`${t.yellow(`Status`)}: ${h.status}`,`${t.yellow(`Started`)}: ${G.display(h.startedAt)}`];h.containerUrl&&v.push(`${t.yellow(`Container URL`)}: ${t.blue(h.containerUrl)}`);let y=h.buildNumber.split(`.`).slice(0,2).join(`.`),b=u.versions.find(e=>e.versionNumber===y),x=Object.entries(u.taggedBuilds??{}).find(([,e])=>e.buildNumber===h.buildNumber)?.[0],S=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];x?S.push(`(${t.yellow(x)})`):S.push(`(${t.gray(`N/A`)})`),b&&S.push(`| ${t.gray(`Actor version:`)} ${t.cyan(b.versionNumber)} (${t.yellow(b.buildTag)})`),v.push(S.join(` `)),v.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),v.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),v.push(``,`${t.blue(`Export results`)}: ${_}`,`${t.blue(`View on Apify Console`)}: ${g}`,``,t.gray(`This command does not wait for the run to finish.`),``,`To wait for the final status:`,` apify runs wait ${h.id} --json`,``,`To stream or inspect logs:`,` apify runs log ${h.id}`,``,`To inspect run metadata:`,` apify runs info ${h.id} --json`),simpleLog({message:v.join(`
110
+ Uses authenticated account and local key-value store for input.`;static examples=[{description:`Start the Actor defined in the current directory and return immediately.`,command:`apify actors start`},{description:`Start a specific Actor with inline JSON input.`,command:`apify actors start apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Start with input from a file and custom memory/timeout.`,command:`apify actors start apify/web-scraper --input-file ./input.json --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-start`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]})};static enableJsonFlag=!0;static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id,{id:c,userFriendlyId:l,actorData:u}=await tr.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),h;for await(let e of m)h=e;if(!h){simpleLog({message:`Actor run did not start.`,stdout:!1}),e.exitCode=1;return}let g=consoleRunUrl(c,h.id),_=`https://console.apify.com/storage/datasets/${h.defaultDatasetId}`;if(this.flags.json){printJsonToStdout({ok:!0,operation:`actors.start`,waited:!1,actor:{id:c,name:l},run:{id:h.id,status:h.status,url:g},next:{wait:`apify runs wait ${h.id} --json`,log:`apify runs log ${h.id}`,info:`apify runs info ${h.id} --json`},exitCode:0});return}let v=[`${t.gray(`Run:`)} Calling Actor ${l} (${t.gray(c)})`,``,`${t.yellow(`Run ID`)}: ${h.id}`,`${t.yellow(`Status`)}: ${h.status}`,`${t.yellow(`Started`)}: ${G.display(h.startedAt)}`];h.containerUrl&&v.push(`${t.yellow(`Container URL`)}: ${t.blue(h.containerUrl)}`);let y=h.buildNumber.split(`.`).slice(0,2).join(`.`),b=u.versions.find(e=>e.versionNumber===y),x=Object.entries(u.taggedBuilds??{}).find(([,e])=>e.buildNumber===h.buildNumber)?.[0],S=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];x?S.push(`(${t.yellow(x)})`):S.push(`(${t.gray(`N/A`)})`),b&&S.push(`| ${t.gray(`Actor version:`)} ${t.cyan(b.versionNumber)} (${t.yellow(b.buildTag)})`),v.push(S.join(` `)),v.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),v.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),v.push(``,`${t.blue(`Export results`)}: ${_}`,`${t.blue(`View on Apify Console`)}: ${g}`,``,t.gray(`This command does not wait for the run to finish.`),``,`To wait for the final status:`,` apify runs wait ${h.id} --json`,``,`To stream or inspect logs:`,` apify runs log ${h.id}`,``,`To inspect run metadata:`,` apify runs info ${h.id} --json`),simpleLog({message:v.join(`
109
111
  `),stdout:!0})}},ActorsIndexCommand=class extends ApifyCommand{static name=`actors`;static description=`Search, list, deploy, and call Actors on the Apify platform.
110
- For runtime operations inside a running Actor (push-data, get-input, set-value...), see 'apify actor' (singular).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors`;static subcommands=[ActorsStartCommand,ActorsRmCommand,ActorsSearchCommand,ActorsPushCommand,ActorsPullCommand,ActorsLsCommand,ActorsInfoCommand,$n,ActorsBuildCommand];async run(){this.printHelp()}};const fr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],pr=new Set([`GET`,`HEAD`]),mr=`https://docs.apify.com/api/openapi.json`;function parseParams(e){if(!e)return``;let t;try{t=JSON.parse(e)}catch{throw Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let n=new URLSearchParams;for(let[e,r]of Object.entries(t))if(r!=null){if(typeof r==`object`)throw Error(`--params value for "${e}" must be a scalar (string, number, or boolean), got ${Array.isArray(r)?`array`:`object`}. Query parameters cannot contain nested objects or arrays.`);n.append(e,String(r))}return n.toString()}function parseHeaders(e){if(!e)return{};let t=e.trim();if(t.startsWith(`{`)){let e;try{e=JSON.parse(t)}catch{throw Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--header JSON must be an object mapping header names to string values.`);let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)throw Error(`--header value for "${t}" must be a string, got ${typeof r}.`);n[t.trim()]=r.trim()}return n}let n=t.indexOf(`:`);if(n===-1)throw Error(`Header must be in "key:value" format, or a JSON object for multiple headers.`);return{[t.slice(0,n).trim()]:t.slice(n+1).trim()}}const hr={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};function formatEndpointLine(e){let n=(hr[e.method]||t.white)(e.method.padEnd(7)),r=e.summary?t.gray(` ${e.summary}`):``;return`${n} ${e.path}${r}`}const gr=`Run ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`;function printSuggestions(e){if(e.length>0){simpleLog({message:`
111
- Did you mean:`,stdout:!1});for(let t of e)simpleLog({message:` ${formatEndpointLine(t)}`,stdout:!1})}simpleLog({message:`\n${gr}`,stdout:!1})}var ApiCommand=class extends ApifyCommand{cachedEndpoints=null;static name=`api`;static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
112
+ For runtime operations inside a running Actor (push-data, get-input, set-value...), see 'apify actor' (singular).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors`;static subcommands=[ActorsStartCommand,ActorsRmCommand,ActorsSearchCommand,ActorsPushCommand,ActorsPullCommand,ActorsLsCommand,ActorsInfoCommand,tr,ActorsBuildCommand];async run(){this.printHelp()}};const mr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],hr=new Set([`GET`,`HEAD`]),gr=`https://docs.apify.com/api/openapi.json`;function parseParams(e){if(!e)return``;let t;try{t=JSON.parse(e)}catch{throw Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let n=new URLSearchParams;for(let[e,r]of Object.entries(t))if(r!=null){if(typeof r==`object`)throw Error(`--params value for "${e}" must be a scalar (string, number, or boolean), got ${Array.isArray(r)?`array`:`object`}. Query parameters cannot contain nested objects or arrays.`);n.append(e,String(r))}return n.toString()}function parseHeaders(e){if(!e)return{};let t=e.trim();if(t.startsWith(`{`)){let e;try{e=JSON.parse(t)}catch{throw Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--header JSON must be an object mapping header names to string values.`);let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)throw Error(`--header value for "${t}" must be a string, got ${typeof r}.`);n[t.trim()]=r.trim()}return n}let n=t.indexOf(`:`);if(n===-1)throw Error(`Header must be in "key:value" format, or a JSON object for multiple headers.`);return{[t.slice(0,n).trim()]:t.slice(n+1).trim()}}const _r={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};function formatEndpointLine(e){let n=(_r[e.method]||t.white)(e.method.padEnd(7)),r=e.summary?t.gray(` ${e.summary}`):``;return`${n} ${e.path}${r}`}const vr=`Run ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`;function printSuggestions(e){if(e.length>0){simpleLog({message:`
113
+ Did you mean:`,stdout:!1});for(let t of e)simpleLog({message:` ${formatEndpointLine(t)}`,stdout:!1})}simpleLog({message:`\n${vr}`,stdout:!1})}var ApiCommand=class extends ApifyCommand{cachedEndpoints=null;static name=`api`;static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
112
114
  The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the "v2/" prefix is added automatically if omitted.
113
115
 
114
- Use --list-endpoints to see all available API endpoints.`;static examples=[{description:`Make a GET request to an API endpoint (defaults to GET).`,command:`apify api users/me`},{description:`Pass the HTTP method as a positional argument before the endpoint.`,command:`apify api GET /v2/actor-runs`},{description:`Create a resource by POSTing a JSON body.`,command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:`Pass query parameters as a JSON object.`,command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:`Send one or more custom headers as a JSON object.`,command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:`List all available Apify API endpoints.`,command:`apify api --list-endpoints`},{description:`Search for endpoints matching a query.`,command:`apify api --list-endpoints --search "actor run"`},{description:`Print a reference for an endpoint (methods, summary, path params).`,command:`apify api --describe actor-runs/{runId}`}];static docsUrl=`https://docs.apify.com/api/v2`;static args={methodOrEndpoint:Z.string({required:!1,description:`The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").`}),endpoint:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:fr}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.string({char:`H`,description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1,exclusive:[`describe`]}),search:Y.string({char:`s`,description:`Filter results returned by --list-endpoints. The query is case-insensitive and split into tokens by spaces. For an endpoint to be returned, every token must appear in that endpoint's method, path, or summary.`,required:!1,exclusive:[`describe`]}),describe:Y.string({description:`Print a reference for an endpoint path: its HTTP methods, summary, and path parameters. Leading slashes and a version prefix in the path are optional. For example, "actor-runs/{runId}" and "/v2/actor-runs/{runId}" are both accepted.`,required:!1,exclusive:[`list-endpoints`,`search`]})};async run(){if(this.flags.search&&!this.flags.listEndpoints)throw Error(`The --search flag can only be used together with --list-endpoints.`);if(this.flags.describe){await this.describeEndpoint(this.flags.describe);return}if(this.flags.listEndpoints){await this.printEndpoints(this.flags.search);return}let t=this.flags.method?.toUpperCase(),n,r=this.args.methodOrEndpoint;if(r&&fr.includes(r.toUpperCase())){let e=r.toUpperCase();if(t&&t!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${t}". Please specify the method only once.`);n=e,r=this.args.endpoint}else n=t;if(n??=`GET`,!r){this.printHelp();return}let i=parseParams(this.flags.params),a=parseHeaders(this.flags.header);if(this.flags.body){if(pr.has(n))throw Error(`HTTP ${n} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let s=await getLoggedClientOrThrow(),c=s.token,l=normalizePath(r),u=`${s.baseUrl}/${l}`;if(i){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}${i}`}let f={...sn,Authorization:`Bearer ${c}`};this.flags.body&&(f[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(a)){for(let t of Object.keys(f))t.toLowerCase()===e.toLowerCase()&&delete f[t];f[e]=t}let p=await fetch(u,{method:n,headers:f,body:this.flags.body||void 0}),m=await p.text();if(!p.ok){if(e.exitCode=1,error({message:`${p.status} ${p.statusText}`}),m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}p.status===404&&await this.print404Suggestions(l);return}if(m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}}async getEndpoints(){return this.cachedEndpoints??=await fetchEndpoints(),this.cachedEndpoints}async printEndpoints(e){let t=await this.getEndpoints();if(e&&(t=filterEndpoints(t,e),t.length===0)){simpleLog({message:`No endpoints matched the query "${e}".`,stdout:!1});return}for(let e of t)console.log(formatEndpointLine(e))}async describeEndpoint(e){let n=normalizePath(e),r=await this.getEndpoints(),i=r.filter(e=>normalizePath(e.path)===n);if(i.length>0){let e=extractPathParams(i[0].path);console.log(t.bold(i[0].path)),console.log(``);for(let e of i){let n=hr[e.method]||t.white;console.log(` ${n(e.method.padEnd(7))} ${e.summary||t.gray(`(no summary)`)}`)}if(e.length>0){console.log(``),console.log(t.bold(`Path parameters:`));for(let n of e)console.log(` ${t.yellow(`{${n}}`)}`)}console.log(``),console.log(t.gray(`Docs: https://docs.apify.com/api/v2`));return}simpleLog({message:`No endpoint found for "${e}".`,stdout:!1}),printSuggestions(findClosestEndpoints(r,n))}async print404Suggestions(e){try{printSuggestions(findClosestEndpoints(await this.getEndpoints(),e))}catch{simpleLog({message:`\n${gr}`,stdout:!1})}}};async function fetchEndpoints(){let e;try{e=await fetch(mr)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${mr}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${mr}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))fr.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}function normalizePath(e){let t=e;return t.startsWith(`/`)&&(t=t.slice(1)),t=t.replace(/^v2\//i,``),t}function filterEndpoints(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?e:e.filter(e=>{let t=`${e.method} ${e.path} ${e.summary}`.toLowerCase();return n.every(e=>t.includes(e))})}function extractPathParams(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(e=>e.slice(1,-1)):[]}function findClosestEndpoints(e,t,n=5){let r=t.toLowerCase(),i=r.split(`/`).filter(Boolean),a=new Map;for(let t of e){if(a.has(t.path))continue;let e=normalizePath(t.path).toLowerCase(),n=0;(e.includes(r)||r.includes(e))&&(n+=10);let s=e.split(`/`).filter(Boolean),c=Math.min(i.length,s.length);for(let e=0;e<c;e++)s[e]===i[e]?n+=2:s[e].startsWith(`{`)&&(n+=1);i.length===s.length&&(n+=1),n>0&&a.set(t.path,n)}let s=[...a.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,n).map(([e])=>e),c=new Set(s),l=new Map;for(let t of e)if(c.has(t.path)){let e=l.get(t.path)||[];e.push(t),l.set(t.path,e)}return s.flatMap(e=>l.get(e)||[])}const _r=stdinCheckWrapper(async({message:e,mask:t})=>await Ft({message:e,mask:t??`*`})),vr=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await It({message:e,choices:t,pageSize:n,loop:r,default:i})),yr=`https://console.apify.com/settings/integrations`,br=new URL(yr).origin,xr=yr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async n=>{let r=await getLoggedClient(n,xr),i=await getLocalUserInfo();if(r){await updateUserId(i.id);let n=await getBackend(),r;r=n===`keyring`?`your OS keyring`:e.env.APIFY_DISABLE_KEYRING===`1`?`${AUTH_FILE_PATH()} (OS keyring disabled via APIFY_DISABLE_KEYRING)`:e.env.APIFY_CLI_BUNDLE?`${AUTH_FILE_PATH()} (OS keyring not available in bundle installs; install via npm for keyring storage, or set APIFY_DISABLE_KEYRING=1 to silence)`:`${AUTH_FILE_PATH()} (OS keyring unavailable; set APIFY_DISABLE_KEYRING=1 to silence)`,success({message:`You are logged in to Apify as ${i.username||i.id}. ${t.gray(`Your token is stored in ${r}.`)}`})}else error({message:`Login to Apify failed, the provided API token is not valid.`});return r};var AuthLoginCommand=class extends ApifyCommand{static name=`login`;static description=`Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\nAll other commands use these stored credentials.
116
+ Use --list-endpoints to see all available API endpoints.`;static examples=[{description:`Make a GET request to an API endpoint (defaults to GET).`,command:`apify api users/me`},{description:`Pass the HTTP method as a positional argument before the endpoint.`,command:`apify api GET /v2/actor-runs`},{description:`Create a resource by POSTing a JSON body.`,command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:`Pass query parameters as a JSON object.`,command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:`Send one or more custom headers as a JSON object.`,command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:`List all available Apify API endpoints.`,command:`apify api --list-endpoints`},{description:`Search for endpoints matching a query.`,command:`apify api --list-endpoints --search "actor run"`},{description:`Print a reference for an endpoint (methods, summary, path params).`,command:`apify api --describe actor-runs/{runId}`}];static docsUrl=`https://docs.apify.com/api/v2`;static args={methodOrEndpoint:Z.string({required:!1,description:`The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").`}),endpoint:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:mr}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.string({char:`H`,description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1,exclusive:[`describe`]}),search:Y.string({char:`s`,description:`Filter results returned by --list-endpoints. The query is case-insensitive and split into tokens by spaces. For an endpoint to be returned, every token must appear in that endpoint's method, path, or summary.`,required:!1,exclusive:[`describe`]}),describe:Y.string({description:`Print a reference for an endpoint path: its HTTP methods, summary, and path parameters. Leading slashes and a version prefix in the path are optional. For example, "actor-runs/{runId}" and "/v2/actor-runs/{runId}" are both accepted.`,required:!1,exclusive:[`list-endpoints`,`search`]})};async run(){if(this.flags.search&&!this.flags.listEndpoints)throw Error(`The --search flag can only be used together with --list-endpoints.`);if(this.flags.describe){await this.describeEndpoint(this.flags.describe);return}if(this.flags.listEndpoints){await this.printEndpoints(this.flags.search);return}let t=this.flags.method?.toUpperCase(),n,r=this.args.methodOrEndpoint;if(r&&mr.includes(r.toUpperCase())){let e=r.toUpperCase();if(t&&t!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${t}". Please specify the method only once.`);n=e,r=this.args.endpoint}else n=t;if(n??=`GET`,!r){this.printHelp();return}let i=parseParams(this.flags.params),a=parseHeaders(this.flags.header);if(this.flags.body){if(hr.has(n))throw Error(`HTTP ${n} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let s=await getLoggedClientOrThrow(),c=s.token,l=normalizePath(r),u=`${s.baseUrl}/${l}`;if(i){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}${i}`}let f={...sn,Authorization:`Bearer ${c}`};this.flags.body&&(f[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(a)){for(let t of Object.keys(f))t.toLowerCase()===e.toLowerCase()&&delete f[t];f[e]=t}let p=await fetch(u,{method:n,headers:f,body:this.flags.body||void 0}),m=await p.text();if(!p.ok){if(e.exitCode=1,error({message:`${p.status} ${p.statusText}`}),m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}p.status===404&&await this.print404Suggestions(l);return}if(m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}}async getEndpoints(){return this.cachedEndpoints??=await fetchEndpoints(),this.cachedEndpoints}async printEndpoints(e){let t=await this.getEndpoints();if(e&&(t=filterEndpoints(t,e),t.length===0)){simpleLog({message:`No endpoints matched the query "${e}".`,stdout:!1});return}for(let e of t)console.log(formatEndpointLine(e))}async describeEndpoint(e){let n=normalizePath(e),r=await this.getEndpoints(),i=r.filter(e=>normalizePath(e.path)===n);if(i.length>0){let e=extractPathParams(i[0].path);console.log(t.bold(i[0].path)),console.log(``);for(let e of i){let n=_r[e.method]||t.white;console.log(` ${n(e.method.padEnd(7))} ${e.summary||t.gray(`(no summary)`)}`)}if(e.length>0){console.log(``),console.log(t.bold(`Path parameters:`));for(let n of e)console.log(` ${t.yellow(`{${n}}`)}`)}console.log(``),console.log(t.gray(`Docs: https://docs.apify.com/api/v2`));return}simpleLog({message:`No endpoint found for "${e}".`,stdout:!1}),printSuggestions(findClosestEndpoints(r,n))}async print404Suggestions(e){try{printSuggestions(findClosestEndpoints(await this.getEndpoints(),e))}catch{simpleLog({message:`\n${vr}`,stdout:!1})}}};async function fetchEndpoints(){let e;try{e=await fetch(gr)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))mr.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}function normalizePath(e){let t=e;return t.startsWith(`/`)&&(t=t.slice(1)),t=t.replace(/^v2\//i,``),t}function filterEndpoints(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?e:e.filter(e=>{let t=`${e.method} ${e.path} ${e.summary}`.toLowerCase();return n.every(e=>t.includes(e))})}function extractPathParams(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(e=>e.slice(1,-1)):[]}function findClosestEndpoints(e,t,n=5){let r=t.toLowerCase(),i=r.split(`/`).filter(Boolean),a=new Map;for(let t of e){if(a.has(t.path))continue;let e=normalizePath(t.path).toLowerCase(),n=0;(e.includes(r)||r.includes(e))&&(n+=10);let s=e.split(`/`).filter(Boolean),c=Math.min(i.length,s.length);for(let e=0;e<c;e++)s[e]===i[e]?n+=2:s[e].startsWith(`{`)&&(n+=1);i.length===s.length&&(n+=1),n>0&&a.set(t.path,n)}let s=[...a.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,n).map(([e])=>e),c=new Set(s),l=new Map;for(let t of e)if(c.has(t.path)){let e=l.get(t.path)||[];e.push(t),l.set(t.path,e)}return s.flatMap(e=>l.get(e)||[])}const yr=stdinCheckWrapper(async({message:e,mask:t})=>await Ft({message:e,mask:t??`*`})),br=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await It({message:e,choices:t,pageSize:n,loop:r,default:i})),xr=`https://console.apify.com/settings/integrations`,Sr=new URL(xr).origin,Cr=xr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async n=>{let r=await getLoggedClient(n,Cr),i=await getLocalUserInfo();if(r){await updateUserId(i.id);let n=await getBackend(),r;r=n===`keyring`?`your OS keyring`:e.env.APIFY_DISABLE_KEYRING===`1`?`${AUTH_FILE_PATH()} (OS keyring disabled via APIFY_DISABLE_KEYRING)`:e.env.APIFY_CLI_BUNDLE?`${AUTH_FILE_PATH()} (OS keyring not available in bundle installs; install via npm for keyring storage, or set APIFY_DISABLE_KEYRING=1 to silence)`:`${AUTH_FILE_PATH()} (OS keyring unavailable; set APIFY_DISABLE_KEYRING=1 to silence)`,success({message:`You are logged in to Apify as ${i.username||i.id}. ${t.gray(`Your token is stored in ${r}.`)}`})}else error({message:`Login to Apify failed, the provided API token is not valid.`});return r};var AuthLoginCommand=class extends ApifyCommand{static name=`login`;static description=`Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\nAll other commands use these stored credentials.
115
117
 
116
- Run 'apify logout' to remove authentication.`;static group=`Authentication`;static interactive=!0;static interactiveNote=`Prompts for an API token if not provided. To run non-interactively, pass --token <api-token>.`;static examples=[{description:`Log in interactively (prompts to choose a method, then completes the flow accordingly).`,command:`apify login`},{description:`Log in non-interactively with an API token.`,command:`apify login --token apify_api_xxxxx`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-login`;static flags={token:Y.string({char:`t`,description:`Apify API token.`,required:!1}),method:Y.string({char:`m`,description:`Method of logging in to Apify.`,choices:[`console`,`manual`],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await tryToLogin(e);return}let n=t;if(t||(n=await vr({message:`Choose how you want to log in to Apify`,choices:[{value:`console`,name:`Through Apify Console in your default browser`,short:`Through Apify Console`},{value:`manual`,name:`Enter API token manually`,short:`Manually`}],loop:!0})),n===`console`){let e,t=Pt();t.use(Nt({origin:br,allowedHeaders:[`Content-Type`,`Authorization`]})),t.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),t.use(Pt.json());let n=we();t.use((e,t,r)=>{let{token:i}=e.query;if(!i){let t=e.get(`Authorization`);if(t){let[e,n,...r]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&r.length===0&&(i=n)}}i===n?r():(t.status(401),t.send(`Authorization failed`))});let r=Pt.Router();t.use(`/api/v1`,r),r.post(`/login-token`,async(t,n)=>{try{if(t.body.apiToken)await tryToLogin(t.body.apiToken);else throw Error(`Request did not contain API token`);n.end()}catch(e){let t=`Login to Apify failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}e.close()}),r.post(`/exit`,(t,n)=>{t.body.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):t.body.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),e.close()}),e=t.listen(0);let{port:i}=e.address(),a=new URL(yr);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${i}`),a.searchParams.set(`localCliToken`,n),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Mt()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await Ot(a.href)}else console.log(`Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations`),await tryToLogin(await _r({message:`token:`}))}},AuthLogoutCommand=class extends ApifyCommand{static name=`logout`;static description=`Removes authentication by deleting your API token and account information from '${tildify(AUTH_FILE_PATH())}'.\nRun 'apify login' to authenticate again.`;static group=`Authentication`;static examples=[{description:`Remove the stored Apify credentials.`,command:`apify logout`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-logout`;async run(){await clearKeyringSecrets(),await rimrafPromised(AUTH_FILE_PATH()),await updateUserId(null),success({message:`You are logged out from your Apify account.`})}},AuthTokenCommand=class extends ApifyCommand{static name=`token`;static description=`Prints the current API token for the Apify CLI.`;static examples=[{description:`Print the stored API token to stdout (use with care — it is a secret).`,command:`apify auth token`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-token`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();e.token&&simpleLog({message:e.token,stdout:!0})}},AuthIndexCommand=class extends ApifyCommand{static name=`auth`;static description="Log in, log out, and inspect your stored Apify API token. Also available as `apify login` / `apify logout`.";static group=`Authentication`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth`;static subcommands=[AuthLoginCommand,AuthLogoutCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{static name=`add-tag`;static description=`Adds a tag to a specific Actor build.`;static examples=[{description:`Tag a successful build as "latest".`,command:`apify builds add-tag --build <buildId> --tag latest`},{description:`Tag a build with a custom name like "beta".`,command:`apify builds add-tag --build <buildId> --tag beta`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-add-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to add to the build.`,required:!0})};async run(){let{build:e,tag:n}=this.flags,r=await getLoggedClientOrThrow(),i=await r.build(e).get();if(!i){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(i.status!==`SUCCEEDED`){error({message:`Build with ID "${e}" has status "${i.status}". Only successful builds can be tagged.`,stdout:!0});return}let a=await r.actor(i.actId).get();if(!a){error({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let s=(a.taggedBuilds??{})[n];if(s?.buildId===e){warning({message:`Build "${e}" is already tagged as "${n}".`,stdout:!0});return}try{await r.actor(i.actId).update({taggedBuilds:{[n]:{buildId:i.id}}});let a=s?.buildNumber?` (previously pointed to build ${t.gray(s.buildNumber)})`:``;success({message:`Tag "${t.yellow(n)}" added to build ${t.gray(i.buildNumber)} (${t.gray(e)})${a}`,stdout:!0})}catch(t){let r=t;error({message:`Failed to add tag "${n}" to build "${e}".\n ${r.message||r}`,stdout:!0})}}};const noColor=e=>e;function prettyPrintBytes({bytes:e,shortBytes:t=!1,colorFunc:n=noColor,precision:r=2}){let i=[t?`B`:`Bytes`,`KB`,`MB`,`GB`,`TB`];if(e===0)return t?`${0 .toPrecision(r)} B`:`${0 .toPrecision(r)} Byte`;let a=Math.floor(Math.log(e)/Math.log(1e3));return`${(e/1e3**a).toFixed(r)} ${n(i[a])}`}var BuildsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about a specific build.`;static examples=[{description:`Print information about a build.`,command:`apify builds info <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-info`;static args={buildId:Z.string({required:!0,description:`The build ID to get information about.`})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){printJsonToStdout(r);return}let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[e,t]of Object.entries(i.taggedBuilds))if(t.buildId===r.id){a=e;break}}let s=Reflect.get(r,`exitCode`),c=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,l=a?` (tagged as ${t.yellow(a)})`:``,u=s===void 0?``:` (exit code: ${t.gray(s)})`,f=[`${t.yellow(`Actor`)}: ${c} (${t.gray(r.actId)})`,``,`${t.yellow(`Build Information`)} (ID: ${t.gray(r.id)})`,` ${t.yellow(`Build Number`)}: ${r.buildNumber}${l}`,` ${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${u}`,` ${t.yellow(`Started`)}: ${G.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(kn.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${kn.format(e)}`)}`)}r.stats?.computeUnits&&f.push(` ${t.yellow(`Compute Units`)}: ${r.stats.computeUnits.toFixed(3)}`);let p=Reflect.get(r.stats??{},`imageSizeBytes`);p&&f.push(` ${t.yellow(`Docker Image Size`)}: ${prettyPrintBytes({bytes:p})}`),f.push(` ${t.yellow(`Origin`)}: ${r.meta.origin??`UNKNOWN`}`),f.push(``);let m=`https://console.apify.com/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
118
+ Run 'apify logout' to remove authentication.`;static group=`Authentication`;static interactive=!0;static interactiveNote=`Prompts for an API token if not provided. To run non-interactively, pass --token <api-token>.`;static examples=[{description:`Log in interactively (prompts to choose a method, then completes the flow accordingly).`,command:`apify login`},{description:`Log in non-interactively with an API token.`,command:`apify login --token apify_api_xxxxx`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-login`;static flags={token:Y.string({char:`t`,description:`Apify API token.`,required:!1}),method:Y.string({char:`m`,description:`Method of logging in to Apify.`,choices:[`console`,`manual`],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await tryToLogin(e);return}let n=t;if(t||(n=await br({message:`Choose how you want to log in to Apify`,choices:[{value:`console`,name:`Through Apify Console in your default browser`,short:`Through Apify Console`},{value:`manual`,name:`Enter API token manually`,short:`Manually`}],loop:!0})),n===`console`){let e,t=Pt();t.use(Nt({origin:Sr,allowedHeaders:[`Content-Type`,`Authorization`]})),t.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),t.use(Pt.json());let n=we();t.use((e,t,r)=>{let{token:i}=e.query;if(!i){let t=e.get(`Authorization`);if(t){let[e,n,...r]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&r.length===0&&(i=n)}}i===n?r():(t.status(401),t.send(`Authorization failed`))});let r=Pt.Router();t.use(`/api/v1`,r),r.post(`/login-token`,async(t,n)=>{try{if(t.body.apiToken)await tryToLogin(t.body.apiToken);else throw Error(`Request did not contain API token`);n.end()}catch(e){let t=`Login to Apify failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}e.close()}),r.post(`/exit`,(t,n)=>{t.body.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):t.body.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),e.close()}),e=t.listen(0);let{port:i}=e.address(),a=new URL(xr);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${i}`),a.searchParams.set(`localCliToken`,n),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Mt()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await Ot(a.href)}else console.log(`Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations`),await tryToLogin(await yr({message:`token:`}))}},AuthLogoutCommand=class extends ApifyCommand{static name=`logout`;static description=`Removes authentication by deleting your API token and account information from '${tildify(AUTH_FILE_PATH())}'.\nRun 'apify login' to authenticate again.`;static group=`Authentication`;static examples=[{description:`Remove the stored Apify credentials.`,command:`apify logout`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-logout`;async run(){await clearKeyringSecrets(),await rimrafPromised(AUTH_FILE_PATH()),await updateUserId(null),success({message:`You are logged out from your Apify account.`})}},AuthTokenCommand=class extends ApifyCommand{static name=`token`;static description=`Prints the current API token for the Apify CLI.`;static examples=[{description:`Print the stored API token to stdout (use with care — it is a secret).`,command:`apify auth token`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-token`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();e.token&&simpleLog({message:e.token,stdout:!0})}},AuthIndexCommand=class extends ApifyCommand{static name=`auth`;static description="Log in, log out, and inspect your stored Apify API token. Also available as `apify login` / `apify logout`.";static group=`Authentication`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth`;static subcommands=[AuthLoginCommand,AuthLogoutCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{static name=`add-tag`;static description=`Adds a tag to a specific Actor build.`;static examples=[{description:`Tag a successful build as "latest".`,command:`apify builds add-tag --build <buildId> --tag latest`},{description:`Tag a build with a custom name like "beta".`,command:`apify builds add-tag --build <buildId> --tag beta`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-add-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to add to the build.`,required:!0})};async run(){let{build:e,tag:n}=this.flags,r=await getLoggedClientOrThrow(),i=await r.build(e).get();if(!i){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(i.status!==`SUCCEEDED`){error({message:`Build with ID "${e}" has status "${i.status}". Only successful builds can be tagged.`,stdout:!0});return}let a=await r.actor(i.actId).get();if(!a){error({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let s=(a.taggedBuilds??{})[n];if(s?.buildId===e){warning({message:`Build "${e}" is already tagged as "${n}".`,stdout:!0});return}try{await r.actor(i.actId).update({taggedBuilds:{[n]:{buildId:i.id}}});let a=s?.buildNumber?` (previously pointed to build ${t.gray(s.buildNumber)})`:``;success({message:`Tag "${t.yellow(n)}" added to build ${t.gray(i.buildNumber)} (${t.gray(e)})${a}`,stdout:!0})}catch(t){let r=t;error({message:`Failed to add tag "${n}" to build "${e}".\n ${r.message||r}`,stdout:!0})}}};const noColor=e=>e;function prettyPrintBytes({bytes:e,shortBytes:t=!1,colorFunc:n=noColor,precision:r=2}){let i=[t?`B`:`Bytes`,`KB`,`MB`,`GB`,`TB`];if(e===0)return t?`${0 .toPrecision(r)} B`:`${0 .toPrecision(r)} Byte`;let a=Math.floor(Math.log(e)/Math.log(1e3));return`${(e/1e3**a).toFixed(r)} ${n(i[a])}`}var BuildsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about a specific build.`;static examples=[{description:`Print information about a build.`,command:`apify builds info <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-info`;static args={buildId:Z.string({required:!0,description:`The build ID to get information about.`})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){printJsonToStdout(r);return}let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[e,t]of Object.entries(i.taggedBuilds))if(t.buildId===r.id){a=e;break}}let s=Reflect.get(r,`exitCode`),c=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,l=a?` (tagged as ${t.yellow(a)})`:``,u=s===void 0?``:` (exit code: ${t.gray(s)})`,f=[`${t.yellow(`Actor`)}: ${c} (${t.gray(r.actId)})`,``,`${t.yellow(`Build Information`)} (ID: ${t.gray(r.id)})`,` ${t.yellow(`Build Number`)}: ${r.buildNumber}${l}`,` ${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${u}`,` ${t.yellow(`Started`)}: ${G.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(kn.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${kn.format(e)}`)}`)}r.stats?.computeUnits&&f.push(` ${t.yellow(`Compute Units`)}: ${r.stats.computeUnits.toFixed(3)}`);let p=Reflect.get(r.stats??{},`imageSizeBytes`);p&&f.push(` ${t.yellow(`Docker Image Size`)}: ${prettyPrintBytes({bytes:p})}`),f.push(` ${t.yellow(`Origin`)}: ${r.meta.origin??`UNKNOWN`}`),f.push(``);let m=`https://console.apify.com/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
117
119
  `),stdout:!0})}},BuildsLogCommand=class extends ApifyCommand{static name=`log`;static description=`Prints the log of a specific build.`;static examples=[{description:`Print the build log.`,command:`apify builds log <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-log`;static args={buildId:Z.string({required:!0,description:`The build ID to get the log from.`})};async run(){let{buildId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.build(e).get();if(!n)throw Error(`Build with ID "${e}" was not found on your account.`);info({message:`Log for build with ID "${e}":\n`}),await outputJobLog({job:n,apifyClient:t})}};const tableFactory=()=>new Q({allColumns:[`Number`,`ID`,`Status`,`Took`],mandatoryColumns:[`Number`,`ID`,`Status`,`Took`],columnAlignments:{Took:`right`}});var BuildsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all builds of the Actor.`;static examples=[{description:`List builds of the Actor in the current directory.`,command:`apify builds ls`},{description:`List builds of a specific Actor.`,command:`apify builds ls apify/hello-world`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-ls`;static flags={offset:Y.integer({description:`Number of builds that will be skipped.`,default:0}),limit:Y.integer({description:`Number of builds that will be listed.`,default:10}),desc:Y.boolean({description:`Sort builds in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.string({description:`Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let u=await c.actor(l.id).builds().list({desc:e,limit:n,offset:r}),f=await c.actor(l.id).get(),p=objectGroupBy(u.items,e=>{let[t,n]=Reflect.get(e,`buildNumber`).split(`.`);return`${t}.${n}`}),m=Object.entries(f.taggedBuilds??{}).reduce((e,[t,n])=>(e[n.buildNumber]=t,e),{});if(a){for(let e of u.items){let t=m[Reflect.get(e,`buildNumber`)];t&&Reflect.set(e,`buildTag`,t)}printJsonToStdout(u);return}simpleLog({message:`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} builds for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})\n`,stdout:!0});let h=Object.entries(p).sort((e,t)=>e[0].localeCompare(t[0]));for(let[e,n]of h){if(!n?.length){simpleLog({message:`No builds for version ${e}`,stdout:!0});continue}let r=f.versions.find(t=>t.versionNumber===e)?.buildTag,a=this.generateTableForActorVersion({buildsForVersion:n,buildTagToActorVersion:m}),s=r?` (latest build gets tagged with ${t.yellow(r)})`:``;simpleLog({message:[t.reset(`Builds for Actor Version ${t.yellow(e)}${s}`),a.render(i?0:-1),``].join(`
118
- `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${K.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${K.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{static name=`remove-tag`;static description=`Removes a tag from a specific Actor build.`;static examples=[{description:`Remove a tag from a build (prompts for confirmation).`,command:`apify builds remove-tag --build <buildId> --tag beta`},{description:`Remove a tag non-interactively.`,command:`apify builds remove-tag --build <buildId> --tag beta --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c){error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});return}if(c.buildId!==e){error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,providedConfirmFromStdin:r||void 0})){info({message:`Tag removal was canceled.`,stdout:!0});return}try{await i.actor(a.actId).update({taggedBuilds:{[n]:null}}),success({message:`Tag "${t.yellow(n)}" removed from build ${t.gray(a.buildNumber)} (${t.gray(e)})`,stdout:!0})}catch(t){let r=t;error({message:`Failed to remove tag "${n}" from build "${e}".\n ${r.message||r}`,stdout:!0})}}};const Sr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await at({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}}));var BuildsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes an Actor build from the Apify platform.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Tagged builds additionally require typing the tag name.`;static examples=[{description:`Delete a build (prompts for confirmation).`,command:`apify builds rm <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-rm`;static args={buildId:Z.string({description:`The build ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r)throw Error(`Build with ID "${e}" was not found on your account.`);let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[t,n]of Object.entries(i.taggedBuilds))if(e===n.buildId){a=t;break}}let s;if(s=a?await Sr({message:`Are you sure you want to delete this Actor Build? If so, please type in "${a}":`,expectedValue:a,failureMessage:`Your provided value does not match the build tag.`,providedConfirmFromStdin:t?a:void 0}):await X({message:`Are you sure you want to delete this Actor Build?`,providedConfirmFromStdin:t||void 0}),!s){info({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}await n.build(e).delete(),success({message:`Build with ID "${e}" was deleted.`,stdout:!0})}},BuildsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor build to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
119
- Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a build to finish and return a non-zero exit code on failure.`,command:`apify builds wait <buildId>`},{description:`Wait for a build and emit a structured JSON result.`,command:`apify builds wait <buildId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-wait`;static enableJsonFlag=!0;static args={buildId:Z.string({required:!0,description:`The build ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`In seconds, how long to wait before giving up. If skipped, it waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`In seconds, how often to poll the platform. Defaults to 2.`,required:!1})};async run(){let{buildId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`build`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleBuildUrl(l.actId,l.buildNumber),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`build`),m=`Gave up waiting after ${n}s; build is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`builds.wait`,timedOutWaiting:c,build:{id:l.id,status:l.status,number:l.buildNumber,url:u},...f?{}:{error:{phase:`build`,message:c?m:`Actor build did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Build`,value:l.status},{label:`Build ID`,value:l.id},{label:`Build number`,value:l.buildNumber},{label:`Actor ID`,value:l.actId}],_=[{label:`Build URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Build ended with status ${l.status}.`}),e.exitCode=p}},BuildsIndexCommand=class extends ApifyCommand{static name=`builds`;static description=`Create, inspect, tag, and delete Actor builds on the Apify platform.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds`;static subcommands=[BuildsAddTagCommand,BuildsRemoveTagCommand,BuildsRmCommand,BuildsLsCommand,BuildsLogCommand,BuildsInfoCommand,BuildsCreateCommand,BuildsWaitCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends $n{static name=`call`};const pathToInstallMarker=e=>k(e,`.install-marker`);var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;async run(){let{installMethod:e,installPath:n,version:r}=useCLIMetadata();if(e!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}Lt(n,`When CLI is installed via bundles, the install path must be set`);let i=pathToInstallMarker(n);if(v(i)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(process.platform!==`win32`){await this.symlinkToLocalBin(n);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await z(i,r),cliDebugPrint(`[install] install marker written to`,i),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(r)}`),t.gray(` Location: ${t.bold.white(tildify(k(n,`apify`)))} and ${t.bold.white(tildify(k(n,`actor`)))}`)].join(`
120
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${K.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${K.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{static name=`remove-tag`;static description=`Removes a tag from a specific Actor build.`;static examples=[{description:`Remove a tag from a build (prompts for confirmation).`,command:`apify builds remove-tag --build <buildId> --tag beta`},{description:`Remove a tag non-interactively.`,command:`apify builds remove-tag --build <buildId> --tag beta --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c){error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});return}if(c.buildId!==e){error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,providedConfirmFromStdin:r||void 0})){info({message:`Tag removal was canceled.`,stdout:!0});return}try{await i.actor(a.actId).update({taggedBuilds:{[n]:null}}),success({message:`Tag "${t.yellow(n)}" removed from build ${t.gray(a.buildNumber)} (${t.gray(e)})`,stdout:!0})}catch(t){let r=t;error({message:`Failed to remove tag "${n}" from build "${e}".\n ${r.message||r}`,stdout:!0})}}};const wr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await at({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}}));var BuildsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes an Actor build from the Apify platform.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Tagged builds additionally require typing the tag name.`;static examples=[{description:`Delete a build (prompts for confirmation).`,command:`apify builds rm <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-rm`;static args={buildId:Z.string({description:`The build ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r)throw Error(`Build with ID "${e}" was not found on your account.`);let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[t,n]of Object.entries(i.taggedBuilds))if(e===n.buildId){a=t;break}}let s;if(s=a?await wr({message:`Are you sure you want to delete this Actor Build? If so, please type in "${a}":`,expectedValue:a,failureMessage:`Your provided value does not match the build tag.`,providedConfirmFromStdin:t?a:void 0}):await X({message:`Are you sure you want to delete this Actor Build?`,providedConfirmFromStdin:t||void 0}),!s){info({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}await n.build(e).delete(),success({message:`Build with ID "${e}" was deleted.`,stdout:!0})}},BuildsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor build to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
121
+ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a build to finish and return a non-zero exit code on failure.`,command:`apify builds wait <buildId>`},{description:`Wait for a build and emit a structured JSON result.`,command:`apify builds wait <buildId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-wait`;static enableJsonFlag=!0;static args={buildId:Z.string({required:!0,description:`The build ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`In seconds, how long to wait before giving up. If skipped, it waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`In seconds, how often to poll the platform. Defaults to 2.`,required:!1})};async run(){let{buildId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`build`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleBuildUrl(l.actId,l.buildNumber),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`build`),m=`Gave up waiting after ${n}s; build is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`builds.wait`,timedOutWaiting:c,build:{id:l.id,status:l.status,number:l.buildNumber,url:u},...f?{}:{error:{phase:`build`,message:c?m:`Actor build did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Build`,value:l.status},{label:`Build ID`,value:l.id},{label:`Build number`,value:l.buildNumber},{label:`Actor ID`,value:l.actId}],_=[{label:`Build URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Build ended with status ${l.status}.`}),e.exitCode=p}},BuildsIndexCommand=class extends ApifyCommand{static name=`builds`;static description=`Create, inspect, tag, and delete Actor builds on the Apify platform.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds`;static subcommands=[BuildsAddTagCommand,BuildsRemoveTagCommand,BuildsRmCommand,BuildsLsCommand,BuildsLogCommand,BuildsInfoCommand,BuildsCreateCommand,BuildsWaitCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends tr{static name=`call`};const pathToInstallMarker=e=>k(e,`.install-marker`);var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;async run(){let{installMethod:e,installPath:n,version:r}=useCLIMetadata();if(e!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}Lt(n,`When CLI is installed via bundles, the install path must be set`);let i=pathToInstallMarker(n);if(v(i)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(process.platform!==`win32`){await this.symlinkToLocalBin(n);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await z(i,r),cliDebugPrint(`[install] install marker written to`,i),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(r)}`),t.gray(` Location: ${t.bold.white(tildify(k(n,`apify`)))} and ${t.bold.white(tildify(k(n,`actor`)))}`)].join(`
120
122
  `)}),simpleLog({message:``}),success({message:`To get started, run:`}),simpleLog({message:t.white.bold(` apify --help
121
123
  actor --help`)})}async symlinkToLocalBin(e){let n=userHomeDir();if(cliDebugPrint(`[install -> symlinkToLocalBin] user home directory`,n),!n){cliDebugPrint(`[install -> symlinkToLocalBin] user home directory not found`),warning({message:t.gray(`User home directory not found, cannot symlink to ~/.local/bin`)});return}let r=k(n,`.local`,`bin`);await F(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=k(e,n);if(!v(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=k(r,n);await Me(a).catch(()=>{}),await je(i,a),cliDebugPrint(`[install] symlink created for item`,n,a)}info({message:t.gray(`Symlinked apify, actor, and apify-cli to ${tildify(r)}`)})}async confirmFromTty(e){let n,r,i=`${t.green(`?`)} ${t.bold(e)} ${t.dim(`(Y/n)`)} `,writeDone=n=>{process.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(e)} ${t.cyan(n)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),n=x(`/dev/tty`,`r`),r=new Rt(n),process.stdout.write(i),r.setRawMode(!0),r.resume(),await new Promise(e=>{let onData=t=>{let n=t.toString();n===`y`||n===`Y`||n===`\r`||n===`
122
124
  `?(r.removeListener(`data`,onData),writeDone(`Yes`),e(!0)):n===`n`||n===`N`?(r.removeListener(`data`,onData),writeDone(`No`),e(!1)):(n===``||n===``)&&(r.removeListener(`data`,onData),process.stdout.write(`
@@ -124,29 +126,29 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
124
126
  `)}\n`;try{await F(O(p),{recursive:!0}),await z(p,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(p)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(p)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(c)}" to your PATH in ${tildify(p)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(p)}`)} to reload your shell.`)].join(`
125
127
  `)});return}let _=p??`your shell config file`;if(g){let e=`echo -e '${h.join(`\\n`)}' >> "${_}" && source "${_}"`;info({message:[t.gray(`The Apify & Actor CLIs are not in your PATH. Run:`),``,t.white.bold(` ${e}`)].join(`
126
128
  `)});return}info({message:[t.gray(`Manually add the following lines to ${_} or similar:`),...h.map(e=>t.white.bold(` ${e}`))].join(`
127
- `)})}};const spawnPromised=async(e,t,n,{forwardSignals:r}={})=>{let i=normalizeExecutablePath(e);cliDebugPrint(`spawnPromised`,{escapedCommand:i,args:t,opts:n,forwardSignals:r});let a=st(i,t,{shell:!0,windowsHide:!0,env:n.env,cwd:n.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(r?.length)for(let e of r){let handler=()=>{a.kill(e)};process.on(e,handler),s.push(()=>process.off(e,handler))}try{return await et.fromAsync(a.catch(t=>{let n;throw n=t.exitCode==null?t.signal?`${e} exited due to signal ${t.signal}`:t.shortMessage:`${e} exited with code ${t.exitCode}`,Error(n,{cause:t})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const $=useCLIMetadata();function isInstalledOnMusl(){return $.platform===`linux`?v(`/etc/alpine-release`):!1}function isInstalledOnBaseline(){return $.platform===`darwin`&&$.arch===`x64`?!Te(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):$.platform===`linux`&&$.arch===`x64`?!S(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):$.platform===`windows`?$.arch===`arm64`?!0:Te(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:`utf-8`,windowsHide:!0}).trim().toLowerCase()===`true`:!1}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":hn}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{let[n,r,i,c,l,u]=e.name.replace(t,`version`).replace(`.exe`,``).split(`-`);return i!==$.platform||c!==$.arch?!1:a?l===`musl`:s?u===`baseline`||l===`baseline`:!l&&!u});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Cr={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},wr=`1.0.1`,Tr=`https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1`;var UpgradeCommand=class extends ApifyCommand{static name=`upgrade`;static description=`Checks that installed Apify CLI version is up to date.`;static group=`Utilities`;static examples=[{description:`Check for a newer CLI version and upgrade if available.`,command:`apify upgrade`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-upgrade`;static hidden=!0;static aliases=[`cv`,`check-version`];static flags={force:Y.boolean({description:`[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.`,required:!1,char:`f`}),version:Y.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":Y.boolean({description:`Whether the command was called automatically by the CLI for a version check.`,hidden:!0,default:!1})};get cliName(){return this.entrypoint===`apify`?`Apify CLI`:`Actor CLI`}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=Cr[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
128
- `)})}async handleInstallSpecificVersion(e){if(e!==`latest`&&!u(e,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let t=await useCLIVersionAssets(e);if(!t){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:n,version:r}=t;if(!u(r,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let i=useCLIMetadata();if(i.installMethod===`bundle`){if(!n.length){error({message:[`Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
129
+ `)})}};const spawnPromised=async(e,t,n,{forwardSignals:r}={})=>{let i=normalizeExecutablePath(e);cliDebugPrint(`spawnPromised`,{escapedCommand:i,args:t,opts:n,forwardSignals:r});let a=st(i,t,{shell:!0,windowsHide:!0,env:n.env,cwd:n.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(r?.length)for(let e of r){let handler=()=>{a.kill(e)};process.on(e,handler),s.push(()=>process.off(e,handler))}try{return await et.fromAsync(a.catch(t=>{let n;throw n=t.exitCode==null?t.signal?`${e} exited due to signal ${t.signal}`:t.shortMessage:`${e} exited with code ${t.exitCode}`,Error(n,{cause:t})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const $=useCLIMetadata();function isInstalledOnMusl(){return $.platform===`linux`?v(`/etc/alpine-release`):!1}function isInstalledOnBaseline(){return $.platform===`darwin`&&$.arch===`x64`?!Te(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):$.platform===`linux`&&$.arch===`x64`?!S(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):$.platform===`windows`?$.arch===`arm64`?!0:Te(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:`utf-8`,windowsHide:!0}).trim().toLowerCase()===`true`:!1}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":hn}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{let[n,r,i,c,l,u]=e.name.replace(t,`version`).replace(`.exe`,``).split(`-`);return i!==$.platform||c!==$.arch?!1:a?l===`musl`:s?u===`baseline`||l===`baseline`:!l&&!u});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Tr={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},Er=`1.0.1`,Dr=`https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1`;var UpgradeCommand=class extends ApifyCommand{static name=`upgrade`;static description=`Checks that installed Apify CLI version is up to date.`;static group=`Utilities`;static examples=[{description:`Check for a newer CLI version and upgrade if available.`,command:`apify upgrade`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-upgrade`;static hidden=!0;static aliases=[`cv`,`check-version`];static flags={force:Y.boolean({description:`[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.`,required:!1,char:`f`}),version:Y.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":Y.boolean({description:`Whether the command was called automatically by the CLI for a version check.`,hidden:!0,default:!1})};get cliName(){return this.entrypoint===`apify`?`Apify CLI`:`Actor CLI`}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=Tr[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
130
+ `)})}async handleInstallSpecificVersion(e){if(e!==`latest`&&!u(e,Er)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Er}.`});return}let t=await useCLIVersionAssets(e);if(!t){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:n,version:r}=t;if(!u(r,Er)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Er}.`});return}let i=useCLIMetadata();if(i.installMethod===`bundle`){if(!n.length){error({message:[`Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
129
131
  `)});return}let e=O(process.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,e);let t=await L(e);if(!t.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,t),error({message:[`Failed to find the currently installed ${this.cliName} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${e}`].join(`
130
- `)});return}if(i.platform===`windows`)return this.startUpgradeProcess(e,r,n);await this.handleUnixUpgrade(e,r,n),this.successMessage(r);return}let a=Cr[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${a.join(` `)}`});return}try{await execWithLog({cmd:a[0],args:a.slice(1)}),this.successMessage(r)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${a.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(e,t,n){await this.upsertUpgradeScript(e);let r=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${k(e,`upgrade.ps1`)}"`,`-ProcessId`,process.pid.toString(),`-InstallLocation`,`"${e}"`,`-Version`,`"${t}"`],i=n.map(e=>e.browser_download_url).join(`,`);r.push(`-AllUrls`,`"${i}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,r),info({message:`Starting upgrade process...`});let a=Ee(`powershell.exe`,r,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});a.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),a.unref(),process.exit(0)}),a.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(e){let t=k(e,`upgrade.ps1`);if(v(t))return;let n=useCLIMetadata(),r=await fetch(Tr,{headers:{"User-Agent":hn}});r.ok||(error({message:[`Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The system you are running on: ${n.platform} ${n.arch}`,`- The URL of the asset that failed to fetch: ${Tr}`,`- The status code of the response: ${r.status}`].join(`
132
+ `)});return}if(i.platform===`windows`)return this.startUpgradeProcess(e,r,n);await this.handleUnixUpgrade(e,r,n),this.successMessage(r);return}let a=Tr[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${a.join(` `)}`});return}try{await execWithLog({cmd:a[0],args:a.slice(1)}),this.successMessage(r)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${a.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(e,t,n){await this.upsertUpgradeScript(e);let r=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${k(e,`upgrade.ps1`)}"`,`-ProcessId`,process.pid.toString(),`-InstallLocation`,`"${e}"`,`-Version`,`"${t}"`],i=n.map(e=>e.browser_download_url).join(`,`);r.push(`-AllUrls`,`"${i}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,r),info({message:`Starting upgrade process...`});let a=Ee(`powershell.exe`,r,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});a.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),a.unref(),process.exit(0)}),a.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(e){let t=k(e,`upgrade.ps1`);if(v(t))return;let n=useCLIMetadata(),r=await fetch(Dr,{headers:{"User-Agent":hn}});r.ok||(error({message:[`Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The system you are running on: ${n.platform} ${n.arch}`,`- The URL of the asset that failed to fetch: ${Dr}`,`- The status code of the response: ${r.status}`].join(`
131
133
  `)}),process.exit(1));let i=await r.arrayBuffer();await z(t,Buffer.from(i)),cliDebugPrint(`[upgrade] downloaded upgrade script to`,t)}async handleUnixUpgrade(e,n,r){let i=useCLIMetadata();for(let a of r){let r=a.name.split(`-`)[0],s=k(e,r);info({message:`Downloading \`${r}\` binary of the Apify CLI...`});let c=await fetch(a.browser_download_url,{headers:{"User-Agent":hn}});if(!c.ok){let e=await c.text();cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:a,status:c.status,body:e}),error({message:[`Failed to fetch the ${r} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${e}`].join(`
132
134
  `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){info({message:`Would write asset ${r} to ${s}`});continue}info({message:t.gray(`Writing ${r} to ${s}...`)});let l=await c.arrayBuffer();try{let e=await Oe(s).then(e=>e.mode).catch(()=>493);await z(s,Buffer.from(l),{mode:e|448}),cliDebugPrint(`[upgrade ${r}] wrote asset to`,s)}catch(e){cliDebugPrint(`[upgrade] failed to write asset`,{error:e}),error({message:[`Failed to write the ${r} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${n}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The URL of the asset that failed to fetch: ${a.browser_download_url}`,`- The error: ${e.message}`].join(`
133
- `)})}}}};const Er=[`JavaScript`,`TypeScript`,`Python`];async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t){let n=await t;if(n instanceof Error)throw n;if(e){let t=n.templates.find(t=>t.name===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await httpsGet(n.localReadmeSuffixUrl),r=_(e,{flags:`a`});r.write(`
135
+ `)})}}}};const Or=[`JavaScript`,`TypeScript`,`Python`];async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t){let n=await t;if(n instanceof Error)throw n;if(e){let t=n.templates.find(t=>t.name===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await httpsGet(n.localReadmeSuffixUrl),r=_(e,{flags:`a`});r.write(`
134
136
 
135
137
  `),await Fe(t,r)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a}=e,s=`✅ Actor '${t}' created successfully!`;return n?s+=`\n\nNext steps:\n\ncd "${t}"\napify run`:s+=`\n\nNext steps:\n\ncd "${t}"\n${a||`install dependencies with your package manager`}\napify run`,s+=`
136
138
 
137
139
  💡 Tip: Use 'apify push' to deploy your Actor to the Apify platform
138
- 📖 Docs: https://docs.apify.com/platform/actors/development`,i&&(s+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`),r&&(s+=`\n\n${r}`),s}async function executePrompts(e){let t=await promptProgrammingLanguage();for(;;){let n=await promptTemplateDefinition(e,t);if(n){if(await promptTemplateInstallation())return n}else return executePrompts(e)}}async function promptActorName(){return await Fn({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptProgrammingLanguage(){return await vr({message:`Choose the programming language of your new Actor:`,choices:Er,loop:!1,default:Er[0]})}async function promptTemplateDefinition(e,t){let n=[...e.templates.filter(e=>e.category.toLowerCase()===t.toLowerCase()).map(e=>({name:e.label,value:e})),new ut,{name:`Go back`,value:!1}];return await vr({message:`Choose a template for your new Actor. You can check more information at https://apify.com/templates.`,default:n[0],choices:n,loop:!1,pageSize:8})}async function promptTemplateInstallation(){let e=[{name:`Install dependencies`,value:!0},new ut,{name:`Go back`,value:!1}];return await vr({message:`Almost done! Last step is to install dependencies.`,default:e[0],choices:e,loop:!1})}var CreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name and template if not provided. To run non-interactively, pass the name as a positional argument and --template.`;static examples=[{description:`Create a new Actor project interactively (prompts for name and template).`,command:`apify create`},{description:`Create non-interactively with explicit name and template.`,command:`apify create my-actor --template js-crawlee-cheerio`},{description:`Create without installing dependencies (faster; run install yourself later).`,command:`apify create my-actor --template python-start --skip-dependency-install`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:Y.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${At} to find available template names.`,required:!1}),"skip-dependency-install":Y.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":Y.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":Y.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":Y.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1})};static args={actorName:Z.string({required:!1,description:`Name of the Actor and its directory.`})};async run(){let{actorName:t}=this.args,{template:n,skipDependencyInstall:r,skipGitInit:i}=this.flags,{templateArchiveUrl:a}=this.flags,s=!1,c=kt().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let l=e.cwd(),p=k(l,t);for(;;){let e=await R(p).catch(()=>null),n=e&&await L(p).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){error({message:`Cannot create new Actor, directory '${t}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),t=await ensureValidActorName(),p=k(l,t);continue}e||await F(p,{recursive:!0});break}let m=null;if(this.telemetryData.create={fromArchiveUrl:!!a},!a){let e=await getTemplateDefinition(n,c);({archiveUrl:a,messages:m}=e),this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(s=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(s=!0),await downloadAndUnzip({url:a,pathTo:p});let h=getJsonFileContent(k(p,W));await setLocalConfig(Object.assign(h||tn,{name:t}),p),await setLocalEnv(p),await createPrefilledInputFileFromInputSchema(p);let g=k(p,`package.json`);await enhanceReadmeWithLocalSuffix(k(p,`README.md`),c);let _=!1;r||await(await useCwdProject({cwd:p})).inspectAsync(async n=>{let r=f(an);if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${cn} or higher to be able to run Python Actors locally.`});break;default:}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(g,{name:t});let e=[`install`];if(s)switch(i.pmName){case`npm`:u(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`);break;default:}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:p},overrideCommand:i.pmName}),_=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python 3.9 or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}let t=k(p,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:p}}),i=(await usePythonRuntime({cwd:p,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:p}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:p}}),_=!0;break}default:}});let v={success:!0},y=await R(k(l,`.git`)).catch(()=>null);if(!i&&!y)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:p}})}catch(e){v={success:!1,error:e}}let b=_?null:await getInstallCommandSuggestion(p);simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:_,postCreate:m?.postCreate??null,gitRepositoryInitialized:!i&&!y&&v.success,installCommandSuggestion:b})}),!i&&!y&&!v.success&&(warning({message:`Failed to initialize git repository: ${v.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`}))}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getLocalUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new dataset for storing structured data on your account.`;static examples=[{description:`Create an unnamed dataset.`,command:`apify datasets create`},{description:`Create a named dataset.`,command:`apify datasets create my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-create`;static args={datasetName:Z.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const Dr={[V.JSON]:`application/json`,[V.JSONL]:`application/jsonl`,[V.CSV]:`text/csv`,[V.HTML]:`text/html`,[V.RSS]:`application/rss+xml`,[V.XML]:`application/xml`,[V.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{static name=`get-items`;static description=`Retrieves dataset items in specified format (JSON, CSV, etc).`;static examples=[{description:`Print all items from a dataset as JSON.`,command:`apify datasets get-items <datasetId>`},{description:`Export the first 100 items as CSV to a file.`,command:`apify datasets get-items <datasetId> --format csv --limit 100 > items.csv`},{description:`Paginate: skip the first 500 items, return the next 500.`,command:`apify datasets get-items <datasetId> --offset 500 --limit 500`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-get-items`;static flags={limit:Y.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:Y.integer({description:`The offset in the dataset where to start getting items.`}),format:Y.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(Dr),default:V.JSON})};static args={datasetId:Z.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:Dr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
139
- `)}async tryToGetDataset(e,t){let n=await e.dataset(t).get().catch(()=>void 0);if(n)return{dataset:n,datasetClient:e.dataset(n.id)};let r=await getLocalUserInfo(),i=await e.dataset(`${r.username}/${t}`).get().catch(()=>void 0);return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};function getUserPlanPricing(e){let t=Reflect.get(e,`planPricing`);return t?Reflect.get(t,`chargeableServiceUnitPricesUsd`):null}const Or=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var DatasetsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about a specific dataset.`;static examples=[{description:`Show dataset metadata (item count, size, timestamps).`,command:`apify datasets info <datasetId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-info`;static args={storeId:Z.string({description:`The dataset store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetDataset(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=(i.cleanItemCount||0).toLocaleString(`en-US`),h=(i.itemCount||0).toLocaleString(`en-US`),g=[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`],_=`Items: ${t.bold(m)} ${t.gray(`clean`)} / ${t.bold(h)} ${t.gray(`total`)}\nOperations: ${g.join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;_+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else _+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})}`;let v=[`Dataset ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
140
+ 📖 Docs: https://docs.apify.com/platform/actors/development`,i&&(s+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`),r&&(s+=`\n\n${r}`),s}async function executePrompts(e){let t=await promptProgrammingLanguage();for(;;){let n=await promptTemplateDefinition(e,t);if(n){if(await promptTemplateInstallation())return n}else return executePrompts(e)}}async function promptActorName(){return await Fn({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptProgrammingLanguage(){return await br({message:`Choose the programming language of your new Actor:`,choices:Or,loop:!1,default:Or[0]})}async function promptTemplateDefinition(e,t){let n=[...e.templates.filter(e=>e.category.toLowerCase()===t.toLowerCase()).map(e=>({name:e.label,value:e})),new ut,{name:`Go back`,value:!1}];return await br({message:`Choose a template for your new Actor. You can check more information at https://apify.com/templates.`,default:n[0],choices:n,loop:!1,pageSize:8})}async function promptTemplateInstallation(){let e=[{name:`Install dependencies`,value:!0},new ut,{name:`Go back`,value:!1}];return await br({message:`Almost done! Last step is to install dependencies.`,default:e[0],choices:e,loop:!1})}var CreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name and template if not provided. To run non-interactively, pass the name as a positional argument and --template.`;static examples=[{description:`Create a new Actor project interactively (prompts for name and template).`,command:`apify create`},{description:`Create non-interactively with explicit name and template.`,command:`apify create my-actor --template js-crawlee-cheerio`},{description:`Create without installing dependencies (faster; run install yourself later).`,command:`apify create my-actor --template python-start --skip-dependency-install`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:Y.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${At} to find available template names.`,required:!1}),"skip-dependency-install":Y.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":Y.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":Y.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":Y.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1})};static args={actorName:Z.string({required:!1,description:`Name of the Actor and its directory.`})};async run(){let{actorName:t}=this.args,{template:n,skipDependencyInstall:r,skipGitInit:i}=this.flags,{templateArchiveUrl:a}=this.flags,s=!1,c=kt().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let l=e.cwd(),p=k(l,t);for(;;){let e=await R(p).catch(()=>null),n=e&&await L(p).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){error({message:`Cannot create new Actor, directory '${t}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),t=await ensureValidActorName(),p=k(l,t);continue}e||await F(p,{recursive:!0});break}let m=null;if(this.telemetryData.create={fromArchiveUrl:!!a},!a){let e=await getTemplateDefinition(n,c);({archiveUrl:a,messages:m}=e),this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(s=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(s=!0),await downloadAndUnzip({url:a,pathTo:p});let h=getJsonFileContent(k(p,W));await setLocalConfig(Object.assign(h||tn,{name:t}),p),await setLocalEnv(p),await createPrefilledInputFileFromInputSchema(p);let g=k(p,`package.json`);await enhanceReadmeWithLocalSuffix(k(p,`README.md`),c);let _=!1;r||await(await useCwdProject({cwd:p})).inspectAsync(async n=>{let r=f(an);if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${cn} or higher to be able to run Python Actors locally.`});break;default:}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(g,{name:t});let e=[`install`];if(s)switch(i.pmName){case`npm`:u(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`);break;default:}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:p},overrideCommand:i.pmName}),_=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python 3.9 or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python 3.9 or higher to be able to run Python Actors locally.`});return}let t=k(p,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:p}}),i=(await usePythonRuntime({cwd:p,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:p}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:p}}),_=!0;break}default:}});let v={success:!0},y=await R(k(l,`.git`)).catch(()=>null);if(!i&&!y)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:p}})}catch(e){v={success:!1,error:e}}let b=_?null:await getInstallCommandSuggestion(p);simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:_,postCreate:m?.postCreate??null,gitRepositoryInitialized:!i&&!y&&v.success,installCommandSuggestion:b})}),!i&&!y&&!v.success&&(warning({message:`Failed to initialize git repository: ${v.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`}))}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getLocalUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new dataset for storing structured data on your account.`;static examples=[{description:`Create an unnamed dataset.`,command:`apify datasets create`},{description:`Create a named dataset.`,command:`apify datasets create my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-create`;static args={datasetName:Z.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const kr={[V.JSON]:`application/json`,[V.JSONL]:`application/jsonl`,[V.CSV]:`text/csv`,[V.HTML]:`text/html`,[V.RSS]:`application/rss+xml`,[V.XML]:`application/xml`,[V.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{static name=`get-items`;static description=`Retrieves dataset items in specified format (JSON, CSV, etc).`;static examples=[{description:`Print all items from a dataset as JSON.`,command:`apify datasets get-items <datasetId>`},{description:`Export the first 100 items as CSV to a file.`,command:`apify datasets get-items <datasetId> --format csv --limit 100 > items.csv`},{description:`Paginate: skip the first 500 items, return the next 500.`,command:`apify datasets get-items <datasetId> --offset 500 --limit 500`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-get-items`;static flags={limit:Y.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:Y.integer({description:`The offset in the dataset where to start getting items.`}),format:Y.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(kr),default:V.JSON})};static args={datasetId:Z.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:kr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
141
+ `)}async tryToGetDataset(e,t){let n=await e.dataset(t).get().catch(()=>void 0);if(n)return{dataset:n,datasetClient:e.dataset(n.id)};let r=await getLocalUserInfo(),i=await e.dataset(`${r.username}/${t}`).get().catch(()=>void 0);return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};function getUserPlanPricing(e){let t=Reflect.get(e,`planPricing`);return t?Reflect.get(t,`chargeableServiceUnitPricesUsd`):null}const Ar=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var DatasetsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about a specific dataset.`;static examples=[{description:`Show dataset metadata (item count, size, timestamps).`,command:`apify datasets info <datasetId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-info`;static args={storeId:Z.string({description:`The dataset store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetDataset(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=(i.cleanItemCount||0).toLocaleString(`en-US`),h=(i.itemCount||0).toLocaleString(`en-US`),g=[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`],_=`Items: ${t.bold(m)} ${t.gray(`clean`)} / ${t.bold(h)} ${t.gray(`total`)}\nOperations: ${g.join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;_+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else _+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})}`;let v=[`Dataset ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
140
142
  `),y=t.bold(`—`);i.actRunId&&(y=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let b=t.bold(`—`);s&&(b=t.blue(s.title||s.name));let x=t.bold(`—`);l&&(x=t.blue(l.title||l.name));let S=[`Run: ${y}`,`Actor: ${b}`,`Task: ${x}`].join(`
141
- `);Or.pushRow({Row1:v,Row2:S});let C=Or.render(2).split(`
143
+ `);Ar.pushRow({Row1:v,Row2:S});let C=Ar.render(2).split(`
142
144
  `).map(e=>e.trim());C.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,C.join(`
143
145
  `),``,_].join(`
144
- `),stdout:!0})}};const kr=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints all datasets on your account.`;static examples=[{description:`List your datasets (most recently modified first).`,command:`apify datasets ls --desc`},{description:`List only unnamed (auto-generated) datasets.`,command:`apify datasets ls --unnamed`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-ls`;static flags={offset:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any Datasets on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);kr.pushRow({"Dataset ID":e.id,Created:G.display(e.createdAt),Items:`${e.itemCount}`,Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:kr.render(1),stdout:!0})}},DatasetsPushDataCommand=class extends ApifyCommand{static name=`push-items`;static description=`Adds data items to specified dataset. Accepts single object or array of objects.`;static examples=[{description:`Push a single item as an inline JSON argument.`,command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:`Push an array of items from stdin.`,command:`cat ./items.json | apify datasets push-items my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-push-items`;static args={nameOrId:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||pn;if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{static name=`rename`;static description=`Change the dataset name or remove the name with --unname flag.`;static examples=[{description:`Rename a dataset.`,command:`apify datasets rename old-name new-name`},{description:`Remove the name from a dataset (makes it unnamed).`,command:`apify datasets rename my-dataset --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes a dataset.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a dataset by name or ID (prompts for confirmation).`,command:`apify datasets rm my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rm`;static args={datasetNameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,providedConfirmFromStdin:n||void 0})){info({message:`Dataset deletion has been aborted.`});return}let{id:i,name:a}=r.dataset;try{await r.datasetClient.delete(),success({message:`Dataset with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete dataset with ID ${t.yellow(i)}\n ${n.message||n}`})}}},DatasetsIndexCommand=class extends ApifyCommand{static name=`datasets`;static description=`Manage Apify datasets — create, list, rename, delete, push items, and download items in various formats.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets`;static subcommands=[DatasetsCreateCommand,DatasetsGetItems,DatasetsLsCommand,DatasetsInfoCommand,DatasetsRmCommand,DatasetsRenameCommand,DatasetsPushDataCommand];async run(){this.printHelp()}};const Ar=`https://apify.github.io/input-schema-editor-react/`,jr=new URL(Ar).origin;var EditInputSchemaCommand=class extends ApifyCommand{static name=`edit-input-schema`;static description=`Lets you edit your input schema that would be used on the platform in a visual input schema editor.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Opens a browser-based schema editor. Requires a local display; cannot be run headlessly.`;static examples=[{description:`Edit the input schema of the Actor in the current directory.`,command:`apify edit-input-schema`},{description:`Edit a specific INPUT_SCHEMA.json file.`,command:`apify edit-input-schema ./.actor/INPUT_SCHEMA.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-edit-input-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used.`})};static hidden=!0;static aliases=[`eis`];async run(){let{inputSchema:e,inputSchemaPath:t}=await readInputSchema({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw Error(`Editing an input schema directly embedded in '${W}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
145
- `}),info({message:`Editing input schema at "${t}"...`});let n,r=Pt();r.use(Nt({origin:jr,allowedHeaders:[`Content-Type`,`Authorization`]})),r.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),r.use(Pt.json());let i=we();r.use((e,t,n)=>{let{token:r}=e.query;if(!r){let t=e.get(`Authorization`);if(t){let[e,n,...i]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&i.length===0&&(r=n)}}r===i?n():(t.status(401),t.send(`Authorization failed`))});let a=Pt.Router();r.use(`/api/v1`,a);let s=` `,c=!0;a.get(`/input-schema`,(e,n)=>{let r;try{r=v(t)?S(t,{encoding:`utf-8`}):`{}
146
+ `),stdout:!0})}};const jr=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints all datasets on your account.`;static examples=[{description:`List your datasets (most recently modified first).`,command:`apify datasets ls --desc`},{description:`List only unnamed (auto-generated) datasets.`,command:`apify datasets ls --unnamed`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-ls`;static flags={offset:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any Datasets on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);jr.pushRow({"Dataset ID":e.id,Created:G.display(e.createdAt),Items:`${e.itemCount}`,Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:jr.render(1),stdout:!0})}},DatasetsPushDataCommand=class extends ApifyCommand{static name=`push-items`;static description=`Adds data items to specified dataset. Accepts single object or array of objects.`;static examples=[{description:`Push a single item as an inline JSON argument.`,command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:`Push an array of items from stdin.`,command:`cat ./items.json | apify datasets push-items my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-push-items`;static args={nameOrId:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||pn;if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{static name=`rename`;static description=`Change the dataset name or remove the name with --unname flag.`;static examples=[{description:`Rename a dataset.`,command:`apify datasets rename old-name new-name`},{description:`Remove the name from a dataset (makes it unnamed).`,command:`apify datasets rename my-dataset --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes a dataset.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a dataset by name or ID (prompts for confirmation).`,command:`apify datasets rm my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rm`;static args={datasetNameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,providedConfirmFromStdin:n||void 0})){info({message:`Dataset deletion has been aborted.`});return}let{id:i,name:a}=r.dataset;try{await r.datasetClient.delete(),success({message:`Dataset with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete dataset with ID ${t.yellow(i)}\n ${n.message||n}`})}}},DatasetsIndexCommand=class extends ApifyCommand{static name=`datasets`;static description=`Manage Apify datasets — create, list, rename, delete, push items, and download items in various formats.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets`;static subcommands=[DatasetsCreateCommand,DatasetsGetItems,DatasetsLsCommand,DatasetsInfoCommand,DatasetsRmCommand,DatasetsRenameCommand,DatasetsPushDataCommand];async run(){this.printHelp()}};const Mr=`https://apify.github.io/input-schema-editor-react/`,Nr=new URL(Mr).origin;var EditInputSchemaCommand=class extends ApifyCommand{static name=`edit-input-schema`;static description=`Lets you edit your input schema that would be used on the platform in a visual input schema editor.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Opens a browser-based schema editor. Requires a local display; cannot be run headlessly.`;static examples=[{description:`Edit the input schema of the Actor in the current directory.`,command:`apify edit-input-schema`},{description:`Edit a specific INPUT_SCHEMA.json file.`,command:`apify edit-input-schema ./.actor/INPUT_SCHEMA.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-edit-input-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used.`})};static hidden=!0;static aliases=[`eis`];async run(){let{inputSchema:e,inputSchemaPath:t}=await readInputSchema({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw Error(`Editing an input schema directly embedded in '${W}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
147
+ `}),info({message:`Editing input schema at "${t}"...`});let n,r=Pt();r.use(Nt({origin:Nr,allowedHeaders:[`Content-Type`,`Authorization`]})),r.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),r.use(Pt.json());let i=we();r.use((e,t,n)=>{let{token:r}=e.query;if(!r){let t=e.get(`Authorization`);if(t){let[e,n,...i]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&i.length===0&&(r=n)}}r===i?n():(t.status(401),t.send(`Authorization failed`))});let a=Pt.Router();r.use(`/api/v1`,a);let s=` `,c=!0;a.get(`/input-schema`,(e,n)=>{let r;try{r=v(t)?S(t,{encoding:`utf-8`}):`{}
146
148
  `,r.length>3&&(s=zt(r).indent||s),r&&(c=r[r.length-1]===`
147
149
  `),v(t)?info({message:`Input schema loaded from "${t}"`}):info({message:`Empty input schema initialized.`})}catch(e){let t=`Reading input schema from disk failed with: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}let i;try{i=JSON.parse(r||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(i),info({message:`Input schema sent to editor.`})}),a.post(`/input-schema`,(e,n)=>{try{info({message:`Got input schema from editor...`});let r=e.body,i=JSON.stringify(r,null,s);c&&(i+=`
148
- `);let a=O(t);v(a)||b(a,{recursive:!0}),E(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${Ar}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Ot(u)}},HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.string({required:!1,description:`The command to get help for.`,catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
149
- `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const Mr=[`.dockerignore`,`.gitignore`],Nr=Bt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Vt.walk(e,async(r,i,a)=>{if(i===e)return;let s=ae(e,i),c=s.split(j).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(j),l=k(t,c);if(a.isDirectory())return v(l)||b(l),merge(i,l);s.includes(`.template`)?E(k(t,c.replace(`.template`,``)),Ht.compile(S(i,`utf8`))(n.bindings)):v(l)&&Mr.includes(re(c))?m(l,S(i)):g(i,l)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await vr({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${ae(e,t).split(j).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await kt(jt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);v(Nr)&&w(Nr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Nr}),info({message:`Wrapping the Scrapy project...`}),await merge(Nr,e,{bindings:r});let s=new it;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=_(k(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
150
+ `);let a=O(t);v(a)||b(a,{recursive:!0}),E(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${Mr}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Ot(u)}},HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.string({required:!1,description:`The command to get help for.`,catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
151
+ `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const Pr=[`.dockerignore`,`.gitignore`],Fr=Bt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Vt.walk(e,async(r,i,a)=>{if(i===e)return;let s=ae(e,i),c=s.split(j).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(j),l=k(t,c);if(a.isDirectory())return v(l)||b(l),merge(i,l);s.includes(`.template`)?E(k(t,c.replace(`.template`,``)),Ht.compile(S(i,`utf8`))(n.bindings)):v(l)&&Pr.includes(re(c))?m(l,S(i)):g(i,l)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await br({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${ae(e,t).split(j).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await kt(jt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);v(Fr)&&w(Fr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Fr}),info({message:`Wrapping the Scrapy project...`}),await merge(Fr,e,{bindings:r});let s=new it;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=_(k(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
150
152
  `,()=>{s.write(t),e()})})}),success({message:`The Scrapy project has been wrapped successfully.`})}var WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
151
153
 
152
154
  It adds the following features:
@@ -156,17 +158,17 @@ It adds the following features:
156
158
  ...
157
159
  `;static args={path:Z.string({required:!1,description:`Optional path to your scrapy project. If not provided, the current directory is used.`})};static hidden=!0;async run(){await wrapScrapyProject({projectPath:this.args.path}),info({message:`Scrapy project wrapped successfully.`})}},InitCommand=class extends ApifyCommand{static name=`init`;static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
158
160
  If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
159
- Creates the '${W}' file and the '${en}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${en}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=re(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${W}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await Fn({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...tn,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n)){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(!await X({message:`Are you sure you want to delete this record?`,providedConfirmFromStdin:r||void 0})){info({message:`Key-value store record deletion aborted.`,stdout:!0});return}try{await a.deleteRecord(n),info({message:`Record with key "${t.yellow(n)}" deleted from the key-value store.`,stdout:!0})}catch(e){let t=e;error({message:`Failed to delete record with key "${n}" from the key-value store.\n ${t.message||t}`})}}},KeyValueStoresGetValueCommand=class extends ApifyCommand{static name=`get-value`;static description=`Retrieves stored value for specified key. Use --only-content-type to check MIME type.`;static examples=[{description:`Read a record value and print it to stdout.`,command:`apify key-value-stores get-value <storeId> INPUT`},{description:`Print only the record content-type.`,command:`apify key-value-stores get-value <storeId> INPUT --only-content-type`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value`;static flags={"only-content-type":Y.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Z.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:n}=this.args,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),t);if(!r){error({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.getRecord(n,{stream:!0});if(!a){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(simpleLog({message:a.contentType??`application/octet-stream`}),e){a.value.destroy();return}if(a.contentType?.includes(`application/json`)){let{value:e}=a,t=[];for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();try{let e=JSON.parse(n);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:n,stdout:!0})}return}a.value.pipe(process.stdout)}};const Pr=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var KeyValueStoresInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Shows information about a key-value store.`;static examples=[{description:`Show metadata about a key-value store.`,command:`apify key-value-stores info <storeId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info`;static args={storeId:Z.string({description:`The key-value store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetKeyValueStore(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=i.stats?.deleteCount||0,h=i.stats?.listCount||0,g=`Operations: ${[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`,`${t.bold(m.toLocaleString(`en-US`))} ${t.gray(this.pluralString(m,`delete`,`deletes`))}`,`${t.bold(h.toLocaleString(`en-US`))} ${t.gray(this.pluralString(h,`list`,`lists`))}`].join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`$unknown per month`)}`;let _=[`Store ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
161
+ Creates the '${W}' file and the '${en}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${en}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=re(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${W}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await Fn({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...tn,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n)){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(!await X({message:`Are you sure you want to delete this record?`,providedConfirmFromStdin:r||void 0})){info({message:`Key-value store record deletion aborted.`,stdout:!0});return}try{await a.deleteRecord(n),info({message:`Record with key "${t.yellow(n)}" deleted from the key-value store.`,stdout:!0})}catch(e){let t=e;error({message:`Failed to delete record with key "${n}" from the key-value store.\n ${t.message||t}`})}}},KeyValueStoresGetValueCommand=class extends ApifyCommand{static name=`get-value`;static description=`Retrieves stored value for specified key. Use --only-content-type to check MIME type.`;static examples=[{description:`Read a record value and print it to stdout.`,command:`apify key-value-stores get-value <storeId> INPUT`},{description:`Print only the record content-type.`,command:`apify key-value-stores get-value <storeId> INPUT --only-content-type`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value`;static flags={"only-content-type":Y.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Z.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:n}=this.args,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),t);if(!r){error({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.getRecord(n,{stream:!0});if(!a){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(simpleLog({message:a.contentType??`application/octet-stream`}),e){a.value.destroy();return}if(a.contentType?.includes(`application/json`)){let{value:e}=a,t=[];for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();try{let e=JSON.parse(n);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:n,stdout:!0})}return}a.value.pipe(process.stdout)}};const Ir=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var KeyValueStoresInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Shows information about a key-value store.`;static examples=[{description:`Show metadata about a key-value store.`,command:`apify key-value-stores info <storeId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info`;static args={storeId:Z.string({description:`The key-value store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetKeyValueStore(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=i.stats?.deleteCount||0,h=i.stats?.listCount||0,g=`Operations: ${[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`,`${t.bold(m.toLocaleString(`en-US`))} ${t.gray(this.pluralString(m,`delete`,`deletes`))}`,`${t.bold(h.toLocaleString(`en-US`))} ${t.gray(this.pluralString(h,`list`,`lists`))}`].join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`$unknown per month`)}`;let _=[`Store ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
160
162
  `),v=t.bold(`—`);i.actRunId&&(v=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let y=t.bold(`—`);s&&(y=t.blue(s.title||s.name));let b=t.bold(`—`);l&&(b=t.blue(l.title||l.name));let x=[`Run: ${v}`,`Actor: ${y}`,`Task: ${b}`].join(`
161
- `);Pr.pushRow({Row1:_,Row2:x});let S=Pr.render(2).split(`
163
+ `);Ir.pushRow({Row1:_,Row2:x});let S=Ir.render(2).split(`
162
164
  `).map(e=>e.trim());S.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,S.join(`
163
165
  `),``,g].join(`
164
- `),stdout:!0})}};const Fr=new Q({allColumns:[`Key`,`Size`],mandatoryColumns:[`Key`,`Size`]});var KeyValueStoresKeysCommand=class extends ApifyCommand{static name=`keys`;static description=`Lists all keys in a key-value store.`;static examples=[{description:`List the first 20 keys in a key-value store.`,command:`apify key-value-stores keys <storeId>`},{description:`Paginate keys past an exclusive start key.`,command:`apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys`;static flags={limit:Y.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":Y.string({description:`The key to start the list from.`})};static args={storeId:Z.string({description:`The key-value store ID to list keys for.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.listKeys({limit:t,exclusiveStartKey:n});if(this.flags.json){printJsonToStdout(a);return}for(let e of a.items)Fr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Fr.render(1),stdout:!0})}};const Ir=new Q({allColumns:[`Store ID`,`Name`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Store ID`,`Name`,`Size`]});var KeyValueStoresLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all key-value stores on your account.`;static examples=[{description:`List your key-value stores.`,command:`apify key-value-stores ls`},{description:`List the next page of stores, sorted descending.`,command:`apify key-value-stores ls --limit 50 --offset 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls`;static flags={offset:Y.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:Y.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists key-value stores that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.keyValueStores().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any key-value stores on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e,`stats`).s3StorageBytes;Ir.pushRow({"Store ID":e.id,Created:G.display(e.createdAt),Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:Ir.render(1),stdout:!0})}},KeyValueStoresRenameCommand=class extends ApifyCommand{static name=`rename`;static description=`Renames a key-value store, or removes its unique name.`;static examples=[{description:`Rename a key-value store.`,command:`apify key-value-stores rename old-name new-name`},{description:`Remove the name from a key-value store.`,command:`apify key-value-stores rename my-store --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the key-value store.`})};async run(){let{unname:e}=this.flags,{newName:n,keyValueStoreNameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),r);if(!i){error({message:`Key-value store with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.keyValueStore,c=s?e?`The name of the key-value store with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the key-value store with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the key-value store with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.keyValueStoreClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename key-value store with ID ${t.yellow(a)}\n ${n.message||n}`})}}},KeyValueStoresRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a key-value store (prompts for confirmation).`,command:`apify key-value-stores rm my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm`;static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Key-value store?`,providedConfirmFromStdin:n||void 0})){info({message:`Key-value store deletion has been aborted.`});return}let{id:i,name:a}=r.keyValueStore;try{await r.keyValueStoreClient.delete(),success({message:`Key-value store with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete key-value store with ID ${t.yellow(i)}\n ${n.message||n}`})}}},KeyValueStoresSetValueCommand=class extends ApifyCommand{static name=`set-value`;static description=`Stores value with specified key. Set content-type with --content-type flag.`;static examples=[{description:`Store a JSON value under a key.`,command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:`Store a plain-text file read from stdin.`,command:`cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value`;static flags={"content-type":Y.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Z.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0}),value:Z.string({description:`The value to set.`})};async run(){let{storeId:e,itemKey:t,value:n}=this.args,{contentType:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;try{await a.setRecord({key:t,value:n||process.stdin,contentType:r}),success({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to set value with key "${t}" in the key-value store.\n ${n.message||n}`})}}},KeyValueStoresIndexCommand=class extends ApifyCommand{static name=`key-value-stores`;static description=`Manage Apify key-value stores — create, list, rename, delete stores, and get/set/delete individual records.
166
+ `),stdout:!0})}};const Lr=new Q({allColumns:[`Key`,`Size`],mandatoryColumns:[`Key`,`Size`]});var KeyValueStoresKeysCommand=class extends ApifyCommand{static name=`keys`;static description=`Lists all keys in a key-value store.`;static examples=[{description:`List the first 20 keys in a key-value store.`,command:`apify key-value-stores keys <storeId>`},{description:`Paginate keys past an exclusive start key.`,command:`apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys`;static flags={limit:Y.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":Y.string({description:`The key to start the list from.`})};static args={storeId:Z.string({description:`The key-value store ID to list keys for.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.listKeys({limit:t,exclusiveStartKey:n});if(this.flags.json){printJsonToStdout(a);return}for(let e of a.items)Lr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Lr.render(1),stdout:!0})}};const Rr=new Q({allColumns:[`Store ID`,`Name`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Store ID`,`Name`,`Size`]});var KeyValueStoresLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all key-value stores on your account.`;static examples=[{description:`List your key-value stores.`,command:`apify key-value-stores ls`},{description:`List the next page of stores, sorted descending.`,command:`apify key-value-stores ls --limit 50 --offset 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls`;static flags={offset:Y.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:Y.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists key-value stores that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.keyValueStores().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any key-value stores on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e,`stats`).s3StorageBytes;Rr.pushRow({"Store ID":e.id,Created:G.display(e.createdAt),Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:Rr.render(1),stdout:!0})}},KeyValueStoresRenameCommand=class extends ApifyCommand{static name=`rename`;static description=`Renames a key-value store, or removes its unique name.`;static examples=[{description:`Rename a key-value store.`,command:`apify key-value-stores rename old-name new-name`},{description:`Remove the name from a key-value store.`,command:`apify key-value-stores rename my-store --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the key-value store.`})};async run(){let{unname:e}=this.flags,{newName:n,keyValueStoreNameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),r);if(!i){error({message:`Key-value store with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.keyValueStore,c=s?e?`The name of the key-value store with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the key-value store with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the key-value store with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.keyValueStoreClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename key-value store with ID ${t.yellow(a)}\n ${n.message||n}`})}}},KeyValueStoresRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a key-value store (prompts for confirmation).`,command:`apify key-value-stores rm my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm`;static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Key-value store?`,providedConfirmFromStdin:n||void 0})){info({message:`Key-value store deletion has been aborted.`});return}let{id:i,name:a}=r.keyValueStore;try{await r.keyValueStoreClient.delete(),success({message:`Key-value store with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete key-value store with ID ${t.yellow(i)}\n ${n.message||n}`})}}},KeyValueStoresSetValueCommand=class extends ApifyCommand{static name=`set-value`;static description=`Stores value with specified key. Set content-type with --content-type flag.`;static examples=[{description:`Store a JSON value under a key.`,command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:`Store a plain-text file read from stdin.`,command:`cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value`;static flags={"content-type":Y.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Z.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0}),value:Z.string({description:`The value to set.`})};async run(){let{storeId:e,itemKey:t,value:n}=this.args,{contentType:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;try{await a.setRecord({key:t,value:n||process.stdin,contentType:r}),success({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to set value with key "${t}" in the key-value store.\n ${n.message||n}`})}}},KeyValueStoresIndexCommand=class extends ApifyCommand{static name=`key-value-stores`;static description=`Manage Apify key-value stores — create, list, rename, delete stores, and get/set/delete individual records.
165
167
 
166
168
  Alias: kvs.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores`;static hiddenAliases=[`kvs`];static subcommands=[KeyValueStoresCreateCommand,KeyValueStoresDeleteValueCommand,KeyValueStoresGetValueCommand,KeyValueStoresInfoCommand,KeyValueStoresKeysCommand,KeyValueStoresLsCommand,KeyValueStoresRenameCommand,KeyValueStoresRmCommand,KeyValueStoresSetValueCommand];async run(){this.printHelp()}},LoginCommand=class extends AuthLoginCommand{static name=`login`},LogoutCommand=class extends AuthLogoutCommand{static name=`logout`};async function confirmOverwrite({filePath:e,entryKey:t,yes:n}){return X({message:`A server entry named '${t}' already exists in ${tildify(e)}. Overwrite it?`,default:!1,providedConfirmFromStdin:n||void 0,errorMessageForStdin:`An '${t}' entry already exists in ${tildify(e)}. Re-run with --yes to overwrite.`})}async function mergeServerEntry({filePath:t,topLevelKey:n,entryKey:r,serverEntry:i,yes:a}){let s=v(t)?await I(t,`utf-8`):``,c=s.trim(),l;if(c){let e;try{e=Dt.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
167
- `)[0]:`invalid JSON`;throw Error(`Cannot install: ${tildify(t)} is not valid JSON (${n}). Fix the file manually and re-run.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Cannot install: ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let c=e[n];if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw Error(`Cannot install: '${n}' in ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let u=c??{};if(Object.prototype.hasOwnProperty.call(u,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;u[r]=i,e[n]=u,l=Dt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Dt.stringify(e,{mode:`json`,indent:2})}\n`}await F(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await z(u,l,`utf-8`),await ke(u,t)}catch(e){throw await Ae(u,{force:!0}),e}return!0}function buildMcpUrl(e,t){if(!t)return e;let n=t.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`);if(!n)return e;let r=new URL(e);return r.searchParams.set(`tools`,n),r.toString()}function maskToken(e){return e.length<=14?`***`:`${e.slice(0,10)}...${e.slice(-4)}`}function maskSecret(e,t){return t?e.split(t).join(maskToken(t)):e}const Lr=`apify`,bearer=e=>({Authorization:`Bearer ${e}`});function printResult(e){success({message:`Apify MCP server configured for ${e.clientLabel}.`});let n=[``,` ${t.yellow(`Server URL:`)} ${e.serverUrl}`,` ${t.yellow(`Auth:`)} ${e.authDescription}`];e.configPath&&n.push(` ${t.yellow(`Config:`)} ${tildify(e.configPath)}`),e.nextSteps&&n.push(``,e.nextSteps),simpleLog({message:n.join(`
168
- `)})}function isExecaError(e){return typeof e==`object`&&!!e&&`shortMessage`in e&&`command`in e}function describeExecaError(e,t){return isExecaError(e)?e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage??e.message:`${t} exited with code ${e.exitCode}`:e instanceof Error?e.message:String(e)}async function runCliInstall({binary:t,clientLabel:n,token:r,args:i,maskedCommand:a,missingMessage:s}){if(!await ct(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await st(t,i,{stdio:[`ignore`,`ignore`,`pipe`]})}catch(i){let a=isExecaError(i)?String(i.stderr??``).trim():``;return error({message:maskSecret(`Failed to add the MCP server via ${n}: ${a?`${describeExecaError(i,t)}\n${a}`:describeExecaError(i,t)}`,r)}),e.exitCode=1,!1}return!0}function fileClient({label:t,segments:n,entry:r}){return async({url:i,token:a,yes:s})=>{let c=userHomeDir();if(!c){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let l=k(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:Lr,serverEntry:r(i,a),yes:s})&&printResult({clientLabel:t,serverUrl:i,authDescription:`Bearer ${maskToken(a)}`,configPath:l})}}const claudeCodeHandler=async({url:e,token:t})=>{let command=t=>`claude mcp add --transport http --scope user ${Lr} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Lr,e,`--header`,`Authorization: Bearer ${t}`],maskedCommand:command(maskToken(t)),missingMessage:`The 'claude' CLI was not found on PATH. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) and re-run, or add the server manually:\n\n ${command(`<your-token>`)}`})&&printResult({clientLabel:`Claude Code`,serverUrl:e,authDescription:`Bearer ${maskToken(t)} (stored by Claude Code)`})};function vscodeHandler(e,t){return async({url:n,token:r})=>{let serverJson=e=>JSON.stringify({name:Lr,type:`http`,url:n,headers:{Authorization:e}});await runCliInstall({binary:e,clientLabel:t,token:r,args:[`--add-mcp`,serverJson(`Bearer ${r}`)],maskedCommand:`${e} --add-mcp '${serverJson(`Bearer ${maskToken(r)}`)}'`,missingMessage:`The '${e}' CLI was not found on PATH. Install ${t} and re-run, or add the server manually:\n\n ${e} --add-mcp '${serverJson(`Bearer <your-token>`)}'`})&&printResult({clientLabel:t,serverUrl:n,authDescription:`Bearer ${maskToken(r)} (stored by ${t})`})}}const codexHandler=async({url:n})=>{let r=userHomeDir();if(!r){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let i=k(r,`.codex`,`config.toml`),a=[`mcp`,`add`,Lr,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Lr}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
169
- `);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},Rr={"claude-code":claudeCodeHandler,cursor:fileClient({label:`Cursor`,segments:[`.cursor`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t)})}),vscode:vscodeHandler(`code`,`VS Code`),"vscode-insiders":vscodeHandler(`code-insiders`,`VS Code Insiders`),codex:codexHandler,kiro:fileClient({label:`Kiro`,segments:[`.kiro`,`settings`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t),disabled:!1,autoApprove:[]})}),antigravity:fileClient({label:`Antigravity`,segments:[`.gemini`,`antigravity`,`mcp_config.json`],entry:(e,t)=>({serverUrl:e,headers:bearer(t)})})},zr=Object.keys(Rr);function isSupportedClient(e){return e in Rr}const Br=new Set([`codex`]);function clientNeedsToken(e){return!Br.has(e)}function getClientHandler(e){return Rr[e]}async function resolveApifyToken(t){if(t)return t;if(e.env.APIFY_TOKEN)return e.env.APIFY_TOKEN;let n=await getLocalUserInfo();return n.token?n.token:(error({message:`You are not logged in to Apify. Run 'apify login' first, or pass --token <api-token>.`}),e.exitCode=1,null)}var MCPInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Configure a local MCP client to use the Apify MCP server. Writes or merges a server entry named 'apify' into the client's config file, or runs the client's own 'mcp add' command when available.`;static group=`MCP`;static interactive=!0;static interactiveNote=`Prompts before overwriting an existing JSON config entry (cursor, kiro, antigravity). Pass --yes to overwrite without prompting. For clients delegated to their own CLI (claude-code, vscode, vscode-insiders, codex), overwrite behavior is controlled by that CLI.`;static examples=[{description:`Add Apify to Claude Code using the stored API token.`,command:`apify mcp install claude-code`},{description:`Add Apify to Cursor.`,command:`apify mcp install cursor`},{description:`Add only the 'search-actors' tool and the 'apify/rag-web-browser' Actor to VS Code.`,command:`apify mcp install vscode --tools search-actors,apify/rag-web-browser`},{description:`Add Apify to Codex CLI with an explicit token (non-interactive).`,command:`apify mcp install codex --token apify_api_xxxxx --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp-install`;static args={client:Z.string({required:!0,description:`Target MCP client. One of: ${zr.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry without prompting.`),token:Y.string({char:`t`,description:`Apify API token to embed in the config. Defaults to the token from 'apify login'.`}),url:Y.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:Y.string({description:`Comma-separated tool IDs or Actor full names to expose. Forwarded as a '?tools=' query parameter.`})};async run(){let{client:t}=this.args,{token:n,url:r,tools:i,yes:a}=this.flags;if(!isSupportedClient(t)){error({message:`Unknown MCP client '${t}'. Supported clients: ${zr.join(`, `)}.`}),e.exitCode=5;return}let s=``;if(clientNeedsToken(t)){let e=await resolveApifyToken(n);if(!e)return;s=e}await getClientHandler(t)({url:buildMcpUrl(r,i),token:s,yes:a})}},MCPIndexCommand=class extends ApifyCommand{static name=`mcp`;static description=`Configure the Apify MCP server in your AI client: Claude Code, Cursor, VS Code, Codex CLI, Kiro, or Antigravity.`;static group=`MCP`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp`;static subcommands=[MCPInstallCommand];async run(){this.printHelp()}},TopLevelPullCommand=class extends ActorsPullCommand{static name=`pull`},ToplevelPushCommand=class extends ActorsPushCommand{static name=`push`},RequestQueuesIndexCommand=class extends ApifyCommand{static name=`request-queues`;static description=`Manage Apify request queues. No subcommands are available yet.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-request-queues`;async run(){this.printHelp()}};const jsScript=e=>`
169
+ `)[0]:`invalid JSON`;throw Error(`Cannot install: ${tildify(t)} is not valid JSON (${n}). Fix the file manually and re-run.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Cannot install: ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let c=e[n];if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw Error(`Cannot install: '${n}' in ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let u=c??{};if(Object.prototype.hasOwnProperty.call(u,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;u[r]=i,e[n]=u,l=Dt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Dt.stringify(e,{mode:`json`,indent:2})}\n`}await F(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await z(u,l,`utf-8`),await ke(u,t)}catch(e){throw await Ae(u,{force:!0}),e}return!0}function buildMcpUrl(e,t){if(!t)return e;let n=t.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`);if(!n)return e;let r=new URL(e);return r.searchParams.set(`tools`,n),r.toString()}function maskToken(e){return e.length<=14?`***`:`${e.slice(0,10)}...${e.slice(-4)}`}function maskSecret(e,t){return t?e.split(t).join(maskToken(t)):e}const zr=`apify`,bearer=e=>({Authorization:`Bearer ${e}`});function printResult(e){success({message:`Apify MCP server configured for ${e.clientLabel}.`});let n=[``,` ${t.yellow(`Server URL:`)} ${e.serverUrl}`,` ${t.yellow(`Auth:`)} ${e.authDescription}`];e.configPath&&n.push(` ${t.yellow(`Config:`)} ${tildify(e.configPath)}`),e.nextSteps&&n.push(``,e.nextSteps),simpleLog({message:n.join(`
170
+ `)})}function isExecaError(e){return typeof e==`object`&&!!e&&`shortMessage`in e&&`command`in e}function describeExecaError(e,t){return isExecaError(e)?e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage??e.message:`${t} exited with code ${e.exitCode}`:e instanceof Error?e.message:String(e)}async function runCliInstall({binary:t,clientLabel:n,token:r,args:i,maskedCommand:a,missingMessage:s}){if(!await ct(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await st(t,i,{stdio:[`ignore`,`ignore`,`pipe`]})}catch(i){let a=isExecaError(i)?String(i.stderr??``).trim():``;return error({message:maskSecret(`Failed to add the MCP server via ${n}: ${a?`${describeExecaError(i,t)}\n${a}`:describeExecaError(i,t)}`,r)}),e.exitCode=1,!1}return!0}function fileClient({label:t,segments:n,entry:r}){return async({url:i,token:a,yes:s})=>{let c=userHomeDir();if(!c){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let l=k(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:zr,serverEntry:r(i,a),yes:s})&&printResult({clientLabel:t,serverUrl:i,authDescription:`Bearer ${maskToken(a)}`,configPath:l})}}const claudeCodeHandler=async({url:e,token:t})=>{let command=t=>`claude mcp add --transport http --scope user ${zr} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,zr,e,`--header`,`Authorization: Bearer ${t}`],maskedCommand:command(maskToken(t)),missingMessage:`The 'claude' CLI was not found on PATH. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) and re-run, or add the server manually:\n\n ${command(`<your-token>`)}`})&&printResult({clientLabel:`Claude Code`,serverUrl:e,authDescription:`Bearer ${maskToken(t)} (stored by Claude Code)`})};function vscodeHandler(e,t){return async({url:n,token:r})=>{let serverJson=e=>JSON.stringify({name:zr,type:`http`,url:n,headers:{Authorization:e}});await runCliInstall({binary:e,clientLabel:t,token:r,args:[`--add-mcp`,serverJson(`Bearer ${r}`)],maskedCommand:`${e} --add-mcp '${serverJson(`Bearer ${maskToken(r)}`)}'`,missingMessage:`The '${e}' CLI was not found on PATH. Install ${t} and re-run, or add the server manually:\n\n ${e} --add-mcp '${serverJson(`Bearer <your-token>`)}'`})&&printResult({clientLabel:t,serverUrl:n,authDescription:`Bearer ${maskToken(r)} (stored by ${t})`})}}const codexHandler=async({url:n})=>{let r=userHomeDir();if(!r){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let i=k(r,`.codex`,`config.toml`),a=[`mcp`,`add`,zr,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${zr}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
171
+ `);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},Br={"claude-code":claudeCodeHandler,cursor:fileClient({label:`Cursor`,segments:[`.cursor`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t)})}),vscode:vscodeHandler(`code`,`VS Code`),"vscode-insiders":vscodeHandler(`code-insiders`,`VS Code Insiders`),codex:codexHandler,kiro:fileClient({label:`Kiro`,segments:[`.kiro`,`settings`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t),disabled:!1,autoApprove:[]})}),antigravity:fileClient({label:`Antigravity`,segments:[`.gemini`,`antigravity`,`mcp_config.json`],entry:(e,t)=>({serverUrl:e,headers:bearer(t)})})},Vr=Object.keys(Br);function isSupportedClient(e){return e in Br}const Hr=new Set([`codex`]);function clientNeedsToken(e){return!Hr.has(e)}function getClientHandler(e){return Br[e]}async function resolveApifyToken(t){if(t)return t;if(e.env.APIFY_TOKEN)return e.env.APIFY_TOKEN;let n=await getLocalUserInfo();return n.token?n.token:(error({message:`You are not logged in to Apify. Run 'apify login' first, or pass --token <api-token>.`}),e.exitCode=1,null)}var MCPInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Configure a local MCP client to use the Apify MCP server. Writes or merges a server entry named 'apify' into the client's config file, or runs the client's own 'mcp add' command when available.`;static group=`MCP`;static interactive=!0;static interactiveNote=`Prompts before overwriting an existing JSON config entry (cursor, kiro, antigravity). Pass --yes to overwrite without prompting. For clients delegated to their own CLI (claude-code, vscode, vscode-insiders, codex), overwrite behavior is controlled by that CLI.`;static examples=[{description:`Add Apify to Claude Code using the stored API token.`,command:`apify mcp install claude-code`},{description:`Add Apify to Cursor.`,command:`apify mcp install cursor`},{description:`Add only the 'search-actors' tool and the 'apify/rag-web-browser' Actor to VS Code.`,command:`apify mcp install vscode --tools search-actors,apify/rag-web-browser`},{description:`Add Apify to Codex CLI with an explicit token (non-interactive).`,command:`apify mcp install codex --token apify_api_xxxxx --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp-install`;static args={client:Z.string({required:!0,description:`Target MCP client. One of: ${Vr.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry without prompting.`),token:Y.string({char:`t`,description:`Apify API token to embed in the config. Defaults to the token from 'apify login'.`}),url:Y.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:Y.string({description:`Comma-separated tool IDs or Actor full names to expose. Forwarded as a '?tools=' query parameter.`})};async run(){let{client:t}=this.args,{token:n,url:r,tools:i,yes:a}=this.flags;if(!isSupportedClient(t)){error({message:`Unknown MCP client '${t}'. Supported clients: ${Vr.join(`, `)}.`}),e.exitCode=5;return}let s=``;if(clientNeedsToken(t)){let e=await resolveApifyToken(n);if(!e)return;s=e}await getClientHandler(t)({url:buildMcpUrl(r,i),token:s,yes:a})}},MCPIndexCommand=class extends ApifyCommand{static name=`mcp`;static description=`Configure the Apify MCP server in your AI client: Claude Code, Cursor, VS Code, Codex CLI, Kiro, or Antigravity.`;static group=`MCP`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp`;static subcommands=[MCPInstallCommand];async run(){this.printHelp()}},TopLevelPullCommand=class extends ActorsPullCommand{static name=`pull`},ToplevelPushCommand=class extends ActorsPushCommand{static name=`push`},RequestQueuesIndexCommand=class extends ApifyCommand{static name=`request-queues`;static description=`Manage Apify request queues. No subcommands are available yet.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-request-queues`;async run(){this.printHelp()}};const jsScript=e=>`
170
172
  (async () => {
171
173
  const [nodeModule, process, path, fs] = await Promise.all([
172
174
  import('node:module'),
@@ -204,7 +206,7 @@ try:
204
206
  print(${e}.__version__)
205
207
  except:
206
208
  print('n/a')
207
- `,Vr={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:e,project:t}){if(!t.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:t,moduleName:e}),H;let n;if(t.type===0)n=t.runtime.runtimeShorthand||`node`;else if(t.type===1||t.type===2)n=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:t,moduleName:e}),H;let r=Vr[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),H;try{let n=await st(t.runtime.executablePath,r,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:t,moduleName:e}),H):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),rt(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),H}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
209
+ `,Ur={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:e,project:t}){if(!t.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:t,moduleName:e}),H;let n;if(t.type===0)n=t.runtime.runtimeShorthand||`node`;else if(t.type===1||t.type===2)n=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:t,moduleName:e}),H;let r=Ur[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),H;try{let n=await st(t.runtime.executablePath,r,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:t,moduleName:e}),H):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),rt(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),H}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
208
210
  Stores data in local '${en}' directory.\n\nNOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static group=`Local Actor Development`;static examples=[{description:`Run the Actor in the current directory with the stored input.`,command:`apify run`},{description:`Run and purge the default storage first (dataset, request queue, key-value store).`,command:`apify run --purge`},{description:`Run with inline JSON input (overrides the stored INPUT).`,command:`apify run --input '{"startUrls":[{"url":"https://example.com"}]}'`},{description:`Run with input from a file.`,command:`apify run --input-file ./input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-run`;static flags={purge:Y.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
209
211
  For crawlee projects, this is the default behavior, and the flag is optional.
210
212
  Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:Y.boolean({description:`Whether to keep the default request queue, dataset and key-value store before the run starts.`,required:!1,default:!1,exclusive:[`purge`]}),entrypoint:Y.string({description:[`Optional entrypoint for running with injected environment variables.`,`
@@ -214,13 +216,13 @@ Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,ex
214
216
  `;break;default:u=t?`The input provided through the ${t.source} file is invalid. Please fix the following errors:\n`:`The input in your storage is invalid. Please fix the following errors:
215
217
  `;break}if(t){let e={...a,...t.input},i=xt(s,r,e);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
216
218
  `)}`);let c=`${Sn}${n}`,f=k(O(l),`${c}.json`);return await F(O(l),{recursive:!0}),await z(f,JSON.stringify(e,null,2)),{tempInputKey:c,tempInputFilePath:f}}if(!c)return await F(O(l),{recursive:!0}),await z(l,JSON.stringify(a,null,2)),{existingInput:c,inputFilePath:l,writtenAt:Date.now()};if(Je.getExtension(c.contentType)===`json`){let e=JSON.parse(c.body.toString(`utf-8`));if(Array.isArray(e))throw Error(`The input in your storage is invalid. It should be an object, not an array.`);let t={...a,...e},i=xt(s,r,t);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
217
- `)}`);let f=`${Sn}${n}`,p=k(O(l),`${f}.json`);return await z(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const Hr=[N.READY,N.RUNNING],Ur=[N.ABORTING,N.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{static name=`abort`;static description=`Aborts an Actor run.`;static examples=[{description:`Abort a running Actor gracefully (up to 30s drain).`,command:`apify runs abort <runId>`},{description:`Force-abort a running Actor immediately.`,command:`apify runs abort <runId> --force`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-abort`;static args={runId:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.boolean({description:`Whether to force the run to abort immediately, instead of gracefully.`,default:!1,char:`f`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Hr.includes(n.status)){Ur.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Wr=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),Gr={"Actor compute units":`ACTOR_COMPUTE_UNITS`,"Dataset reads":`DATASET_READS`,"Dataset writes":`DATASET_WRITES`,"Key-value store reads":`KEY_VALUE_STORE_READS`,"Key-value store writes":`KEY_VALUE_STORE_WRITES`,"Key-value store lists":`KEY_VALUE_STORE_LISTS`,"Request queue reads":`REQUEST_QUEUE_READS`,"Request queue writes":`REQUEST_QUEUE_WRITES`,"Data transfer internal":`DATA_TRANSFER_INTERNAL_GBYTES`,"Data transfer external":`DATA_TRANSFER_EXTERNAL_GBYTES`,"Proxy residential data transfer":`PROXY_RESIDENTIAL_TRANSFER_GBYTES`,"Proxy SERPs":`PROXY_SERPS`};var RunsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about an Actor run.`;static examples=[{description:`Show a summary of a run.`,command:`apify runs info <runId>`},{description:`Show verbose details including usage breakdown.`,command:`apify runs info <runId> --verbose`},{description:`Emit the full run object as JSON.`,command:`apify runs info <runId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-info`;static args={runId:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.boolean({char:`v`,description:`Prints more in-depth information about the Actor run.`,default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(Wr.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${G.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(K.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${K.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=`https://console.apify.com/actors/${r.actId}/runs/${r.id}`,_=`https://console.apify.com/storage/datasets/${r.defaultDatasetId}`,v=`https://console.apify.com/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
218
- `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(Gr))Wr.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(Gr)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:Wr.pushRow({"":e,Unit:i.toFixed(4),"USD Amount":this.formatUsd(a)});break;case`DATA_TRANSFER_INTERNAL_GBYTES`:case`DATA_TRANSFER_EXTERNAL_GBYTES`:case`PROXY_RESIDENTIAL_TRANSFER_GBYTES`:Wr.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:Wr.pushRow({"":e,Unit:i.toLocaleString(`en-US`),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}},RunsLogCommand=class extends ApifyCommand{static name=`log`;static description=`Prints the log of a specific run.`;static examples=[{description:`Print the log of a specific run to stdout.`,command:`apify runs log <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-log`;static args={runId:Z.string({required:!0,description:`The run ID to get the log from.`})};async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}info({message:`Log for run with ID "${e}":\n`,stdout:!0});try{await outputJobLog({job:n,apifyClient:t})}catch(t){error({message:`Failed to get log for run with ID "${e}": ${t.message}`})}}};const Kr=new Q({allColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`,`Build No.`,`Origin`],mandatoryColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`],columnAlignments:{Results:`right`,Usage:`right`,Took:`right`,"Build No.":`right`}});var RunsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all runs of the Actor.`;static examples=[{description:`List runs of the Actor in the current directory.`,command:`apify runs ls`},{description:`List runs of a specific Actor.`,command:`apify runs ls apify/hello-world`},{description:`List the 50 most recent runs in descending order.`,command:`apify runs ls --limit 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-ls`;static flags={offset:Y.integer({description:`Number of runs that will be skipped.`,default:0}),limit:Y.integer({description:`Number of runs that will be listed.`,default:10}),desc:Y.boolean({description:`Sort runs in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.string({description:`Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await c.actor(l.id).runs().list({desc:e,limit:n,offset:r});if(a){printJsonToStdout(u);return}if(!u.items.length){simpleLog({message:`There are no recent runs found for this Actor.`});return}let f=[`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} runs for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})`],p=new Map(await Promise.all(u.items.map(async e=>c.dataset(e.defaultDatasetId).get().then(n=>[e.id,t.yellow(n?.itemCount??0)],()=>[e.id,t.gray(`N/A`)]))));for(let e of u.items){let n;if(e.finishedAt){let r=e.finishedAt.getTime()-e.startedAt.getTime();n=t.gray(`${K.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${K.format(r,void 0,{left:``})}`)}Kr.pushRow({ID:t.gray(e.id),Status:prettyPrintStatus(e.status),Results:p.get(e.id)||t.gray(`N/A`),Usage:t.cyan(`$${(e.usageTotalUsd??0).toFixed(3)}`),"Started At":Dn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Kr.render(+!i)),simpleLog({message:f.join(`
219
- `),stdout:!0})}};const qr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{static name=`resurrect`;static description=`Resurrects an aborted or finished Actor Run.`;static examples=[{description:`Resurrect a finished or aborted run.`,command:`apify runs resurrect <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-resurrect`;static args={runId:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!qr.includes(n.status)){error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Jr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Deletes an Actor Run.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a finished or aborted run (prompts for confirmation).`,command:`apify runs rm <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-rm`;static args={runId:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}if(!Jr.includes(r.status)){error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:`Are you sure you want to delete this Actor Run?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of run "${e}" was canceled.`});return}try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor run to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
219
+ `)}`);let f=`${Sn}${n}`,p=k(O(l),`${f}.json`);return await z(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const Wr=[N.READY,N.RUNNING],Gr=[N.ABORTING,N.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{static name=`abort`;static description=`Aborts an Actor run.`;static examples=[{description:`Abort a running Actor gracefully (up to 30s drain).`,command:`apify runs abort <runId>`},{description:`Force-abort a running Actor immediately.`,command:`apify runs abort <runId> --force`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-abort`;static args={runId:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.boolean({description:`Whether to force the run to abort immediately, instead of gracefully.`,default:!1,char:`f`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Wr.includes(n.status)){Gr.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Kr=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),qr={"Actor compute units":`ACTOR_COMPUTE_UNITS`,"Dataset reads":`DATASET_READS`,"Dataset writes":`DATASET_WRITES`,"Key-value store reads":`KEY_VALUE_STORE_READS`,"Key-value store writes":`KEY_VALUE_STORE_WRITES`,"Key-value store lists":`KEY_VALUE_STORE_LISTS`,"Request queue reads":`REQUEST_QUEUE_READS`,"Request queue writes":`REQUEST_QUEUE_WRITES`,"Data transfer internal":`DATA_TRANSFER_INTERNAL_GBYTES`,"Data transfer external":`DATA_TRANSFER_EXTERNAL_GBYTES`,"Proxy residential data transfer":`PROXY_RESIDENTIAL_TRANSFER_GBYTES`,"Proxy SERPs":`PROXY_SERPS`};var RunsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about an Actor run.`;static examples=[{description:`Show a summary of a run.`,command:`apify runs info <runId>`},{description:`Show verbose details including usage breakdown.`,command:`apify runs info <runId> --verbose`},{description:`Emit the full run object as JSON.`,command:`apify runs info <runId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-info`;static args={runId:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.boolean({char:`v`,description:`Prints more in-depth information about the Actor run.`,default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(Kr.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${G.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(K.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${K.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=`https://console.apify.com/actors/${r.actId}/runs/${r.id}`,_=`https://console.apify.com/storage/datasets/${r.defaultDatasetId}`,v=`https://console.apify.com/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
220
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(qr))Kr.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(qr)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:Kr.pushRow({"":e,Unit:i.toFixed(4),"USD Amount":this.formatUsd(a)});break;case`DATA_TRANSFER_INTERNAL_GBYTES`:case`DATA_TRANSFER_EXTERNAL_GBYTES`:case`PROXY_RESIDENTIAL_TRANSFER_GBYTES`:Kr.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:Kr.pushRow({"":e,Unit:i.toLocaleString(`en-US`),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}},RunsLogCommand=class extends ApifyCommand{static name=`log`;static description=`Prints the log of a specific run.`;static examples=[{description:`Print the log of a specific run to stdout.`,command:`apify runs log <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-log`;static args={runId:Z.string({required:!0,description:`The run ID to get the log from.`})};async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}info({message:`Log for run with ID "${e}":\n`,stdout:!0});try{await outputJobLog({job:n,apifyClient:t})}catch(t){error({message:`Failed to get log for run with ID "${e}": ${t.message}`})}}};const Jr=new Q({allColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`,`Build No.`,`Origin`],mandatoryColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`],columnAlignments:{Results:`right`,Usage:`right`,Took:`right`,"Build No.":`right`}});var RunsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all runs of the Actor.`;static examples=[{description:`List runs of the Actor in the current directory.`,command:`apify runs ls`},{description:`List runs of a specific Actor.`,command:`apify runs ls apify/hello-world`},{description:`List the 50 most recent runs in descending order.`,command:`apify runs ls --limit 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-ls`;static flags={offset:Y.integer({description:`Number of runs that will be skipped.`,default:0}),limit:Y.integer({description:`Number of runs that will be listed.`,default:10}),desc:Y.boolean({description:`Sort runs in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.string({description:`Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await c.actor(l.id).runs().list({desc:e,limit:n,offset:r});if(a){printJsonToStdout(u);return}if(!u.items.length){simpleLog({message:`There are no recent runs found for this Actor.`});return}let f=[`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} runs for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})`],p=new Map(await Promise.all(u.items.map(async e=>c.dataset(e.defaultDatasetId).get().then(n=>[e.id,t.yellow(n?.itemCount??0)],()=>[e.id,t.gray(`N/A`)]))));for(let e of u.items){let n;if(e.finishedAt){let r=e.finishedAt.getTime()-e.startedAt.getTime();n=t.gray(`${K.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${K.format(r,void 0,{left:``})}`)}Jr.pushRow({ID:t.gray(e.id),Status:prettyPrintStatus(e.status),Results:p.get(e.id)||t.gray(`N/A`),Usage:t.cyan(`$${(e.usageTotalUsd??0).toFixed(3)}`),"Started At":Dn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Jr.render(+!i)),simpleLog({message:f.join(`
221
+ `),stdout:!0})}};const Yr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{static name=`resurrect`;static description=`Resurrects an aborted or finished Actor Run.`;static examples=[{description:`Resurrect a finished or aborted run.`,command:`apify runs resurrect <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-resurrect`;static args={runId:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Yr.includes(n.status)){error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Xr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Deletes an Actor Run.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a finished or aborted run (prompts for confirmation).`,command:`apify runs rm <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-rm`;static args={runId:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}if(!Xr.includes(r.status)){error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:`Are you sure you want to delete this Actor Run?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of run "${e}" was canceled.`});return}try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor run to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
220
222
  Returns exit code 0 only when the run SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a run to finish and return a non-zero exit code on failure.`,command:`apify runs wait <runId>`},{description:`Wait for a run and emit a structured JSON result.`,command:`apify runs wait <runId> --json`},{description:`Give up waiting after 5 minutes. Reports the real current status and exits with code 6 if the run is still running.`,command:`apify runs wait <runId> --timeout 300`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-wait`;static enableJsonFlag=!0;static args={runId:Z.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`How often to poll the platform, in seconds. Defaults to 2.`,required:!1})};async run(){let{runId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`run`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleRunUrl(l.actId,l.id),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`run`),m=`Gave up waiting after ${n}s; run is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`runs.wait`,timedOutWaiting:c,run:{id:l.id,status:l.status,exitCode:l.exitCode??null,url:u},...f?{}:{error:{phase:`run`,message:c?m:`Actor run did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Run`,value:l.status},{label:`Run ID`,value:l.id},{label:`Actor ID`,value:l.actId}];l.buildNumber&&g.push({label:`Build number`,value:l.buildNumber}),typeof l.exitCode==`number`&&g.push({label:`Exit code`,value:String(l.exitCode)});let _=[{label:`Run URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify run result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Run ended with status ${l.status}.`}),e.exitCode=p}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
221
- Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Yr=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Yr.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Yr.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${W}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
223
+ Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Zr=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Zr.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Zr.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${W}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
222
224
  Customize with --memory and --timeout flags.
223
- `;static examples=[{description:`Run a task by name.`,command:`apify task run my-task`},{description:`Run a task by full ID with custom memory and timeout.`,command:`apify task run username/my-task --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-run`;static flags=SharedRunOnCloudFlags(`Task`);static enableJsonFlag=!0;static args={taskId:Z.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let t=await getLoggedClientOrThrow(),n=await getLocalUserInfo(),r=n.username||n.id,{id:i,userFriendlyId:a,title:s}=await this.resolveTaskId(t,r),c={waitForFinish:2};this.flags.build&&(c.build=this.flags.build),this.flags.timeout&&(c.timeout=this.flags.timeout),this.flags.memory&&(c.memory=this.flags.memory);let l,u=runActorOrTaskOnCloud(t,{actorOrTaskData:{id:i,userFriendlyId:a,title:s},runOptions:c,type:`Task`,printRunLogs:!0,waitForRunToFinish:!0,silent:this.flags.json,suppressFinalStatus:!0});for await(let e of u)l=e;if(!l){simpleLog({message:`Task run did not start.`,stdout:!1}),e.exitCode=1;return}let f=l,p=consoleRunUrl(f.actId,f.id),m=consoleDatasetUrl(f.defaultDatasetId),h=f.status===`SUCCEEDED`,g=exitCodeForJobStatus(f.status,`run`),_=h?[]:await fetchLogTail(t,f.id);if(this.flags.json){printJsonToStdout({ok:h,operation:`task.run`,task:{id:i,name:a,title:s},actor:{id:f.actId,url:`https://console.apify.com/actors/${f.actId}`},run:{id:f.id,status:f.status,exitCode:f.exitCode??null,url:p},storage:{defaultDatasetId:f.defaultDatasetId,defaultKeyValueStoreId:f.defaultKeyValueStoreId,datasetUrl:m},...h?{}:{error:{phase:`run`,message:`Task run did not succeed`,logTail:_}},exitCode:g}),e.exitCode=g;return}simpleLog({message:formatResultSummary({resultLabel:`Apify task run result`,overallStatus:f.status,lines:[{label:`Run`,value:f.status},{label:`Task ID`,value:i},{label:`Actor ID`,value:f.actId},{label:`Run ID`,value:f.id},{label:`Build number`,value:f.buildNumber},...typeof f.exitCode==`number`?[{label:`Exit code`,value:String(f.exitCode)}]:[],{label:`Dataset ID`,value:f.defaultDatasetId},{label:`Key-value store ID`,value:f.defaultKeyValueStoreId}],links:[{label:`Run URL`,url:p},{label:`Dataset URL`,url:m}],errorReason:h?void 0:_}),stdout:!0}),e.exitCode=g}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run saved Apify tasks (named Actor configurations). Only 'task run' is available; create and manage tasks in Apify Console.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task`;static subcommands=[TaskRunCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{static name=`disable`;static description=`Disables telemetry.`;static examples=[{description:`Opt out of anonymous telemetry.`,command:`apify telemetry disable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{static name=`enable`;static description=`Enables telemetry.`;static examples=[{description:`Opt in to anonymous telemetry.`,command:`apify telemetry enable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{static name=`telemetry`;static description=`Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.`;static group=`Utilities`;static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;static subcommands=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
225
+ `;static examples=[{description:`Run a task by name.`,command:`apify task run my-task`},{description:`Run a task by full ID with custom memory and timeout.`,command:`apify task run username/my-task --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-run`;static flags=SharedRunOnCloudFlags(`Task`);static enableJsonFlag=!0;static args={taskId:Z.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let e=await getLoggedClientOrThrow(),t=await getLocalUserInfo(),n=t.username||t.id,{id:r,userFriendlyId:i,title:a}=await this.resolveTaskId(e,n),s={waitForFinish:2};this.flags.build&&(s.build=this.flags.build),this.flags.timeout&&(s.timeout=this.flags.timeout),this.flags.memory&&(s.memory=this.flags.memory);let c,l=runActorOrTaskOnCloud(e,{actorOrTaskData:{id:r,userFriendlyId:i,title:a},runOptions:s,type:`Task`,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of l)c=e;await finalizeRun({apifyClient:e,run:c,operation:`task-run`,json:this.flags.json})}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run saved Apify tasks (named Actor configurations). Only 'task run' is available; create and manage tasks in Apify Console.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task`;static subcommands=[TaskRunCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{static name=`disable`;static description=`Disables telemetry.`;static examples=[{description:`Opt out of anonymous telemetry.`,command:`apify telemetry disable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{static name=`enable`;static description=`Enables telemetry.`;static examples=[{description:`Opt in to anonymous telemetry.`,command:`apify telemetry enable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{static name=`telemetry`;static description=`Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.`;static group=`Utilities`;static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;static subcommands=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
224
226
 
225
227
  When a path argument is provided, validates only the input schema at that path.
226
228
 
@@ -228,5 +230,5 @@ When no path is provided, validates all schemas found in '${W}':
228
230
  - Input schema (from "input" key or default locations)
229
231
  - Dataset schema (from "storages.dataset")
230
232
  - Output schema (from "output")
231
- - Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),bt(new wn({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Xr=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Zr=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Xr as n,processVersionCheck as r,Zr as t};
232
- //# sourceMappingURL=_register-B1FD7fYN.js.map
233
+ - Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),bt(new wn({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Qr=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],$r=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Qr as n,processVersionCheck as r,$r as t};
234
+ //# sourceMappingURL=_register-LrJ1a-WN.js.map