apify-cli 1.9.1-beta.1 → 1.9.1-beta.3

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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as A,readFileSync as j,readdirSync as M,realpathSync as ee,renameSync as te,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as L,KEY_VALUE_STORE_KEYS as me,LOCAL_ACTOR_ENV_VARS as he,LOCAL_STORAGE_SUBDIRS as ge,MAX_MULTIFILE_BYTES as _e,META_ORIGINS as ve,SOURCE_FILE_FORMATS as ye}from"@apify/consts";import{jaroWinkler as be}from"@skyra/jaro-winkler";import xe from"js-levenshtein";import{Result as Se,err as Ce,none as R,ok as we,some as Te}from"@sapphire/result";import{execa as Ee}from"execa";import{access as De,appendFile as Oe,mkdir as z,readFile as B,readdir as ke,rename as Ae,rm as je,stat as V,symlink as Me,unlink as Ne,writeFile as H}from"node:fs/promises";import Pe from"configparser";import Fe from"@inquirer/input";import Ie from"which";import{createHmacSignature as Le,cryptoRandomObjectId as Re}from"@apify/utilities";import{execSync as ze,spawn as Be}from"node:child_process";import{DurationFormatter as Ve,Time as He,TimeTypes as Ue}from"@sapphire/duration";import{Timestamp as We}from"@sapphire/timestamp";import Ge from"adm-zip";import Ke from"ajv/dist/2019.js";import{ApifyClient as qe,DownloadItemsFormat as U}from"apify-client";import{ZipArchive as Je}from"archiver";import Ye,{AxiosHeaders as Xe}from"axios";import Ze from"escape-string-regexp";import Qe from"ignore";import{getEncoding as $e}from"istextorbinary";import et,{Mime as tt}from"mime";import nt from"mime/types/other.js";import rt from"mime/types/standard.js";import{glob as it}from"tinyglobby";import{calculateRunDynamicMemory as at}from"@apify/actor-memory-expression";import{Separator as ot,createPrompt as st,isEnterKey as ct,makeTheme as lt,useKeypress as ut,usePrefix as dt,useState as ft}from"@inquirer/core";import{pipeline as pt}from"node:stream/promises";import{MemoryStorage as mt}from"@crawlee/memory-storage";import{compile as ht}from"json-schema-to-typescript";import{validateInputSchema as gt,validateInputUsingValidator as _t}from"@apify/input_schema";import{getDatasetSchemaValidator as vt,getKeyValueStoreSchemaValidator as yt,getOutputSchemaValidator as bt}from"@apify/json_schemas";import xt from"cli-table3";import{downloadTemplate as St}from"giget";import Ct from"jju";import wt from"open";import{fetchManifest as Tt,manifestUrl as Et,wrapperManifestUrl as Dt}from"@apify/actor-templates";import Ot from"computer-name";import kt from"@inquirer/password";import At from"@inquirer/select";import{createServer as jt}from"node:http";import Mt from"node:assert";import{ReadStream as Nt}from"node:tty";import{setTimeout as Pt}from"node:timers/promises";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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_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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.9.1-beta.1`,hash:`87dd140f1666c78d548008b14c9bf349d3be5281`,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`&&(zt.installPath=c(process.execPath)),zt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Bt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as A,readFileSync as j,readdirSync as M,realpathSync as ee,renameSync as te,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce}from"node:os";import le,{isCI as ue}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as de,ACTOR_NAME as fe,ACTOR_SOURCE_TYPES as pe,APIFY_ENV_VARS as L,KEY_VALUE_STORE_KEYS as me,LOCAL_ACTOR_ENV_VARS as he,LOCAL_STORAGE_SUBDIRS as ge,MAX_MULTIFILE_BYTES as _e,META_ORIGINS as ve,SOURCE_FILE_FORMATS as ye}from"@apify/consts";import{jaroWinkler as be}from"@skyra/jaro-winkler";import xe from"js-levenshtein";import{Result as Se,err as Ce,none as R,ok as we,some as Te}from"@sapphire/result";import{execa as Ee}from"execa";import{access as De,appendFile as Oe,mkdir as z,readFile as B,readdir as ke,rename as Ae,rm as je,stat as V,symlink as Me,unlink as Ne,writeFile as H}from"node:fs/promises";import Pe from"configparser";import Fe from"@inquirer/input";import Ie from"which";import{createHmacSignature as Le,cryptoRandomObjectId as Re}from"@apify/utilities";import{execSync as ze,spawn as Be}from"node:child_process";import{DurationFormatter as Ve,Time as He,TimeTypes as Ue}from"@sapphire/duration";import{Timestamp as We}from"@sapphire/timestamp";import Ge from"adm-zip";import Ke from"ajv/dist/2019.js";import{ApifyClient as qe,DownloadItemsFormat as U}from"apify-client";import{ZipArchive as Je}from"archiver";import Ye,{AxiosHeaders as Xe}from"axios";import Ze from"escape-string-regexp";import Qe from"ignore";import{getEncoding as $e}from"istextorbinary";import et,{Mime as tt}from"mime";import nt from"mime/types/other.js";import rt from"mime/types/standard.js";import{glob as it}from"tinyglobby";import{calculateRunDynamicMemory as at}from"@apify/actor-memory-expression";import{Separator as ot,createPrompt as st,isEnterKey as ct,makeTheme as lt,useKeypress as ut,usePrefix as dt,useState as ft}from"@inquirer/core";import{pipeline as pt}from"node:stream/promises";import{MemoryStorage as mt}from"@crawlee/memory-storage";import{compile as ht}from"json-schema-to-typescript";import{validateInputSchema as gt,validateInputUsingValidator as _t}from"@apify/input_schema";import{getDatasetSchemaValidator as vt,getKeyValueStoreSchemaValidator as yt,getOutputSchemaValidator as bt}from"@apify/json_schemas";import xt from"cli-table3";import{downloadTemplate as St}from"giget";import Ct from"jju";import wt from"open";import{fetchManifest as Tt,manifestUrl as Et,wrapperManifestUrl as Dt}from"@apify/actor-templates";import Ot from"computer-name";import kt from"@inquirer/password";import At from"@inquirer/select";import{createServer as jt}from"node:http";import Mt from"node:assert";import{ReadStream as Nt}from"node:tty";import{setTimeout as Pt}from"node:timers/promises";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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_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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.9.1-beta.3`,hash:`90d633ea3dca2aa3a4232f9d86903bbe834bfd4b`,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`&&(zt.installPath=c(process.execPath)),zt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Bt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
2
2
  `)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
3
3
  `)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
4
4
  `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{P(i,n),r!==void 0&&C(i,r),te(i,t)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{T(t,i),r!==void 0&&C(i,r),te(i,n)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Bt)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Bt){let t=u(r,`${e}.exe.old`);if(D(t))try{N(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Bt.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Bt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(te(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):N(n,{force:!0})}catch(e){try{te(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{N(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Vt;function getMaxLineWidth(){if(Vt)return Vt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Vt=e;else if(!process.stdout.isTTY)Vt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Vt=e<1?80:e<40?40:e}return Vt}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(`
@@ -85,7 +85,7 @@ just as if the command were run from that directory with no argument.`;static gr
85
85
  - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
86
86
  - If options.contentType is set, value is taken as is.`})};static flags={contentType:J.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(Zn.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.
87
87
 
88
- 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}function getConsoleUrl(){let t=e.env.APIFY_CONSOLE_URL;if(t){let e=stripTrailingSlash(t);if(!URL.canParse(e))throw Error(`Invalid APIFY_CONSOLE_URL environment variable: "${t}" is not a valid URL.`);return e}return`https://console.apify.com`}function stripTrailingSlash(e){return e.replace(/\/+$/,``)}const $n=new Set(de);function isTerminalStatus(e){return!!e&&$n.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(`
88
+ 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}function getConsoleUrl(){let t=e.env.APIFY_CONSOLE_URL;if(t){let e=stripTrailingSlash(t);if(!URL.canParse(e))throw Error(`Invalid APIFY_CONSOLE_URL environment variable: "${t}" is not a valid URL.`);return e}return`https://console.apify.com`}function getConsoleRoutePrefix(e){return e?.organizationOwnerUserId&&e.id?`/organization/${e.id}`:null}function getConsoleIntegrationsUrl(e){return`${getConsoleUrl()}${getConsoleRoutePrefix(e)??``}/settings/integrations`}function stripTrailingSlash(e){return e.replace(/\/+$/,``)}const $n=new Set(de);function isTerminalStatus(e){return!!e&&$n.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(`
89
89
  `).filter(e=>e.length>0).slice(-n):[]}catch{return[]}}function consoleRunUrl(e,t){return`${getConsoleUrl()}/actors/${e}/runs/${t}`}function consoleBuildUrl(e,t){return`${getConsoleUrl()}/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(`
90
90
  `)}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:en,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:J.string({description:`Build tag to be applied to the successful Actor build. By default, this is "latest".`}),version:J.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:J.boolean({description:`Whether to print out the build log after the build is triggered.`}),wait:J.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:X.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;if(a&&s){error({message:`The --log and --wait flags cannot be used together. --log already waits for the build to finish while streaming its log.`}),e.exitCode=5;return}let 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;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}else if(p&&(h=p[0].versionNumber,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 g=await l.actor(u.id).build(h,{tag:n}),_=f?.name??`unknown-actor`,v=consoleBuildUrl(g.actId,g.buildNumber);if(a||s)try{var y=_usingCtx();if(y.u(useAbortJobOnSignal({apifyClient:l,kind:`build`,jobId:g.id})),a)try{await outputJobLog({job:g,apifyClient:l})}catch(e){error({message:`Failed to print log for build with ID "${g.id}": ${e.message}`,stdout:!0})}let{job:e}=await waitForTerminalStatus({apifyClient:l,jobId:g.id,kind:`build`});g=e}catch(e){y.e=e}finally{y.d()}if(a||s){let t=g.status===`SUCCEEDED`,n=exitCodeForJobStatus(g.status,`build`),r=t?[]:await fetchLogTail(l,g.id);if(i){printJsonToStdout({ok:t,operation:`builds.create`,waited:!0,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},...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:g.status,lines:[{label:`Build`,value:g.status},{label:`Build ID`,value:g.id},{label:`Build number`,value:g.buildNumber},{label:`Actor ID`,value:g.actId}],links:[{label:`Build URL`,url:v}],errorReason:t?void 0:r}),stdout:!0}),e.exitCode=n;return}if(i){printJsonToStdout({ok:!0,operation:`builds.create`,waited:!1,actor:{id:g.actId,name:_},build:{id:g.id,number:g.buildNumber,status:g.status,url:v},next:{wait:`apify builds wait ${g.id} --json`,log:`apify builds log ${g.id}`,info:`apify builds info ${g.id} --json`},exitCode:0});return}simpleLog({message:[t.greenBright(`Build started.`),``,`${t.yellow(`Actor`)}: ${_} (${t.gray(g.actId)})`,`${t.yellow(`Build ID`)}: ${g.id}`,`${t.yellow(`Build number`)}: ${g.buildNumber}`,`${t.yellow(`Status`)}: ${g.status}`,``,t.gray(`This command does not wait for the build to finish.`),``,`To wait for the final status:`,` apify builds wait ${g.id} --json`,``,`To inspect logs:`,` apify builds log ${g.id}`,``,`To inspect build metadata:`,` apify builds info ${g.id} --json`].join(`
91
91
  `),stdout:!0})}},ActorsBuildCommand=class extends OverrideClassName(BuildsCreateCommand){static name=`build`};function withSchemaHint(e,t){return t?`${e}\n${t}`:e}function resolveInput(e,t){let n,r;if(t)n=t,r=`application/json`;else{let t=getLocalInput(e);t&&(et.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,i={}){let s,c,{schemaHint:l}=i;if(!n&&!r){let t=dn;if(t)try{let n=JSON.parse(t.toString(`utf8`));if(Array.isArray(n))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=n,c=`stdin`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input from standard input.\n ${t.message}`,l)}),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(p(t,n)).then(()=>!0).catch(()=>!1),i=n.endsWith(`.json`)||n.endsWith(`.json5`)||a.isAbsolute(n)||n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`~`)||n.startsWith(`.\\`)||n.startsWith(`..\\`);if(r||i)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:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=t,c=`input`}catch(t){return error({message:withSchemaHint(`Cannot parse JSON input.\n ${t.message}`,l)}),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=p(t,r),i;try{let t=await B(n,`utf8`),i=JSON.parse(t);if(Array.isArray(i))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=i,c=r}catch(e){i=e}if(i)try{let t=JSON.parse(r);if(Array.isArray(t))return error({message:withSchemaHint(`The provided input is invalid. It should be an object, not an array.`,l)}),e.exitCode=5,!1;s=t,c=r}catch{return error({message:withSchemaHint(`Cannot read input file at path "${n}".\n ${i.message}`,i instanceof SyntaxError?l:void 0)}),e.exitCode=5,!1}}}return s?{input:s,source:c}:void 0}const er=[I.SUCCEEDED,I.ABORTED,I.FAILED,I.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(`
@@ -103,11 +103,12 @@ To inspect the input schema before creating a JSON input, use "apify actors info
103
103
  `);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.
104
104
  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(`
105
105
  `);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.
106
- If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},fr=`temp_file.zip`,pr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case I.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case I.READY:return{resultLabel:`PENDING`,ok:!0};case I.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case I.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case I.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case I.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case I.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case I.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 '${G}'.\nFiles under '${_e/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
106
+ If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},fr=`temp_file.zip`,pr={build:`latest`,memoryMbytes:4096,timeoutSecs:3600};function resolvePushOutcome(e){switch(e){case I.SUCCEEDED:return{resultLabel:`SUCCEEDED`,exitCode:0,ok:!0};case I.READY:return{resultLabel:`PENDING`,ok:!0};case I.RUNNING:return{resultLabel:`RUNNING`,ok:!0};case I.ABORTING:return{resultLabel:`ABORTING`,exitCode:3,ok:!1,errorMessage:`Build is aborting`};case I.ABORTED:return{resultLabel:`ABORTED`,exitCode:3,ok:!1,errorMessage:`Build aborted`};case I.TIMING_OUT:return{resultLabel:`TIMING_OUT`,exitCode:2,ok:!1,errorMessage:`Build is timing out`};case I.TIMED_OUT:return{resultLabel:`TIMED_OUT`,exitCode:2,ok:!1,errorMessage:`Build timed out`};case I.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}"`}}}const confirmGitSourceSwitch=async({actorName:e,gitRepoUrl:t,force:n})=>(warning({message:[`Actor ${e} builds from a Git repository: ${t}`,`A push replaces that source with the local files and drops the Git connection.`,`To build from the repository, run git push instead. The platform builds on push when automated builds are on.`].join(`
107
+ `)}),n?!0:Y({message:`Switch the source to the local files?`,default:!1,errorMessageForStdin:`Actor ${e} builds from a Git repository. To switch the source to the local files, use --force.`}));var ActorsPushCommand=class extends ApifyCommand{static name=`push`;static description=`Deploys Actor to Apify platform using settings from '${G}'.\nFiles under '${_e/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
107
108
  Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
108
- 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:J.string({char:`v`,description:`Actor version number to which the files should be pushed. By default, it is taken from the '${G}' file.`,required:!1}),"build-tag":J.string({char:`b`,description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${G}' file.`,required:!1}),"wait-for-finish":J.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:J.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:J.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:J.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":J.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:X.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 '${G}' file.`})};async run(){try{var t=_usingCtx();let n=p(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(`
109
- `)}),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}`:``,f,m,h=!1,g=this.flags.version||s?.version||`0.0`,_=this.flags.buildTag||s?.buildTag;!_&&g===`0.0`&&(_=`latest`);let v=parseWaitForFinishMillis(this.flags.waitForFinish),y=this.args.actorId;if(y){if(m=await i.actor(y).get(),!m)throw Error(`Cannot find Actor with ID '${y}' in your account.`);f=m.id}else{let e=c.username||c.id;if(m=await i.actor(`${e}/${s.name}`).get(),m)f=m.id;else{let{templates:e}=await Tt(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||pr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:g,buildTag:_,sourceType:pe.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),m=await i.actors().create(n),f=m.id,h=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:f,wasCreated:h};let b=i.actor(f);info({message:`Deploying Actor '${s.name}' to Apify.`});let x=await sumFilesSizeInBytes(r,n),S,C,w;if(x<_e){let e=await b.get();if(!h){let t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=ne(u(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||y))throw Error(`Actor with identifier "${s?.name||y}" is already on the platform and was modified there since modified locally.
110
- Skipping push. Use --force to override.`)}C=await createSourceFiles(r,n),S=pe.SOURCE_FILES}else{run({message:`Zipping Actor files`}),await createActZip(fr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${f}-source`),t=`version-${g}.zip`,a=j(fr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),re(fr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Le(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}w=s.toString(),S=pe.TARBALL}let T=await b.version(g).get(),E=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(T){let e={tarballUrl:w,sourceFiles:C,buildTag:_,sourceType:S,envVars:E};await b.version(g).update(e),run({message:`Updated version ${g} for Actor ${m.name}.`})}else{let e={versionNumber:g,tarballUrl:w,sourceFiles:C,buildTag:_,sourceType:S,envVars:E};await b.versions().create({...e}),run({message:`Created version ${g} for Actor ${m.name}.`})}if(!h&&!!s.usesStandbyMode!=!!m.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await b.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${m.name}.`})}run({message:`Building Actor ${m.name}`});let D=v===void 0?1/0:Date.now()+v,O=await b.build(g,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:O.id}));try{let e=Number.isFinite(D)?Math.max(0,D-Date.now()):void 0;await outputJobLog({job:O,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let k=await i.build(O.id).get();if(!k){error({message:`Could not fetch build with ID "${O.id}" after deployment.`}),e.exitCode=1;return}for(O=k;!de.includes(O.status)&&Date.now()<D;)await new Promise(e=>setTimeout(e,1e3)),O=await i.build(O.id).get();if(O.status===I.SUCCEEDED&&_&&v!==0){run({message:`Applying build tag "${_}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await b.get())?.taggedBuilds?.[_]?.buildId===O.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${_}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let A=O.status,M=resolvePushOutcome(A),ee=`${getConsoleUrl()}${l}/actors/${O.actId}`,te=`${ee}#/builds/${O.buildNumber}`,N=[];if(M.errorMessage)try{let e=await i.log(O.id).get();e&&(N=e.split(`
109
+ 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:J.string({char:`v`,description:`Actor version number to which the files should be pushed. By default, it is taken from the '${G}' file.`,required:!1}),"build-tag":J.string({char:`b`,description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${G}' file.`,required:!1}),"wait-for-finish":J.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:J.boolean({description:`Whether to open the browser automatically to the Actor details page.`,default:!1,required:!1}),force:J.boolean({char:`f`,description:`Push an Actor even when the local files are older than the Actor on the platform, or when the Actor builds from a Git repository.`,default:!1,required:!1}),dir:J.string({description:`Directory where the Actor is located.`,required:!1}),"allow-missing-secrets":J.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:X.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 '${G}' file.`})};async run(){try{var t=_usingCtx();let n=p(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(`
110
+ `)}),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}`:``,f,m,h=!1,g=this.flags.version||s?.version||`0.0`,_=this.flags.buildTag||s?.buildTag;!_&&g===`0.0`&&(_=`latest`);let v=parseWaitForFinishMillis(this.flags.waitForFinish),y=this.args.actorId;if(y){if(m=await i.actor(y).get(),!m)throw Error(`Cannot find Actor with ID '${y}' in your account.`);f=m.id}else{let e=c.username||c.id;if(m=await i.actor(`${e}/${s.name}`).get(),m)f=m.id;else{let{templates:e}=await Tt(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||pr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:g,buildTag:_,sourceType:pe.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),m=await i.actors().create(n),f=m.id,h=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:f,wasCreated:h};let b=i.actor(f);info({message:`Deploying Actor '${s.name}' to Apify.`});let x=await sumFilesSizeInBytes(r,n);if(x<_e&&!h){let e=await b.get(),t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=ne(u(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||y))throw Error(`Actor with identifier "${s?.name||y}" already exists on the platform and has newer changes than your local copy.
111
+ Skipping push. Use --force to override.`)}let S=await b.version(g).get();if(S?.sourceType===pe.GIT_REPO&&!await confirmGitSourceSwitch({actorName:m.name,gitRepoUrl:S.gitRepoUrl,force:this.flags.force})){info({message:`Push aborted. Actor ${m.name} still builds from its Git repository.`});return}let C,w,T;if(x<_e)w=await createSourceFiles(r,n),C=pe.SOURCE_FILES;else{run({message:`Zipping Actor files`}),await createActZip(fr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${f}-source`),t=`version-${g}.zip`,a=j(fr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),re(fr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=Le(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}T=s.toString(),C=pe.TARBALL}let E=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(S){let e={tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E};await b.version(g).update(e),run({message:`Updated version ${g} for Actor ${m.name}.`})}else{let e={versionNumber:g,tarballUrl:T,sourceFiles:w,buildTag:_,sourceType:C,envVars:E};await b.versions().create({...e}),run({message:`Created version ${g} for Actor ${m.name}.`})}if(!h&&!!s.usesStandbyMode!=!!m.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await b.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${m.name}.`})}run({message:`Building Actor ${m.name}`});let D=v===void 0?1/0:Date.now()+v,O=await b.build(g,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:`build`,jobId:O.id}));try{let e=Number.isFinite(D)?Math.max(0,D-Date.now()):void 0;await outputJobLog({job:O,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let k=await i.build(O.id).get();if(!k){error({message:`Could not fetch build with ID "${O.id}" after deployment.`}),e.exitCode=1;return}for(O=k;!de.includes(O.status)&&Date.now()<D;)await new Promise(e=>setTimeout(e,1e3)),O=await i.build(O.id).get();if(O.status===I.SUCCEEDED&&_&&v!==0){run({message:`Applying build tag "${_}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await b.get())?.taggedBuilds?.[_]?.buildId===O.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${_}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let A=O.status,M=resolvePushOutcome(A),ee=`${getConsoleUrl()}${l}/actors/${O.actId}`,te=`${ee}#/builds/${O.buildNumber}`,N=[];if(M.errorMessage)try{let e=await i.log(O.id).get();e&&(N=e.split(`
111
112
  `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}M.exitCode&&(e.exitCode=M.exitCode);let P={ok:M.ok,operation:`push`,actor:{id:O.actId,url:ee},build:{id:O.id,number:O.buildNumber,status:A,url:te}};if(M.exitCode!==void 0&&(P.exitCode=M.exitCode),M.errorMessage&&(P.error={phase:`build`,message:M.errorMessage,logTail:N}),this.flags.json){printJsonToStdout(P);return}simpleLog({stdout:!0,message:[`Apify push result: ${M.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${A}`,`Actor ID: ${O.actId}`,`Build ID: ${O.id}`,`Build number: ${O.buildNumber}`,...M.exitCode?[`Exit code: ${M.exitCode}`]:[],``,`Actor URL: ${ee}`,`Build URL: ${te}`,...M.errorMessage&&N.length?[``,`Reason:`,...N]:[]].join(`
112
113
  `)}),this.flags.open&&await wt(ee)}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:X.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 Y({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 mr={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?mr[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.
113
114
 
@@ -120,7 +121,7 @@ The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the
120
121
 
121
122
  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:X.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:X.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:J.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:hr}),body:J.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:J.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:J.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":J.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1,exclusive:[`describe`]}),search:J.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:J.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&&hr.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(gr.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={...an,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=vr[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${yr}`,stdout:!1})}}};async function fetchEndpoints(){let e;try{e=await fetch(_r)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${_r}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${_r}: ${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))hr.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 br=stdinCheckWrapper(async({message:e,mask:t})=>await kt({message:e,mask:t??`*`},mn)),xr=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await At({message:e,choices:t,pageSize:n,loop:r,default:i},mn),{errorMessageForStdin:`Please provide the selection using the command options.`}),wrapResponse=e=>({status(t){e.statusCode=t},send(t){typeof t==`string`?(e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(t)):(e.setHeader(`Content-Type`,`application/json; charset=utf-8`),e.end(JSON.stringify(t)))},end(){e.end()}});function createLocalApiServer({corsOrigin:e,authToken:t,routes:n}){return jt(async(r,i)=>{if(i.setHeader(`Connection`,`close`),i.setHeader(`Vary`,`Origin`),i.setHeader(`Access-Control-Allow-Origin`,e),r.method===`OPTIONS`){i.setHeader(`Access-Control-Allow-Methods`,`GET,HEAD,PUT,PATCH,POST,DELETE`),i.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`),i.statusCode=204,i.end();return}let a=new URL(r.url??`/`,`http://localhost`),s=wrapResponse(i),c=a.searchParams.get(`token`);if(!c){let e=r.headers.authorization;if(e){let[t,n,...r]=e.trim().split(/\s+/);t.toLowerCase()===`bearer`&&n&&r.length===0&&(c=n)}}if(c!==t){s.status(401),s.send(`Authorization failed`);return}let l=n[`${r.method} ${a.pathname}`];if(!l){s.status(404),s.send(`Not found`);return}let u=[];for await(let e of r)u.push(e);let f=Buffer.concat(u).toString(`utf-8`),p={};if(f)try{p=JSON.parse(f)}catch{s.status(400),s.send(`Invalid JSON body`);return}await l(p,s)})}const tryToLogin=async n=>{let r=await getLoggedClient(n,getConsoleUrl().includes(`localhost`)?`http://localhost:3333`:void 0),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)`:`${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.
122
123
 
123
- 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:J.string({char:`t`,description:`Apify API token.`,required:!1}),method:J.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=getConsoleUrl(),r=new URL(n).origin,i=`${n}/settings/integrations`,a=t;if(t||(a=await xr({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})),a===`console`){let e=Re(),t=createLocalApiServer({corsOrigin:r,authToken:e,routes:{"POST /api/v1/login-token":async(e,n)=>{try{if(e.apiToken)await tryToLogin(e.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)}t.close()},"POST /api/v1/exit":(e,n)=>{e.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):e.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),t.close()}}});t.listen(0);let{port:n}=t.address(),a=new URL(i);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${n}`),a.searchParams.set(`localCliToken`,e),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Ot()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await wt(a.href)}else{console.log(`Enter your Apify API token. You can find it at ${i}`);let e=await br({message:`token:`});await tryToLogin(e)}}},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:J.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:J.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:X.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`)}: ${K.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${K.display(r.finishedAt)} (took ${t.gray(In.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${In.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=`${getConsoleUrl()}/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
124
+ 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:J.string({char:`t`,description:`Apify API token.`,required:!1}),method:J.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=getConsoleUrl(),r=new URL(n).origin,i=getConsoleIntegrationsUrl(),a=t;if(t||(a=await xr({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})),a===`console`){let e=Re(),t=createLocalApiServer({corsOrigin:r,authToken:e,routes:{"POST /api/v1/login-token":async(e,n)=>{try{if(e.apiToken)await tryToLogin(e.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)}t.close()},"POST /api/v1/exit":(e,n)=>{e.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):e.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),t.close()}}});t.listen(0);let{port:n}=t.address(),a=new URL(i);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${n}`),a.searchParams.set(`localCliToken`,e),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Ot()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await wt(a.href)}else{console.log(`Enter your Apify API token. You can find it at ${i}`);let e=await br({message:`token:`});await tryToLogin(e)}}},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:J.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:J.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:X.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`)}: ${K.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${K.display(r.finishedAt)} (took ${t.gray(In.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${In.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=`${getConsoleUrl()}/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
124
125
  `),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:X.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 Z({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:J.integer({description:`Number of builds that will be skipped.`,default:0}),limit:J.integer({description:`Number of builds that will be listed.`,default:10}),desc:J.boolean({description:`Sort builds in descending order.`,default:!1}),compact:J.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:X.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(`
125
126
  `),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(`${Ln.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${Ln.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:J.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:J.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 Y({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 Fe({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}},mn));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:X.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 Y({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).
126
127
  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:X.string({required:!0,description:`The build ID to wait for.`})};static flags={timeout:J.integer({char:`t`,description:`In seconds, how long to wait before giving up. If skipped, it waits indefinitely.`,required:!1}),"poll-interval":J.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 nr{static name=`call`};const pathToInstallMarker=e=>u(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;static flags={"shims-only":J.boolean({description:`Only (re)create the apify/actor wrapper scripts next to the bundle, then exit. Used by the install/upgrade scripts.`,hidden:!0,default:!1})};async run(){let{installMethod:n,installPath:r,version:i}=useCLIMetadata();if(n!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(Mt(r,`When CLI is installed via bundles, the install path must be set`),writeEntrypointShims(r,e.platform===`win32`),cliDebugPrint(`[install] wrote entrypoint shims to`,r),this.flags.shimsOnly)return;let a=pathToInstallMarker(r);if(D(a)){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(e.platform!==`win32`){await this.symlinkToLocalBin(r);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await H(a,i),cliDebugPrint(`[install] install marker written to`,a),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(i)}`),t.gray(` Location: ${t.bold.white(tildify(u(r,`apify`)))} and ${t.bold.white(tildify(u(r,`actor`)))}`)].join(`
@@ -131,30 +132,30 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
131
132
  `)}\n`;try{await z(c(g),{recursive:!0}),await H(g,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(g)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(g)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(f)}" to your PATH in ${tildify(g)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(g)}`)} to reload your shell.`)].join(`
132
133
  `)});return}let b=g??`your shell config file`;if(y){let e=`echo -e '${v.join(`\\n`)}' >> "${b}" && source "${b}"`;info({message:[t.gray(`The Apify & Actor CLIs are not in your PATH. Run:`),``,t.white.bold(` ${e}`)].join(`
133
134
  `)});return}info({message:[t.gray(`Manually add the following lines to ${b} or similar:`),...v.map(e=>t.white.bold(` ${e}`))].join(`
134
- `)})}};const Q=useCLIMetadata();function isInstalledOnMusl(){return Q.platform===`linux`&&D(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Q.platform===`darwin`&&Q.arch===`x64`?!ze(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Q.platform===`linux`&&Q.arch===`x64`?!j(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Q.platform===`windows`&&Q.arch!==`arm64`&&ze(`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`}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":pn}});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=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Q.platform&&i===Q.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});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/refs/heads/master/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:J.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:J.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":J.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(`
135
- `)})}async handleInstallSpecificVersion(t){if(t!==`latest`&&!y(t,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let n=await useCLIVersionAssets(t);if(!n){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:r,version:i}=n;if(!y(i,wr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${wr}.`});return}let a=useCLIMetadata();if(a.installMethod===`bundle`){if(!r.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: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`].join(`
135
+ `)})}};const Cr=useCLIMetadata();function isInstalledOnMusl(){return Cr.platform===`linux`&&D(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Cr.platform===`darwin`&&Cr.arch===`x64`?!ze(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Cr.platform===`linux`&&Cr.arch===`x64`?!j(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Cr.platform===`windows`&&Cr.arch!==`arm64`&&ze(`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`}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":pn}});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=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Cr.platform&&i===Cr.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const wr={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}`]},Tr=`1.0.1`,Er=`https://raw.githubusercontent.com/apify/apify-cli/refs/heads/master/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:J.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:J.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":J.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=wr[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(`
136
+ `)})}async handleInstallSpecificVersion(t){if(t!==`latest`&&!y(t,Tr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Tr}.`});return}let n=await useCLIVersionAssets(t);if(!n){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:r,version:i}=n;if(!y(i,Tr)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Tr}.`});return}let a=useCLIMetadata();if(a.installMethod===`bundle`){if(!r.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: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`].join(`
136
137
  `)});return}let t=c(e.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,t);let n=await ke(t);if(!n.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,n),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: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${t}`].join(`
137
- `)});return}if(a.platform===`windows`)return this.startUpgradeProcess(t,i,r);await this.handleUnixUpgrade(t,i,r),this.successMessage(i);return}let s=Cr[a.installMethod](t,this.entrypoint);if(e.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${s.join(` `)}`});return}try{await execWithLog({cmd:s[0],args:s.slice(1)}),this.successMessage(i)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${s.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(t,n,r){await this.upsertUpgradeScript(t);let i=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${u(t,`upgrade.ps1`)}"`,`-ProcessId`,e.pid.toString(),`-InstallLocation`,`"${t}"`,`-Version`,`"${n}"`],a=r.map(e=>e.browser_download_url).join(`,`);i.push(`-AllUrls`,`"${a}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,i),info({message:`Starting upgrade process...`});let s=Be(`powershell.exe`,i,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});s.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),s.unref(),e.exit(0)}),s.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(t){let n=u(t,`upgrade.ps1`);if(D(n))return;let r=useCLIMetadata(),i=await fetch(Tr,{headers:{"User-Agent":pn}});i.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: ${r.platform} ${r.arch}`,`- The URL of the asset that failed to fetch: ${Tr}`,`- The status code of the response: ${i.status}`].join(`
138
+ `)});return}if(a.platform===`windows`)return this.startUpgradeProcess(t,i,r);await this.handleUnixUpgrade(t,i,r),this.successMessage(i);return}let s=wr[a.installMethod](t,this.entrypoint);if(e.env.APIFY_CLI_DEBUG){info({message:`Would run command: ${s.join(` `)}`});return}try{await execWithLog({cmd:s[0],args:s.slice(1)}),this.successMessage(i)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${s.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(t,n,r){await this.upsertUpgradeScript(t);let i=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${u(t,`upgrade.ps1`)}"`,`-ProcessId`,e.pid.toString(),`-InstallLocation`,`"${t}"`,`-Version`,`"${n}"`],a=r.map(e=>e.browser_download_url).join(`,`);i.push(`-AllUrls`,`"${a}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,i),info({message:`Starting upgrade process...`});let s=Be(`powershell.exe`,i,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});s.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),s.unref(),e.exit(0)}),s.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(t){let n=u(t,`upgrade.ps1`);if(D(n))return;let r=useCLIMetadata(),i=await fetch(Er,{headers:{"User-Agent":pn}});i.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: ${r.platform} ${r.arch}`,`- The URL of the asset that failed to fetch: ${Er}`,`- The status code of the response: ${i.status}`].join(`
138
139
  `)}),e.exit(1));let a=await i.arrayBuffer();await H(n,Buffer.from(a)),cliDebugPrint(`[upgrade] downloaded upgrade script to`,n)}async handleUnixUpgrade(n,r,i){let a=useCLIMetadata();for(let s of i){let i=`apify-cli`,c=u(n,i);info({message:`Downloading \`${i}\` binary of the Apify CLI...`});let l=await fetch(s.browser_download_url,{headers:{"User-Agent":pn}});if(!l.ok){let e=await l.text();cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:s,status:l.status,body:e}),error({message:[`Failed to fetch the ${i} 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: ${a.platform} ${a.arch}`,`- The URL of the asset that failed to fetch: ${s.browser_download_url}`,`- The status code of the response: ${l.status}`,`- The body of the response: ${e}`].join(`
139
140
  `)});return}if(e.env.APIFY_CLI_DEBUG&&!e.env.APIFY_CLI_FORCE){info({message:`Would write asset ${i} to ${c}`});continue}info({message:t.gray(`Writing ${i} to ${c}...`)});let f=await l.arrayBuffer(),p=`${c}.${e.pid}.tmp`;try{await H(p,Buffer.from(f),{mode:493}),await Ae(p,c),writeEntrypointShims(n,!1),cliDebugPrint(`[upgrade ${i}] wrote asset to`,c)}catch(e){await je(p,{force:!0}).catch(()=>{}),cliDebugPrint(`[upgrade] failed to write asset`,{error:e}),error({message:[`Failed to write the ${i} 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: ${a.platform} ${a.arch}`,`- The URL of the asset that failed to fetch: ${s.browser_download_url}`,`- The error: ${e.message}`].join(`
140
- `)})}}}};const Er={STARTER:`STARTER`,WEB_SCRAPING:`WEB_SCRAPING`,INTEGRATION:`INTEGRATION`,AUTOMATION:`AUTOMATION`,AI:`AI`},$={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},Dr=`any-language`,Or=`any-use-case`,kr={[$.TYPESCRIPT]:`ts-crawlee-cheerio`,[$.JAVASCRIPT]:`js-crawlee-cheerio`,[$.PYTHON]:`python-crawlee-beautifulsoup`},Ar={[$.TYPESCRIPT]:`ts-empty`,[$.JAVASCRIPT]:`js-empty`,[$.PYTHON]:`python-empty`},jr=[{cliFlag:`web-scraper`,templateTag:Er.WEB_SCRAPING,label:`Web scraper`},{cliFlag:`ai-agent`,templateTag:Er.AI,label:`AI agent`},{cliFlag:`data-pipeline`,templateTag:Er.INTEGRATION,label:`API & data pipeline`},{cliFlag:`browser-automation`,templateTag:Er.AUTOMATION,label:`Browser automation`}],Mr=[{cliFlag:$.JAVASCRIPT,templateTag:$.JAVASCRIPT,label:`JavaScript`,aliases:[`js`]},{cliFlag:$.TYPESCRIPT,templateTag:$.TYPESCRIPT,label:`TypeScript`,aliases:[`ts`]},{cliFlag:$.PYTHON,templateTag:$.PYTHON,label:`Python`,aliases:[`py`]}],Nr=Mr.flatMap(e=>[e.cliFlag,...e.aliases]),Pr=jr.map(e=>e.cliFlag);function useCaseFlagToTag(e){return jr.find(t=>t.cliFlag===e)?.templateTag}function languageFlagToTag(e){return Mr.find(t=>t.cliFlag===e||t.aliases.includes(e))?.templateTag}function useCaseLabel(e){return jr.find(t=>t.templateTag===e)?.label??e}function languageLabel(e){return e===`any-language`?`any language`:Mr.find(t=>t.templateTag===e)?.label??e}function getTemplateRecommendation(e,t,n){let r=n!==Dr,i=t!==Or,matchesLanguage=e=>!r||e.category===n,matchesUseCase=e=>!i||!!e.useCases?.includes(t),isExactMatch=e=>matchesLanguage(e)&&matchesUseCase(e),a=new Set,s=[],addCandidates=e=>{for(let t of e)a.has(t.id)||(a.add(t.id),s.push(t))},addCuratedTemplates=t=>{let i=r?[t[n]]:Object.values(t);addCandidates(e.filter(e=>i.includes(e.id)))};return(r||i)&&addCandidates(e.filter(isExactMatch)),addCuratedTemplates(kr),addCuratedTemplates(Ar),r&&addCandidates(e.filter(matchesLanguage)),i&&addCandidates(e.filter(matchesUseCase)),addCandidates(e),s.map(e=>({template:e,isExactMatch:isExactMatch(e)}))}function buildTemplateChoiceList(e,t,n){let r=e.some(e=>e.isExactMatch),i=e.map(({template:e,isExactMatch:t})=>({template:e,label:formatTemplateLabel(e,n),isExactMatch:t})),a=i.findIndex(e=>!e.isExactMatch);return{rows:i,separatorIndex:r&&a>0?a:null,noExactMatchHint:!r&&i.length>0?`No template matches ${describeSelection(t,n)} exactly — showing the closest alternatives.`:null}}function formatTemplateLabel(e,t){let n=Mr.find(t=>t.templateTag===e.category)?.label,r=t===`any-language`||e.category!==t;return n&&r?`${e.label} (${n})`:e.label}function describeSelection(e,t){let n=[];return e!==`any-use-case`&&n.push(useCaseLabel(e)),n.push(languageLabel(t)),n.join(` + `)}async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t,n={}){let r=await t;if(r instanceof Error)throw r;if(e){let t=r.templates.find(t=>t.name===e||t.id===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(r,n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await Ye.get(n.localReadmeSuffixUrl,{responseType:`text`});await Oe(e,`\n\n${t.data}`)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function buildNextSteps(e){let{actorName:t,dependenciesInstalled:n,installCommandSuggestion:r}=e,i=[`cd "${t}"`];return n||i.push(r||`install dependencies with your package manager`),i.push(`apify run`),i}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a,gitRemote:s}=e,c=`✅ Actor '${t}' created successfully!`,l=buildNextSteps({actorName:t,dependenciesInstalled:n,installCommandSuggestion:a});return c+=`\n\nNext steps:\n\n${l.join(`
141
+ `)})}}}};const Dr={STARTER:`STARTER`,WEB_SCRAPING:`WEB_SCRAPING`,INTEGRATION:`INTEGRATION`,AUTOMATION:`AUTOMATION`,AI:`AI`},Q={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},Or=`any-language`,kr=`any-use-case`,Ar={[Q.TYPESCRIPT]:`ts-crawlee-cheerio`,[Q.JAVASCRIPT]:`js-crawlee-cheerio`,[Q.PYTHON]:`python-crawlee-beautifulsoup`},jr={[Q.TYPESCRIPT]:`ts-empty`,[Q.JAVASCRIPT]:`js-empty`,[Q.PYTHON]:`python-empty`},Mr=[{cliFlag:`web-scraper`,templateTag:Dr.WEB_SCRAPING,label:`Web scraper`},{cliFlag:`ai-agent`,templateTag:Dr.AI,label:`AI agent`},{cliFlag:`data-pipeline`,templateTag:Dr.INTEGRATION,label:`API & data pipeline`},{cliFlag:`browser-automation`,templateTag:Dr.AUTOMATION,label:`Browser automation`}],Nr=[{cliFlag:Q.JAVASCRIPT,templateTag:Q.JAVASCRIPT,label:`JavaScript`,aliases:[`js`]},{cliFlag:Q.TYPESCRIPT,templateTag:Q.TYPESCRIPT,label:`TypeScript`,aliases:[`ts`]},{cliFlag:Q.PYTHON,templateTag:Q.PYTHON,label:`Python`,aliases:[`py`]}],Pr=Nr.flatMap(e=>[e.cliFlag,...e.aliases]),Fr=Mr.map(e=>e.cliFlag);function useCaseFlagToTag(e){return Mr.find(t=>t.cliFlag===e)?.templateTag}function languageFlagToTag(e){return Nr.find(t=>t.cliFlag===e||t.aliases.includes(e))?.templateTag}function useCaseLabel(e){return Mr.find(t=>t.templateTag===e)?.label??e}function languageLabel(e){return e===`any-language`?`any language`:Nr.find(t=>t.templateTag===e)?.label??e}function getTemplateRecommendation(e,t,n){let r=n!==Or,i=t!==kr,matchesLanguage=e=>!r||e.category===n,matchesUseCase=e=>!i||!!e.useCases?.includes(t),isExactMatch=e=>matchesLanguage(e)&&matchesUseCase(e),a=new Set,s=[],addCandidates=e=>{for(let t of e)a.has(t.id)||(a.add(t.id),s.push(t))},addCuratedTemplates=t=>{let i=r?[t[n]]:Object.values(t);addCandidates(e.filter(e=>i.includes(e.id)))};return(r||i)&&addCandidates(e.filter(isExactMatch)),addCuratedTemplates(Ar),addCuratedTemplates(jr),r&&addCandidates(e.filter(matchesLanguage)),i&&addCandidates(e.filter(matchesUseCase)),addCandidates(e),s.map(e=>({template:e,isExactMatch:isExactMatch(e)}))}function buildTemplateChoiceList(e,t,n){let r=e.some(e=>e.isExactMatch),i=e.map(({template:e,isExactMatch:t})=>({template:e,label:formatTemplateLabel(e,n),isExactMatch:t})),a=i.findIndex(e=>!e.isExactMatch);return{rows:i,separatorIndex:r&&a>0?a:null,noExactMatchHint:!r&&i.length>0?`No template matches ${describeSelection(t,n)} exactly — showing the closest alternatives.`:null}}function formatTemplateLabel(e,t){let n=Nr.find(t=>t.templateTag===e.category)?.label,r=t===`any-language`||e.category!==t;return n&&r?`${e.label} (${n})`:e.label}function describeSelection(e,t){let n=[];return e!==`any-use-case`&&n.push(useCaseLabel(e)),n.push(languageLabel(t)),n.join(` + `)}async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t,n={}){let r=await t;if(r instanceof Error)throw r;if(e){let t=r.templates.find(t=>t.name===e||t.id===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(r,n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await Ye.get(n.localReadmeSuffixUrl,{responseType:`text`});await Oe(e,`\n\n${t.data}`)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function buildNextSteps(e){let{actorName:t,dependenciesInstalled:n,installCommandSuggestion:r}=e,i=[`cd "${t}"`];return n||i.push(r||`install dependencies with your package manager`),i.push(`apify run`),i}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a,gitRemote:s}=e,c=`✅ Actor '${t}' created successfully!`,l=buildNextSteps({actorName:t,dependenciesInstalled:n,installCommandSuggestion:a});return c+=`\n\nNext steps:\n\n${l.join(`
141
142
  `)}`,s?(c+=`\n\n🌱 Connected to ${s.remoteUrl} — Actor ${s.actorId} builds from this repository.`,c+=`
142
143
  💡 Tip: Turn on Automatic builds in the Actor's Source settings to rebuild on every push.`):(c+=`
143
144
 
144
145
  💡 Tip: Use 'apify push' to deploy your Actor to the Apify platform`,i&&(c+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`)),c+=`
145
- 📖 Docs: https://docs.apify.com/platform/actors/development`,r&&(c+=`\n\n${r}`),c}async function executePrompts(e,t){return promptTemplate(e,t.useCase?useCaseFlagToTag(t.useCase)??`any-use-case`:await promptUseCase(),t.language?languageFlagToTag(t.language)??t.language:await promptLanguage())}async function promptActorName(){return await _n({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptUseCase(){let e=[...jr.map(e=>({name:e.label,value:e.templateTag})),new ot,{name:`Any use case`,value:Or}];return xr({message:`What do you want to build?`,choices:e,default:jr[0].templateTag,loop:!1})}async function promptLanguage(){let e=[...Mr.map(e=>({name:e.label,value:e.templateTag})),new ot,{name:`Any language`,value:Dr}];return xr({message:`Choose the programming language of your new Actor:`,choices:e,default:Mr[0].templateTag,loop:!1})}async function promptTemplate(e,t,n){let{rows:r,separatorIndex:i,noExactMatchHint:a}=buildTemplateChoiceList(getTemplateRecommendation(e.templates,t,n),t,n);if(r.length===0)throw Error(`No Actor templates are available right now. Please try again later.`);let s=[];return r.forEach((e,t)=>{t===i&&s.push(new ot(`── The templates below don't exactly match your selection ──`)),s.push({name:e.label,value:e.template})}),a&&info({message:a,stdout:!1}),xr({message:`Choose a template for your new Actor. More info at https://apify.com/templates`,choices:s,default:r[0].template,loop:!1,pageSize:8})}const Fr=[`apify`,`github`],isGitProvider=e=>e===`github`,Ir={github:{providerId:`github-app`,authorizeEndpoint:`https://github.com/login/oauth/authorize`,defaultClientId:`Iv1.e39b3ed87e74885f`,clientIdEnvVar:`APIFY_GITHUB_APP_CLIENT_ID`,defaultAppName:`apify`,appNameEnvVar:`APIFY_GITHUB_APP_NAME`,appInstallUrl:`https://github.com/apps/{app}/installations/new`,redirectPath:`/actors/new/git/connected?service=github`}},toGitAccount=({id:e,username:t,organizationOwnerUserId:n})=>({id:e,username:t,organizationOwnerUserId:n}),getConsoleRoutePrefix=e=>e?.organizationOwnerUserId&&e.id?`/organization/${e.id}`:null,getGitConnectUrl=(t,n)=>{let{authorizeEndpoint:r,defaultClientId:i,clientIdEnvVar:a,redirectPath:s}=Ir[t],c=new URL(s,getConsoleUrl()),l=getConsoleRoutePrefix(n);l&&c.searchParams.set(`routePrefix`,encodeURIComponent(l));let u=new URL(r);return u.searchParams.set(`client_id`,e.env[a]||i),u.searchParams.set(`redirect_uri`,c.href),u.href},getAddWorkspaceUrl=t=>{let{defaultAppName:n,appNameEnvVar:r,appInstallUrl:i}=Ir[t];return i.replace(`{app}`,e.env[r]||n)},promptGitSource=async()=>xr({message:`Where will the source code live?`,choices:[{name:`Apify`,value:`apify`,description:`Deploy with "apify push". No Git provider involved.`},{name:`GitHub`,value:`github`,description:`Apify creates a private repository and builds the Actor from it.`}],default:`apify`,loop:!1}),parseGitRepoFlag=(e,t)=>{if(!e)return{workspace:void 0,repoName:t};let[n,r,...i]=e.split(`/`);if(i.length>0||r!==void 0&&(!n||!r))throw Error(`Invalid --git-repo "${e}". Use "workspace/name" or just "name".`);return r===void 0?{workspace:void 0,repoName:n}:{workspace:n,repoName:r}},apiUrl=({client:e},t)=>`${e.baseUrl}/${t}`,authHeader=({client:e})=>({Authorization:`Bearer ${e.token}`}),fetchGitIntegrations=async e=>{let t=apiUrl(e,`integrations/git`);cliDebugPrint(`git-source`,`GET`,t);let n=await fetch(t,{headers:authHeader(e)}),r=await n.text();if(cliDebugPrint(`git-source`,`GET`,t,`->`,n.status,r.slice(0,400)),!n.ok)throw Error(`Could not read your Git integrations (${n.status} ${n.statusText}).`);return(()=>{try{return JSON.parse(r)}catch{return null}})()?.data??[]},findIntegration=(e,t)=>e.find(e=>e.id===Ir[t].providerId),ensureUsableIntegration=async(e,{client:t,isInteractive:n,account:r})=>{let load=async()=>findIntegration(await fetchGitIntegrations({client:t}),e),i=await load();if(cliDebugPrint(`git-source`,`integration:`,i?`${i.id} workspaces=${i.workspaces.length}`:`none`),i?.workspaces.length)return i;if(!n)return i??null;let a=null,offer=async t=>{let n=t?t.addWorkspaceUrl||getAddWorkspaceUrl(e):getGitConnectUrl(e,r);n!==a&&(a=n,info({message:`${t?`Give Apify access to a ${e} account`:`Connect your ${e} account to Apify`}: ${n}`}),await wt(n).catch(()=>void 0),info({message:r?.username?`Waiting for authorization to complete in your browser. It connects ${e} to the Apify account ${r.username}.`:`Waiting for authorization to complete in your browser...`}))};await offer(i);let s=Date.now()+18e4,c=2e3;for(;Date.now()<s;){if(await Pt(c),c=Math.min(Math.round(c*1.5),1e4),i=await load(),i?.workspaces.length)return i;await offer(i)}return i??null},chooseWorkspace=async(e,t,n)=>{let{workspaces:r}=e;if(t){let e=r.find(({id:e})=>e.toLowerCase()===t.toLowerCase());return e?{workspace:e.id}:{stopReason:`unknownWorkspace`}}return r.length===1?{workspace:r[0].id}:n?{workspace:await xr({message:`Which account should own the repository?`,choices:r.map(({id:e,label:t})=>({name:t,value:e})),loop:!1})}:{stopReason:`ambiguousWorkspace`}};var CreateRemoteRepoError=class extends Error{stopReason;constructor(e,t){super(e),this.stopReason=t,this.name=`CreateRemoteRepoError`}};const Lr=new Set([`integration-auth-error`,`invalid-git-auth-token`]),createRemoteRepo=async e=>{let{provider:t,workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a}=e,{providerId:s}=Ir[t],c=apiUrl(e,`integrations/git/${s}/create-repo`),l=JSON.stringify({workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a});cliDebugPrint(`git-source`,`POST`,c,l);let u=await fetch(c,{method:`POST`,headers:{...authHeader(e),"Content-Type":`application/json`},body:l}),f=await u.text();cliDebugPrint(`git-source`,`POST`,c,`->`,u.status,f.slice(0,400));let p=(()=>{try{return JSON.parse(f)}catch{return null}})();if(u.ok&&p?.data)return p.data;let m=p?.error?.type,h=p?.error?.message||`${u.status} ${u.statusText}`;throw m&&Lr.has(m)?new CreateRemoteRepoError(h,`notAuthorized`):m===`invalid-parameter`?new CreateRemoteRepoError(h,`repoNameRejected`):new CreateRemoteRepoError(h,`repoCreateFailed`)},cloneRepo=async(e,t,n)=>{await Ee(`git`,[`clone`,t,e],{env:n?void 0:{GIT_TERMINAL_PROMPT:`0`,GIT_SSH_COMMAND:`ssh -o BatchMode=yes`}})},createGitActor=async({client:e,actorName:t,gitRepoUrl:n})=>e.actors().create({name:t,versions:[{versionNumber:`0.0`,sourceType:pe.GIT_REPO,gitRepoUrl:n}]}),registerDeploymentKey=async({client:e,provider:t,actorId:n,repoUrl:r})=>{let{providerId:i}=Ir[t],a=apiUrl({client:e},`integrations/git/${i}/register-deployment-key`),s=JSON.stringify({actorId:n,repoName:r});cliDebugPrint(`git-source`,`POST`,a,s);let c=await fetch(a,{method:`POST`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:s}),l=await c.text();if(cliDebugPrint(`git-source`,`POST`,a,`->`,c.status,l.slice(0,400)),c.ok)return;let u=(()=>{try{return JSON.parse(l).error?.message}catch{return null}})();throw Error(u||`${c.status} ${c.statusText}`)},runGitSourceFlow=async({client:e,provider:t,actorDir:n,actorName:r,workspace:i,repoName:a,isPrivate:s,templateArchiveUrl:c,isInteractive:l,account:u,customize:f})=>{let p=!1,stopped=(e,t,n={})=>({remoteUrl:null,httpsUrl:null,actorId:null,workspaces:null,scaffolded:p,...n,stopReason:e,error:t instanceof Error?t.message:String(t)}),m;try{m=await ensureUsableIntegration(t,{client:e,isInteractive:l,account:u})}catch(e){return stopped(`lookupFailed`,e)}let h=u?.username?`The Apify account ${u.username}`:`Apify`;if(!m)return stopped(`notAuthorized`,Error(`${h} is not authorized to access ${t}.`));if(!m.workspaces.length)return stopped(`noWorkspace`,Error(`${h} has no ${t} account to create the repository in.`));let g=m.workspaces.map(({id:e})=>e),_=g.join(`, `),v=await chooseWorkspace(m,i,l);if(`stopReason`in v)return stopped(v.stopReason,Error(v.stopReason===`unknownWorkspace`?`"${i}" is not one of your connected accounts (${_}).`:`Several accounts are connected (${_}); pick one with --git-repo <account>/<name>.`),{workspaces:g});let{workspace:y}=v,b;for(;;)try{info({message:`Creating ${s?`private`:`public`} repository ${y}/${a} from the template...`}),b=await createRemoteRepo({client:e,provider:t,workspace:y,repoName:a,isPrivate:s,templateArchiveUrl:c});break}catch(e){if(e instanceof CreateRemoteRepoError&&e.stopReason===`repoNameRejected`&&l){warning({message:e.message}),a=await _n({message:`Choose a different repository name:`,validate:e=>e.trim().length>0||`Enter a repository name.`});continue}return stopped(e instanceof CreateRemoteRepoError?e.stopReason:`repoCreateFailed`,e,{workspaces:g})}try{info({message:`Cloning ${b.httpsUrl}...`}),await cloneRepo(n,b.httpsUrl,l),p=!0,await f(n)}catch(e){return stopped(`gitSetupFailed`,e,{workspaces:g,remoteUrl:b.sshUrl,httpsUrl:b.httpsUrl})}let x;try{let t=await createGitActor({client:e,actorName:r,gitRepoUrl:b.sshUrl});info({message:`Created Actor ${t.name} on Apify.`}),x=t.id}catch(e){return stopped(`actorCreateFailed`,e,{workspaces:g,remoteUrl:b.sshUrl,httpsUrl:b.httpsUrl})}try{await registerDeploymentKey({client:e,provider:t,actorId:x,repoUrl:b.htmlUrl})}catch(e){return stopped(`deploymentKeyFailed`,e,{workspaces:g,remoteUrl:b.sshUrl,httpsUrl:b.httpsUrl,actorId:x})}return{remoteUrl:b.sshUrl,httpsUrl:b.httpsUrl,actorId:x,workspaces:g,stopReason:null,error:null,scaffolded:!0}},getGitStopUrl=(e,t,n)=>t===`notAuthorized`?getGitConnectUrl(e,n):t===`noWorkspace`?getAddWorkspaceUrl(e):null,buildGitSourceNextSteps=({actorName:e,stopReason:t,provider:n,remoteUrl:r,httpsUrl:i,repoName:a,scaffolded:s,actorId:c,account:l})=>{let u=`cd "${e}"`;switch(t){case`lookupFailed`:return[`Re-run with APIFY_CLI_DEBUG=1 to see the failing request`];case`notAuthorized`:return[`Connect your ${n} account to Apify: ${getGitConnectUrl(n,l)}`,`then re-run apify create`];case`noWorkspace`:return[`Give Apify access to an account: ${getAddWorkspaceUrl(n)}`,`then re-run apify create`];case`unknownWorkspace`:case`ambiguousWorkspace`:return[`Re-run naming the account: --git-repo <account>/${a}`];case`repoNameRejected`:return[`Re-run with a different repository name: --git-repo <account>/<other-name>`,`The name has to be free, and to use only letters, numbers, hyphens and underscores`];case`repoCreateFailed`:return[`Re-run apify create to try again`];case`gitSetupFailed`:return s?[u,`Apply the local configuration by hand: the error above says what failed`]:[`git clone ${i} "${e}"`,u];case`actorCreateFailed`:return[u,`Create an Actor from ${r} in Apify Console`];case`deploymentKeyFailed`:return[u,`Add the Apify deploy key in the Actor's Source settings before building: ${getConsoleUrl()}/actors/${c}`]}},logGitSourceOutcome=(e,t)=>{e.stopReason&&(warning({message:`${e.scaffolded?`Actor scaffolded, but the Git setup did not finish`:`The Actor was not created: the Git setup stopped`}: ${e.error}`}),info({message:`Next steps:\n${t.map(e=>` ${e}`).join(`
146
- `)}`}))};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, then guides you through what you want to build, a language, a template, and where the source code lives when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively (guided name, use case, language, and template prompts).`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{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`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:J.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Et} to find available template names.`,required:!1}),"use-case":J.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:Pr,required:!1}),language:J.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:Nr,required:!1}),"skip-dependency-install":J.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":J.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":J.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":J.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:J.string({description:`Where the Actor source code will live. With "github", Apify creates the repository on your connected GitHub account from the template, clones it here, and creates an Actor that builds from it.`,choices:[...Fr],required:!1}),"git-repo":J.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),origin:J.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:X.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:f}=this.flags,{templateArchiveUrl:p}=this.flags,m=!1,h=!n&&!p;if(l&&(!t||h)){let e=[...t?[]:[`the Actor name as an argument`],...h?[`--template <name>`]:[]],n=h?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let g=this.flags.source,_=Tt().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let v=e.cwd(),x=u(v,t);for(;;){let e=await V(x).catch(()=>null),n=e&&await ke(x).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),x=u(v,t);continue}e||await z(x,{recursive:!0});break}let S=null,C=null;if(this.telemetryData.create={fromArchiveUrl:!!p,origin:c},!p){let e=await getTemplateDefinition(n,_,{useCase:r,language:i});({archiveUrl:p,messages:S}=e),C=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(m=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(m=!0);let{isTTY:w}=await useStdin(),T=w&&!ue&&!l;g??=T?await promptGitSource():`apify`;let E=isGitProvider(g)?g:null;if(this.telemetryData.create.source=g,E&&s)throw Error(`--source ${g} clones a git repository, so --skip-git-init cannot apply.`);if(!E&&f)throw Error(`--git-repo only applies to a Git source, so add --source github or drop it.`);if(E&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${g}.`);let D=E?{provider:E,client:await getLoggedClientOrThrow(),account:toGitAccount(await getLocalUserInfo()),...parseGitRepoFlag(f,t)}:null,applyLocalConfig=async e=>{let n=getJsonFileContent(u(e,G));await setLocalConfig(Object.assign(n||Qt,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};E||(await downloadAndUnzip({url:p,pathTo:x}),await applyLocalConfig(x),await enhanceReadmeWithLocalSuffix(u(x,`README.md`),_));let O=u(x,`package.json`),k=null;D&&(k=await runGitSourceFlow({provider:D.provider,actorDir:x,actorName:t,workspace:D.workspace,repoName:D.repoName,isPrivate:!0,templateArchiveUrl:p,client:D.client,isInteractive:T,account:D.account,customize:applyLocalConfig}));let A=!1;a||await(await useCwdProject({cwd:x})).inspectAsync(async n=>{let r=b(nn);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await Ie(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:x}}),A=!0;return}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 ${on} or higher to be able to run Python Actors locally.`})}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(O,{name:t});let e=[`install`];if(m)switch(i.pmName){case`npm`:y(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`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:x},overrideCommand:i.pmName}),A=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${on} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${on} or higher to be able to run Python Actors locally.`});return}let t=u(x,`.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:x}}),i=(await usePythonRuntime({cwd:x,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:x}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:x}}),A=!0;break}}});let j={success:!0},M=await V(u(v,`.git`)).catch(()=>null),ee=await V(u(x,`.git`)).catch(()=>null),te=k!==null&&!k.scaffolded,N=!s&&!M&&!ee&&!te;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:x}})}catch(e){j={success:!1,error:e}}let ne=A?null:await getInstallCommandSuggestion(x),re=N&&j.success||!!ee;k?.stopReason&&(e.exitCode=1);let P=D&&k?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:k.stopReason,provider:D.provider,remoteUrl:k.remoteUrl,httpsUrl:k.httpsUrl,repoName:D.repoName,scaffolded:k.scaffolded,actorId:k.actorId,account:D.account}):buildNextSteps({actorName:t,dependenciesInstalled:A,installCommandSuggestion:ne}),ie=!k?.stopReason;l?printJsonToStdout({dir:x,actorJsonPath:u(x,G),template:C,source:g,nextSteps:P,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,remote:k?.remoteUrl??null,actorId:k?.actorId??null,stopReason:k?.stopReason??null,error:k?.error??null,gitConnectUrl:E?getGitStopUrl(E,k?.stopReason??null,D?.account):null,workspaces:k?.workspaces??null}):ie&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:A,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,installCommandSuggestion:ne,gitRemote:k?.remoteUrl&&k.actorId?{remoteUrl:k.remoteUrl,actorId:k.actorId}:null})})),N&&!j.success&&(warning({message:`Failed to initialize git repository: ${j.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),k&&!l&&logGitSourceOutcome(k,P)}};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:X.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 Rr={[U.JSON]:`application/json`,[U.JSONL]:`application/jsonl`,[U.CSV]:`text/csv`,[U.HTML]:`text/html`,[U.RSS]:`application/rss+xml`,[U.XML]:`application/xml`,[U.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:J.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:J.integer({description:`The offset in the dataset where to start getting items.`}),format:J.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(Rr),default:U.JSON})};static args={datasetId:X.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:Rr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
147
- `)}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 zr=new Z({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:X.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(K.display(i.createdAt))}`,`Modified: ${t.bold(K.display(i.modifiedAt))}`].join(`
146
+ 📖 Docs: https://docs.apify.com/platform/actors/development`,r&&(c+=`\n\n${r}`),c}async function executePrompts(e,t){return promptTemplate(e,t.useCase?useCaseFlagToTag(t.useCase)??`any-use-case`:await promptUseCase(),t.language?languageFlagToTag(t.language)??t.language:await promptLanguage())}async function promptActorName(){return await _n({message:`Name of your new Actor:`,validate:e=>{try{validateActorName(e)}catch(e){return e.message}return!0}})}async function promptUseCase(){let e=[...Mr.map(e=>({name:e.label,value:e.templateTag})),new ot,{name:`Any use case`,value:kr}];return xr({message:`What do you want to build?`,choices:e,default:Mr[0].templateTag,loop:!1})}async function promptLanguage(){let e=[...Nr.map(e=>({name:e.label,value:e.templateTag})),new ot,{name:`Any language`,value:Or}];return xr({message:`Choose the programming language of your new Actor:`,choices:e,default:Nr[0].templateTag,loop:!1})}async function promptTemplate(e,t,n){let{rows:r,separatorIndex:i,noExactMatchHint:a}=buildTemplateChoiceList(getTemplateRecommendation(e.templates,t,n),t,n);if(r.length===0)throw Error(`No Actor templates are available right now. Please try again later.`);let s=[];return r.forEach((e,t)=>{t===i&&s.push(new ot(`── The templates below don't exactly match your selection ──`)),s.push({name:e.label,value:e.template})}),a&&info({message:a,stdout:!1}),xr({message:`Choose a template for your new Actor. More info at https://apify.com/templates`,choices:s,default:r[0].template,loop:!1,pageSize:8})}const Ir=3e5,connectViaConsole=async(e,t,{abortSignal:n,account:r}={})=>{let i=getConsoleUrl(),a=Re(),s,c=new Promise(e=>{s=e}),l=createLocalApiServer({corsOrigin:new URL(i).origin,authToken:a,routes:{"POST /api/v1/git-provider-connected":(e,t)=>{t.end(),cliDebugPrint(`git-source`,`connected`,e),s({connected:!0})},"POST /api/v1/exit":(e,n)=>{n.end(),s({stopReason:`connectCancelled`,message:e.isWindowClosed?`Connecting your ${t} account stopped: the Apify Console window was closed.`:`Connecting your ${t} account was canceled in Apify Console.`})}}}),u=setTimeout(()=>s({stopReason:`connectTimedOut`,message:`Connecting your ${t} account did not finish within ${Ir/6e4} minutes.`}),Ir);n?.addEventListener(`abort`,()=>s({abandoned:!0}),{once:!0}),l.listen(0);let{port:f}=l.address(),p=new URL(getConsoleIntegrationsUrl(r));p.searchParams.set(`localCliCommand`,`connect-git-provider`),p.searchParams.set(`gitProvider`,e),p.searchParams.set(`localCliPort`,`${f}`),p.searchParams.set(`localCliToken`,a),p.searchParams.set(`localCliApiVersion`,`v1`);try{p.searchParams.set(`localCliComputerName`,encodeURIComponent(Ot()))}catch{}info({message:`Connect your ${t} account to Apify: ${p.href}`}),wt(p.href).catch(()=>void 0),info({message:`Waiting for the connection to complete in your browser...`});try{return await c}finally{clearTimeout(u),l.closeAllConnections(),l.close()}},Lr=[`apify`,`github`,`gitlab`,`bitbucket`],$={github:{label:`GitHub`,authorize:{endpoint:`https://github.com/login/oauth/authorize`,defaultClientId:`Iv1.e39b3ed87e74885f`,clientIdEnvVar:`APIFY_GITHUB_APP_CLIENT_ID`,defaultAppName:`apify`,appNameEnvVar:`APIFY_GITHUB_APP_NAME`,appInstallUrl:`https://github.com/apps/{app}/installations/new`,redirectPath:`/actors/new/git/connected?service=github`}},gitlab:{label:`GitLab`},bitbucket:{label:`Bitbucket`}},isGitProvider=e=>Object.hasOwn($,e),toGitAccount=({id:e,username:t,organizationOwnerUserId:n})=>({id:e,username:t,organizationOwnerUserId:n}),getGitConnectUrl=(t,n)=>{let{authorize:r}=$[t];if(!r)return getConsoleIntegrationsUrl(n);let i=new URL(r.redirectPath,getConsoleUrl()),a=getConsoleRoutePrefix(n);a&&i.searchParams.set(`routePrefix`,encodeURIComponent(a));let s=new URL(r.endpoint);return s.searchParams.set(`client_id`,e.env[r.clientIdEnvVar]||r.defaultClientId),s.searchParams.set(`redirect_uri`,i.href),s.href},getAddWorkspaceUrl=(t,n)=>{let{authorize:r}=$[t];return r?r.appInstallUrl.replace(`{app}`,e.env[r.appNameEnvVar]||r.defaultAppName):getConsoleIntegrationsUrl(n)},promptGitSource=async()=>xr({message:`Where will the source code live?`,choices:[{name:`Apify`,value:`apify`,description:`Deploy with "apify push". No Git provider involved.`},...Lr.filter(isGitProvider).map(e=>({name:$[e].label,value:e,description:`Apify creates a private repository on ${$[e].label} and builds the Actor from it.`}))],default:`apify`,loop:!1}),parseGitRepoFlag=(e,t)=>{if(!e)return{workspace:void 0,repoName:t};let n=e.lastIndexOf(`/`);if(n===-1)return{workspace:void 0,repoName:e};let r=e.slice(0,n),i=e.slice(n+1);if(!r||!i)throw Error(`Invalid --git-repo "${e}". Use "workspace/name" or just "name".`);return{workspace:r,repoName:i}},apiUrl=({client:e},t)=>`${e.baseUrl}/${t}`,authHeader=({client:e})=>({Authorization:`Bearer ${e.token}`}),fetchGitIntegrations=async e=>{let t=apiUrl(e,`integrations/git`);cliDebugPrint(`git-source`,`GET`,t);let n=await fetch(t,{headers:authHeader(e)}),r=await n.text();if(cliDebugPrint(`git-source`,`GET`,t,`->`,n.status,r.slice(0,400)),!n.ok)throw Error(`Could not read your Git integrations (${n.status} ${n.statusText}).`);return(()=>{try{return JSON.parse(r)}catch{return null}})()?.data??[]},readProviderState=(e,t)=>{let n=e.filter(e=>e.provider===t);return{connected:n.length>0,workspaces:n.flatMap(e=>e.workspaces.map(t=>({...t,providerId:e.id}))),addWorkspaceUrl:n.find(({addWorkspaceUrl:e})=>e)?.addWorkspaceUrl}},Rr=2e3,zr=18e4,pollForWorkspaces=async(e,{timeoutMs:t,abortSignal:n,onState:r})=>{let i=Date.now()+t,a=Rr,s=null;for(;Date.now()<i;){try{await Pt(a,void 0,{signal:n})}catch{return s}a=Math.min(Math.round(a*1.5),1e4);try{s=await e()}catch(e){cliDebugPrint(`git-source`,`poll failed:`,e);continue}if(s.workspaces.length)return s;await r?.(s)}return s},ensureUsableIntegration=async(e,{client:t,isInteractive:n,account:r})=>{let load=async()=>readProviderState(await fetchGitIntegrations({client:t}),e),i=await load();if(cliDebugPrint(`git-source`,`integrations:`,e,i.connected,`workspaces=${i.workspaces.length}`),i.workspaces.length||!n)return i;let{label:a,authorize:s}=$[e];if(!i.connected&&!s){let t=new AbortController,n=Date.now(),s=connectViaConsole(e,a,{abortSignal:t.signal,account:r}),c;try{c=await Promise.race([s.then(()=>null),pollForWorkspaces(load,{timeoutMs:Ir,abortSignal:t.signal})])}finally{t.abort()}if(c?.workspaces.length)return c;let l=await s;if(`stopReason`in l)return warning({message:l.message}),i;if(i=await load(),i.workspaces.length)return i;let u=Math.min(zr,Ir-(Date.now()-n));return u<Rr?i:(info({message:`Waiting for Apify to finish connecting your ${a} account...`}),await pollForWorkspaces(load,{timeoutMs:u})??i)}let c=null,offer=async t=>{let n=t.connected?t.addWorkspaceUrl??getAddWorkspaceUrl(e,r):getGitConnectUrl(e,r);n!==c&&(c=n,info({message:`${t.connected?`Give Apify access to a ${a} account`:`Connect your ${a} account to Apify`}: ${n}`}),await wt(n).catch(()=>void 0),info({message:r?.username?`Waiting for authorization to complete in your browser. It connects ${a} to the Apify account ${r.username}.`:`Waiting for authorization to complete in your browser...`}))};return await offer(i),await pollForWorkspaces(load,{timeoutMs:zr,onState:offer})??i},chooseWorkspace=async(e,t,n)=>{if(t){let n=t.toLowerCase(),r=e.find(({id:e,label:t})=>e.toLowerCase()===n||t.toLowerCase()===n);return r?{workspace:r}:{stopReason:`unknownWorkspace`}}return e.length===1?{workspace:e[0]}:n?{workspace:await xr({message:`Which account should own the repository?`,choices:e.map(e=>({name:e.label,value:e})),loop:!1})}:{stopReason:`ambiguousWorkspace`}};var CreateRemoteRepoError=class extends Error{stopReason;constructor(e,t){super(e),this.stopReason=t,this.name=`CreateRemoteRepoError`}};const Br=new Set([`integration-auth-error`,`invalid-git-auth-token`]),withoutUserInfo=e=>{if(!URL.canParse(e))return e;let t=new URL(e);return t.username=``,t.password=``,t.href},createRemoteRepo=async e=>{let{providerId:t,workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a}=e,s=apiUrl(e,`integrations/git/${t}/create-repo`),c=JSON.stringify({workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a});cliDebugPrint(`git-source`,`POST`,s,c);let l=await fetch(s,{method:`POST`,headers:{...authHeader(e),"Content-Type":`application/json`},body:c}),u=await l.text();cliDebugPrint(`git-source`,`POST`,s,`->`,l.status,u.slice(0,400));let f=(()=>{try{return JSON.parse(u)}catch{return null}})();if(l.ok&&f?.data)return{...f.data,httpsUrl:withoutUserInfo(f.data.httpsUrl)};let p=f?.error?.type,m=f?.error?.message||`${l.status} ${l.statusText}`;throw p&&Br.has(p)?new CreateRemoteRepoError(m,`notAuthorized`):p===`invalid-parameter`?new CreateRemoteRepoError(m,`repoNameRejected`):new CreateRemoteRepoError(m,`repoCreateFailed`)},cloneRepo=async(e,t,n)=>{await Ee(`git`,[`clone`,t,e],{env:n?void 0:{GIT_TERMINAL_PROMPT:`0`,GIT_SSH_COMMAND:`ssh -o BatchMode=yes`}})},createGitActor=async({client:e,actorName:t,gitRepoUrl:n})=>e.actors().create({name:t,versions:[{versionNumber:`0.0`,sourceType:pe.GIT_REPO,gitRepoUrl:n}]}),registerDeploymentKey=async({client:e,providerId:t,actorId:n,repoUrl:r})=>{let i=apiUrl({client:e},`integrations/git/${t}/register-deployment-key`),a=JSON.stringify({actorId:n,repoName:r});cliDebugPrint(`git-source`,`POST`,i,a);let s=await fetch(i,{method:`POST`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:a}),c=await s.text();if(cliDebugPrint(`git-source`,`POST`,i,`->`,s.status,c.slice(0,400)),s.ok)return;let l=(()=>{try{return JSON.parse(c).error?.message}catch{return null}})();throw Error(l||`${s.status} ${s.statusText}`)},runGitSourceFlow=async({client:e,provider:t,actorDir:n,actorName:r,workspace:i,repoName:a,isPrivate:s,templateArchiveUrl:c,isInteractive:l,account:u,customize:f})=>{let p=!1,stopped=(e,t,n={})=>({remoteUrl:null,httpsUrl:null,actorId:null,workspaces:null,scaffolded:p,...n,stopReason:e,error:t instanceof Error?t.message:String(t)}),m;try{m=await ensureUsableIntegration(t,{client:e,isInteractive:l,account:u})}catch(e){return stopped(`lookupFailed`,e)}let{label:h}=$[t],g=u?.username?`The Apify account ${u.username}`:`Apify`;if(!m.connected)return stopped(`notAuthorized`,Error(`${g} is not authorized to access your ${h} account.`));if(!m.workspaces.length)return stopped(`noWorkspace`,Error(`${g} has no ${h} account to create the repository in.`));let _=m.workspaces.map(({label:e})=>e),v=_.join(`, `),y=await chooseWorkspace(m.workspaces,i,l);if(`stopReason`in y)return stopped(y.stopReason,Error(y.stopReason===`unknownWorkspace`?`"${i}" is not one of your connected accounts (${v}).`:`Several accounts are connected (${v}); pick one with --git-repo <account>/<name>.`),{workspaces:_});let{workspace:b}=y,x;for(;;)try{info({message:`Creating ${s?`private`:`public`} repository ${b.label}/${a} from the template...`}),x=await createRemoteRepo({client:e,providerId:b.providerId,workspace:b.id,repoName:a,isPrivate:s,templateArchiveUrl:c});break}catch(e){if(e instanceof CreateRemoteRepoError&&e.stopReason===`repoNameRejected`&&l){warning({message:e.message}),a=await _n({message:`Choose a different repository name:`,validate:e=>e.trim().length>0||`Enter a repository name.`});continue}return stopped(e instanceof CreateRemoteRepoError?e.stopReason:`repoCreateFailed`,e,{workspaces:_})}let S=null;try{info({message:`Cloning ${x.httpsUrl}...`}),await cloneRepo(n,x.httpsUrl,l),p=!0,await f(n)}catch(e){let t=e.stderr?.trim();S=t?Error(t):e}let C;try{let t=await createGitActor({client:e,actorName:r,gitRepoUrl:x.sshUrl});info({message:`Created Actor ${t.name} on Apify.`}),C=t.id}catch(e){return stopped(`actorCreateFailed`,e,{workspaces:_,remoteUrl:x.sshUrl,httpsUrl:x.httpsUrl})}try{await registerDeploymentKey({client:e,providerId:b.providerId,actorId:C,repoUrl:x.htmlUrl})}catch(e){return stopped(`deploymentKeyFailed`,e,{workspaces:_,remoteUrl:x.sshUrl,httpsUrl:x.httpsUrl,actorId:C})}return S?stopped(`gitSetupFailed`,S,{workspaces:_,remoteUrl:x.sshUrl,httpsUrl:x.httpsUrl,actorId:C}):{remoteUrl:x.sshUrl,httpsUrl:x.httpsUrl,actorId:C,workspaces:_,stopReason:null,error:null,scaffolded:!0}},getGitStopUrl=(e,t,n)=>t===`notAuthorized`?getGitConnectUrl(e,n):t===`noWorkspace`?getAddWorkspaceUrl(e,n):null,buildGitSourceNextSteps=({actorName:e,stopReason:t,provider:n,remoteUrl:r,httpsUrl:i,repoName:a,scaffolded:s,actorId:c,account:l})=>{let u=`cd "${e}"`;switch(t){case`lookupFailed`:return[`Re-run with APIFY_CLI_DEBUG=1 to see the failing request`];case`notAuthorized`:return[`Connect your ${$[n].label} account to Apify: ${getGitConnectUrl(n,l)}`,`then re-run apify create`];case`noWorkspace`:return[`Give Apify access to a ${$[n].label} account: ${getAddWorkspaceUrl(n,l)}`,`then re-run apify create`];case`unknownWorkspace`:case`ambiguousWorkspace`:return[`Re-run naming the account: --git-repo <account>/${a}`];case`repoNameRejected`:return[`Re-run with a different repository name: --git-repo <account>/<other-name>`,`The name has to be free, and to use only letters, numbers, hyphens and underscores`];case`repoCreateFailed`:return[`Re-run apify create to try again`];case`gitSetupFailed`:return s?[u,`Apply the local configuration by hand: the error above says what failed`]:[`git clone ${i} "${e}"`,`Or clone over SSH, if you have a key for the provider: git clone ${r} "${e}"`,u];case`actorCreateFailed`:return[u,`Create an Actor from ${r} in Apify Console`];case`deploymentKeyFailed`:return[...s?[u]:[`git clone ${i} "${e}"`,u],`Add the Apify deploy key in the Actor's Source settings before building: ${getConsoleUrl()}/actors/${c}`]}},logGitSourceOutcome=(e,t)=>{e.stopReason&&(warning({message:`${e.scaffolded?`Actor scaffolded, but the Git setup did not finish`:e.actorId?`Actor created, but the clone failed`:`The Actor was not created: the Git setup stopped`}: ${e.error}`}),info({message:`Next steps:\n${t.map(e=>` ${e}`).join(`
147
+ `)}`}))};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, then guides you through what you want to build, a language, a template, and where the source code lives when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively (guided name, use case, language, and template prompts).`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{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`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:J.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Et} to find available template names.`,required:!1}),"use-case":J.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:Fr,required:!1}),language:J.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:Pr,required:!1}),"skip-dependency-install":J.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":J.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":J.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":J.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:J.string({description:`Where the Actor source code will live. With a Git provider, Apify creates the repository on your connected account from the template, clones it here, and creates an Actor that builds from it.`,choices:[...Lr],required:!1}),"git-repo":J.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),origin:J.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:X.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:f}=this.flags,{templateArchiveUrl:p}=this.flags,m=!1,h=!n&&!p;if(l&&(!t||h)){let e=[...t?[]:[`the Actor name as an argument`],...h?[`--template <name>`]:[]],n=h?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let g=this.flags.source,_=Tt().catch(e=>Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let v=e.cwd(),x=u(v,t);for(;;){let e=await V(x).catch(()=>null),n=e&&await ke(x).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),x=u(v,t);continue}e||await z(x,{recursive:!0});break}let S=null,C=null;if(this.telemetryData.create={fromArchiveUrl:!!p,origin:c},!p){let e=await getTemplateDefinition(n,_,{useCase:r,language:i});({archiveUrl:p,messages:S}=e),C=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(m=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(m=!0);let{isTTY:w}=await useStdin(),T=w&&!ue&&!l;g??=T?await promptGitSource():`apify`;let E=isGitProvider(g)?g:null;if(this.telemetryData.create.source=g,E&&s)throw Error(`--source ${g} clones a git repository, so --skip-git-init cannot apply.`);if(!E&&f)throw Error(`--git-repo only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(E&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${g}.`);let D=E?{provider:E,client:await getLoggedClientOrThrow(),account:toGitAccount(await getLocalUserInfo()),...parseGitRepoFlag(f,t)}:null,applyLocalConfig=async e=>{let n=getJsonFileContent(u(e,G));await setLocalConfig(Object.assign(n||Qt,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};E||(await downloadAndUnzip({url:p,pathTo:x}),await applyLocalConfig(x),await enhanceReadmeWithLocalSuffix(u(x,`README.md`),_));let O=u(x,`package.json`),k=null;D&&(k=await runGitSourceFlow({provider:D.provider,actorDir:x,actorName:t,workspace:D.workspace,repoName:D.repoName,isPrivate:!0,templateArchiveUrl:p,client:D.client,isInteractive:T,account:D.account,customize:applyLocalConfig}));let A=!1;a||await(await useCwdProject({cwd:x})).inspectAsync(async n=>{let r=b(nn);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await Ie(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:x}}),A=!0;return}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 ${on} or higher to be able to run Python Actors locally.`})}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(O,{name:t});let e=[`install`];if(m)switch(i.pmName){case`npm`:y(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`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:x},overrideCommand:i.pmName}),A=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${on} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${on} or higher to be able to run Python Actors locally.`});return}let t=u(x,`.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:x}}),i=(await usePythonRuntime({cwd:x,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:x}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:x}}),A=!0;break}}});let j={success:!0},M=await V(u(v,`.git`)).catch(()=>null),ee=await V(u(x,`.git`)).catch(()=>null),te=k!==null&&!k.scaffolded,N=!s&&!M&&!ee&&!te;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:x}})}catch(e){j={success:!1,error:e}}let ne=A?null:await getInstallCommandSuggestion(x),re=N&&j.success||!!ee;k?.stopReason&&(e.exitCode=1);let P=D&&k?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:k.stopReason,provider:D.provider,remoteUrl:k.remoteUrl,httpsUrl:k.httpsUrl,repoName:D.repoName,scaffolded:k.scaffolded,actorId:k.actorId,account:D.account}):buildNextSteps({actorName:t,dependenciesInstalled:A,installCommandSuggestion:ne}),ie=!k?.stopReason;l?printJsonToStdout({dir:x,actorJsonPath:u(x,G),template:C,source:g,nextSteps:P,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,remote:k?.remoteUrl??null,actorId:k?.actorId??null,stopReason:k?.stopReason??null,error:k?.error??null,gitConnectUrl:E?getGitStopUrl(E,k?.stopReason??null,D?.account):null,workspaces:k?.workspaces??null}):ie&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:A,postCreate:S?.postCreate??null,gitRepositoryInitialized:re,installCommandSuggestion:ne,gitRemote:k?.remoteUrl&&k.actorId?{remoteUrl:k.remoteUrl,actorId:k.actorId}:null})})),N&&!j.success&&(warning({message:`Failed to initialize git repository: ${j.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),k&&!l&&logGitSourceOutcome(k,P)}};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:X.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 Vr={[U.JSON]:`application/json`,[U.JSONL]:`application/jsonl`,[U.CSV]:`text/csv`,[U.HTML]:`text/html`,[U.RSS]:`application/rss+xml`,[U.XML]:`application/xml`,[U.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:J.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:J.integer({description:`The offset in the dataset where to start getting items.`}),format:J.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(Vr),default:U.JSON})};static args={datasetId:X.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:Vr[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
148
+ `)}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 Hr=new Z({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:X.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(K.display(i.createdAt))}`,`Modified: ${t.bold(K.display(i.modifiedAt))}`].join(`
148
149
  `),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(`
149
- `);zr.pushRow({Row1:v,Row2:S});let C=zr.render(2).split(`
150
+ `);Hr.pushRow({Row1:v,Row2:S});let C=Hr.render(2).split(`
150
151
  `).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(`
151
152
  `),``,_].join(`
152
- `),stdout:!0})}};const Br=new Z({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:J.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:J.integer({description:`Number of datasets that will be listed.`,default:20}),desc:J.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:J.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`);Br.pushRow({"Dataset ID":e.id,Created:K.display(e.createdAt),Items:`${e.itemCount}`,Modified:K.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:Br.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:X.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:X.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||dn;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:J.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:X.string({description:`The dataset ID or name to delete.`,required:!0}),newName:X.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:X.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 Y({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 Vr=`https://apify.github.io/input-schema-editor-react/`,Hr=new URL(Vr).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:X.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 '${G}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
153
- `}),info({message:`Editing input schema at "${t}"...`});let n=Re(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:Hr,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=D(t)?j(t,{encoding:`utf-8`}):`{}
153
+ `),stdout:!0})}};const Ur=new Z({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:J.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:J.integer({description:`Number of datasets that will be listed.`,default:20}),desc:J.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:J.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`);Ur.pushRow({"Dataset ID":e.id,Created:K.display(e.createdAt),Items:`${e.itemCount}`,Modified:K.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:Ur.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:X.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:X.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||dn;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:J.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:X.string({description:`The dataset ID or name to delete.`,required:!0}),newName:X.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:X.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 Y({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 Wr=`https://apify.github.io/input-schema-editor-react/`,Gr=new URL(Wr).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:X.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 '${G}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
154
+ `}),info({message:`Editing input schema at "${t}"...`});let n=Re(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:Gr,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=D(t)?j(t,{encoding:`utf-8`}):`{}
154
155
  `,a.length>3&&(r=Ft(a).indent||r),a&&(i=a[a.length-1]===`
155
156
  `),D(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 s;try{s=JSON.parse(a||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(s),info({message:`Input schema sent to editor.`})},"POST /api/v1/input-schema":(e,n)=>{try{info({message:`Got input schema from editor...`});let a=JSON.stringify(e,null,r);i&&(a+=`
156
- `);let s=c(t);D(s)||k(s,{recursive:!0}),P(t,a,{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)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let l=`${Vr}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${l}"...`}),await wt(l)}};const Ur=u(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=c(It(import.meta.url));for(;;){let t=u(e,Ur);if(D(t))return j(t,`utf-8`);let n=c(e);if(n===e)return null;e=n}}var 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:X.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:J.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=q.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
157
- `,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 Wr=[`.dockerignore`,`.gitignore`],Gr=It(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Lt.walk(e,async(r,i,a)=>{if(i===e)return;let c=f(e,i),l=c.split(m).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(m),p=u(t,l);if(a.isDirectory())return D(p)||k(p),merge(i,p);c.includes(`.template`)?P(u(t,l.replace(`.template`,``)),Rt.compile(j(i,`utf8`))(n.bindings)):D(p)&&Wr.includes(s(l))?S(p,j(i)):T(i,p)})}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 xr({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`.${f(e,t).split(m).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 Tt(Dt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);D(Gr)&&N(Gr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Gr}),info({message:`Wrapping the Scrapy project...`}),await merge(Gr,e,{bindings:r});let s=new Pe;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=E(u(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
157
+ `);let s=c(t);D(s)||k(s,{recursive:!0}),P(t,a,{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)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let l=`${Wr}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${l}"...`}),await wt(l)}};const Kr=u(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=c(It(import.meta.url));for(;;){let t=u(e,Kr);if(D(t))return j(t,`utf-8`);let n=c(e);if(n===e)return null;e=n}}var 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:X.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:J.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=q.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
158
+ `,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 qr=[`.dockerignore`,`.gitignore`],Jr=It(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Lt.walk(e,async(r,i,a)=>{if(i===e)return;let c=f(e,i),l=c.split(m).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(m),p=u(t,l);if(a.isDirectory())return D(p)||k(p),merge(i,p);c.includes(`.template`)?P(u(t,l.replace(`.template`,``)),Rt.compile(j(i,`utf8`))(n.bindings)):D(p)&&qr.includes(s(l))?S(p,j(i)):T(i,p)})}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 xr({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`.${f(e,t).split(m).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 Tt(Dt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);D(Jr)&&N(Jr,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Jr}),info({message:`Wrapping the Scrapy project...`}),await merge(Jr,e,{bindings:r});let s=new Pe;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=E(u(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
158
159
  `,()=>{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.
159
160
 
160
161
  It adds the following features:
@@ -164,17 +165,17 @@ It adds the following features:
164
165
  ...
165
166
  `;static args={path:X.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.
166
167
  If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
167
- Creates the '${G}' file and the '${Zt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Zt}' 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:X.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:J.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=s(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path,t=e.includes(`.`)?e.split(`.`).pop():e;a=sanitizeActorName(t)}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 Y({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let c=await useActorConfig({cwd:n});if(c.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${G}', the file already exists in the current directory.`});else{if(c.isErr()){error({message:c.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=c.isOkAnd(e=>e.exists)?c.unwrap().config.name:null;for(;!e;)try{let t=await _n({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...Qt,...c.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":X.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":X.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:X.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 Y({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":J.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:X.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:X.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 Kr=new Z({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:X.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(K.display(i.createdAt))}`,`Modified: ${t.bold(K.display(i.modifiedAt))}`].join(`
168
+ Creates the '${G}' file and the '${Zt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Zt}' 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:X.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:J.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=s(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path,t=e.includes(`.`)?e.split(`.`).pop():e;a=sanitizeActorName(t)}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 Y({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let c=await useActorConfig({cwd:n});if(c.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${G}', the file already exists in the current directory.`});else{if(c.isErr()){error({message:c.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=c.isOkAnd(e=>e.exists)?c.unwrap().config.name:null;for(;!e;)try{let t=await _n({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...Qt,...c.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":X.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":X.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:X.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 Y({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":J.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:X.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:X.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 Yr=new Z({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:X.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(K.display(i.createdAt))}`,`Modified: ${t.bold(K.display(i.modifiedAt))}`].join(`
168
169
  `),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(`
169
- `);Kr.pushRow({Row1:_,Row2:x});let S=Kr.render(2).split(`
170
+ `);Yr.pushRow({Row1:_,Row2:x});let S=Yr.render(2).split(`
170
171
  `).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(`
171
172
  `),``,g].join(`
172
- `),stdout:!0})}};const qr=new Z({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:J.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":J.string({description:`The key to start the list from.`})};static args={storeId:X.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)qr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:qr.render(1),stdout:!0})}};const Jr=new Z({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:J.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:J.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:J.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:J.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;Jr.pushRow({"Store ID":e.id,Created:K.display(e.createdAt),Modified:K.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})}},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:J.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:X.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:X.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:X.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 Y({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":J.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:X.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:X.string({description:`The key of the item in the key-value store.`,required:!0}),value:X.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.
173
+ `),stdout:!0})}};const Xr=new Z({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:J.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":J.string({description:`The key to start the list from.`})};static args={storeId:X.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)Xr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Xr.render(1),stdout:!0})}};const Zr=new Z({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:J.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:J.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:J.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:J.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;Zr.pushRow({"Store ID":e.id,Created:K.display(e.createdAt),Modified:K.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:Zr.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:J.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:X.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:X.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:X.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 Y({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":J.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:X.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:X.string({description:`The key of the item in the key-value store.`,required:!0}),value:X.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.
173
174
 
174
175
  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 Y({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=D(t)?await B(t,`utf-8`):``,l=s.trim(),u;if(l){let e;try{e=Ct.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
175
- `)[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 l=c??{};if(Object.prototype.hasOwnProperty.call(l,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;l[r]=i,e[n]=l,u=Ct.update(s,e)}else{let e={[n]:{[r]:i}};u=`${Ct.stringify(e,{mode:`json`,indent:2})}\n`}await z(c(t),{recursive:!0});let f=`${t}.${e.pid}.tmp`;try{await H(f,u,`utf-8`),await Ae(f,t)}catch(e){throw await je(f,{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 Yr=`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(`
176
- `)})}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 Ie(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await Ee(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=u(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:Yr,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 ${Yr} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Yr,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:Yr,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=u(r,`.codex`,`config.toml`),a=[`mcp`,`add`,Yr,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Yr}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
177
- `);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>`})},Xr={"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(Xr);function isSupportedClient(e){return e in Xr}const Qr=new Set([`codex`]);function clientNeedsToken(e){return!Qr.has(e)}function getClientHandler(e){return Xr[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:X.string({required:!0,description:`Target MCP client. One of: ${Zr.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry without prompting.`),token:J.string({char:`t`,description:`Apify API token to embed in the config. Defaults to the token from 'apify login'.`}),url:J.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:J.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=>`
176
+ `)[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 l=c??{};if(Object.prototype.hasOwnProperty.call(l,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;l[r]=i,e[n]=l,u=Ct.update(s,e)}else{let e={[n]:{[r]:i}};u=`${Ct.stringify(e,{mode:`json`,indent:2})}\n`}await z(c(t),{recursive:!0});let f=`${t}.${e.pid}.tmp`;try{await H(f,u,`utf-8`),await Ae(f,t)}catch(e){throw await je(f,{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 Qr=`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(`
177
+ `)})}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 Ie(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await Ee(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=u(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:Qr,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 ${Qr} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Qr,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:Qr,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=u(r,`.codex`,`config.toml`),a=[`mcp`,`add`,Qr,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Qr}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
178
+ `);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>`})},$r={"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)})})},ei=Object.keys($r);function isSupportedClient(e){return e in $r}const ti=new Set([`codex`]);function clientNeedsToken(e){return!ti.has(e)}function getClientHandler(e){return $r[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:X.string({required:!0,description:`Target MCP client. One of: ${ei.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry without prompting.`),token:J.string({char:`t`,description:`Apify API token to embed in the config. Defaults to the token from 'apify login'.`}),url:J.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:J.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: ${ei.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=>`
178
179
  (async () => {
179
180
  const [nodeModule, process, path, fs] = await Promise.all([
180
181
  import('node:module'),
@@ -212,7 +213,7 @@ try:
212
213
  print(${e}.__version__)
213
214
  except:
214
215
  print('n/a')
215
- `,$r={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}),R;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}),R;let r=$r[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),R;try{let n=await Ee(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}),R):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),Te(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),R}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
216
+ `,ni={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}),R;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}),R;let r=ni[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),R;try{let n=await Ee(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}),R):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),Te(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),R}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
216
217
  Stores data in local '${Zt}' 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:J.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
217
218
  For crawlee projects, this is the default behavior, and the flag is optional.
218
219
  Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:J.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:J.string({description:[`Optional entrypoint for running with injected environment variables.`,`
@@ -222,15 +223,15 @@ Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,ex
222
223
  `;break;default:p=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:
223
224
  `}if(t){let e={...a,...t.input},i=_t(s,r,e);if(i.length>0)throw Error(`${p}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
224
225
  `)}`);let l=`${kn}${n}`,m=u(c(f),`${l}.json`);return await z(c(f),{recursive:!0}),await H(m,JSON.stringify(e,null,2)),{tempInputKey:l,tempInputFilePath:m}}if(!l)return await z(c(f),{recursive:!0}),await H(f,JSON.stringify(a,null,2)),{existingInput:l,inputFilePath:f,writtenAt:Date.now()};if(et.getExtension(l.contentType)===`json`){let e=JSON.parse(l.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=_t(s,r,t);if(i.length>0)throw Error(`${p}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
225
- `)}`);let m=`${kn}${n}`,h=u(c(f),`${m}.json`);return await H(h,JSON.stringify(t,null,2)),{tempInputKey:m,tempInputFilePath:h}}return null}};const ei=[I.READY,I.RUNNING],ti=[I.ABORTING,I.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:X.string({required:!0,description:`The run ID to abort.`})};static flags={force:J.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(!ei.includes(n.status)){ti.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 ni=new Z({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),ri={"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:X.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:J.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(ni.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${K.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${K.display(r.finishedAt)} (took ${t.gray(Ln.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${Ln.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=getConsoleUrl(),_=`${g}/actors/${r.actId}/runs/${r.id}`,v=`${g}/storage/datasets/${r.defaultDatasetId}`,y=`${g}/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${v}`),f.push(`${t.blue(`View saved items`)}: ${y}`),f.push(`${t.blue(`View in Apify Console`)}: ${_}`),simpleLog({message:f.join(`
226
- `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(ri))ni.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(ri)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:ni.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`:ni.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:ni.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:X.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 ii=new Z({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:J.integer({description:`Number of runs that will be skipped.`,default:0}),limit:J.integer({description:`Number of runs that will be listed.`,default:10}),desc:J.boolean({description:`Sort runs in descending order.`,default:!1}),compact:J.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:X.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(`${Ln.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${Ln.format(r,void 0,{left:``})}`)}ii.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":Pn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(ii.render(+!i)),simpleLog({message:f.join(`
227
- `),stdout:!0})}};const ai=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!ai.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 oi=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!oi.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 Y({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).
226
+ `)}`);let m=`${kn}${n}`,h=u(c(f),`${m}.json`);return await H(h,JSON.stringify(t,null,2)),{tempInputKey:m,tempInputFilePath:h}}return null}};const ri=[I.READY,I.RUNNING],ii=[I.ABORTING,I.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:X.string({required:!0,description:`The run ID to abort.`})};static flags={force:J.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(!ri.includes(n.status)){ii.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 ai=new Z({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),oi={"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:X.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:J.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(ai.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${K.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${K.display(r.finishedAt)} (took ${t.gray(Ln.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${Ln.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=getConsoleUrl(),_=`${g}/actors/${r.actId}/runs/${r.id}`,v=`${g}/storage/datasets/${r.defaultDatasetId}`,y=`${g}/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${v}`),f.push(`${t.blue(`View saved items`)}: ${y}`),f.push(`${t.blue(`View in Apify Console`)}: ${_}`),simpleLog({message:f.join(`
227
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(oi))ai.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(oi)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:ai.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`:ai.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:ai.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:X.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 si=new Z({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:J.integer({description:`Number of runs that will be skipped.`,default:0}),limit:J.integer({description:`Number of runs that will be listed.`,default:10}),desc:J.boolean({description:`Sort runs in descending order.`,default:!1}),compact:J.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:X.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(`${Ln.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${Ln.format(r,void 0,{left:``})}`)}si.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":Pn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(si.render(+!i)),simpleLog({message:f.join(`
228
+ `),stdout:!0})}};const ci=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!ci.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 li=[I.SUCCEEDED,I.FAILED,I.ABORTED,I.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:X.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(!li.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 Y({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).
228
229
  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:X.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:J.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":J.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.
229
- 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:X.string({required:!0,description:`Name of the secret.`}),value:X.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const si=new Z({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)si.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:si.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:X.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 '${G}' 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()}},TaskPublishCommand=class extends ApifyCommand{static name=`publish`;static description=`Publishes the task on its public landing page.
230
+ 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:X.string({required:!0,description:`Name of the secret.`}),value:X.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const ui=new Z({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)ui.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:ui.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:X.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 '${G}' 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()}},TaskPublishCommand=class extends ApifyCommand{static name=`publish`;static description=`Publishes the task on its public landing page.
230
231
  The task must belong to a public Actor and have its public display configuration set up on the task Publication tab in Apify Console. Requires write access to the task and to its Actor.`;static examples=[{description:`Publish a task by name.`,command:`apify task publish my-task`},{description:`Publish a task by full name.`,command:`apify task publish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-publish`;static args={taskId:X.string({required:!0,description:`Name of the task to publish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getLocalUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l){error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;return}try{await c.publish(),success({message:`Task ${t.yellow(l.name)} has been published.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to publish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
231
232
  Customize with --memory and --timeout flags.
232
233
  `;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:X.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.`)}},TaskUnpublishCommand=class extends ApifyCommand{static name=`unpublish`;static description=`Unpublishes the task from its public landing page.
233
- The public display configuration is preserved, so the task can be published again later. Requires write access to the task and to its Actor.`;static examples=[{description:`Unpublish a task by name.`,command:`apify task unpublish my-task`},{description:`Unpublish a task by full name.`,command:`apify task unpublish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-unpublish`;static args={taskId:X.string({required:!0,description:`Name of the task to unpublish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getLocalUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l){error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;return}try{await c.unpublish(),success({message:`Task ${t.yellow(l.name)} has been unpublished.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to unpublish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run and publish saved Apify tasks (named Actor configurations). 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,TaskPublishCommand,TaskUnpublishCommand];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()}};const ci=new Z({allColumns:[`Template`,`Label`,`Language`,`Use cases`],mandatoryColumns:[`Template`,`Language`,`Use cases`]});var TemplatesLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints all available Actor templates, including the use cases and language each one supports.`;static examples=[{description:`List all available templates.`,command:`apify templates ls`},{description:`List templates as JSON (includes the use-case tags for scripting).`,command:`apify templates ls --json`}];static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=await Tt().catch(e=>{throw Error(`Could not fetch template list from server. Cause: ${e?.message}`)});if(e){printJsonToStdout(t.templates);return}if(t.templates.length===0){info({message:`There are no templates available.`,stdout:!0});return}for(let e of t.templates)ci.pushRow({Template:e.name,Label:e.label,Language:languageLabel(e.category),"Use cases":(e.useCases??[]).join(`, `)});simpleLog({message:ci.render(1),stdout:!0})}},TemplatesIndexCommand=class extends ApifyCommand{static name=`templates`;static description=`Explore the Actor templates used by "apify create".`;static group=`Local Actor Development`;static subcommands=[TemplatesLsCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
234
+ The public display configuration is preserved, so the task can be published again later. Requires write access to the task and to its Actor.`;static examples=[{description:`Unpublish a task by name.`,command:`apify task unpublish my-task`},{description:`Unpublish a task by full name.`,command:`apify task unpublish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-unpublish`;static args={taskId:X.string({required:!0,description:`Name of the task to unpublish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getLocalUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l){error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;return}try{await c.unpublish(),success({message:`Task ${t.yellow(l.name)} has been unpublished.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to unpublish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run and publish saved Apify tasks (named Actor configurations). 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,TaskPublishCommand,TaskUnpublishCommand];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()}};const di=new Z({allColumns:[`Template`,`Label`,`Language`,`Use cases`],mandatoryColumns:[`Template`,`Language`,`Use cases`]});var TemplatesLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints all available Actor templates, including the use cases and language each one supports.`;static examples=[{description:`List all available templates.`,command:`apify templates ls`},{description:`List templates as JSON (includes the use-case tags for scripting).`,command:`apify templates ls --json`}];static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=await Tt().catch(e=>{throw Error(`Could not fetch template list from server. Cause: ${e?.message}`)});if(e){printJsonToStdout(t.templates);return}if(t.templates.length===0){info({message:`There are no templates available.`,stdout:!0});return}for(let e of t.templates)di.pushRow({Template:e.name,Label:e.label,Language:languageLabel(e.category),"Use cases":(e.useCases??[]).join(`, `)});simpleLog({message:di.render(1),stdout:!0})}},TemplatesIndexCommand=class extends ApifyCommand{static name=`templates`;static description=`Explore the Actor templates used by "apify create".`;static group=`Local Actor Development`;static subcommands=[TemplatesLsCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
234
235
 
235
236
  When a path argument is provided, validates only the input schema at that path.
236
237
 
@@ -238,5 +239,5 @@ When no path is provided, validates all schemas found in '${G}':
238
239
  - Input schema (from "input" key or default locations)
239
240
  - Dataset schema (from "storages.dataset")
240
241
  - Output schema (from "output")
241
- - 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:X.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${G}'.`})};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});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${G}'`}`});let t=new jn({strict:!1});gt(t,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 '${G}'`}`}),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 '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const li=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],ui=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,li as n,processVersionCheck as r,ui as t};
242
- //# sourceMappingURL=_register-CikcJ6D_.js.map
242
+ - 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:X.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${G}'.`})};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});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${G}'`}`});let t=new jn({strict:!1});gt(t,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 '${G}'`}`}),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 '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const fi=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],pi=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,fi as n,processVersionCheck as r,pi as t};
243
+ //# sourceMappingURL=_register-Ck8cIF7W.js.map