apify-cli 0.21.10-beta.21 → 0.21.10-beta.23

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,51 +1,51 @@
1
- var La=Object.defineProperty;var c=(r,e)=>La(r,"name",{value:e,configurable:!0});import ve from"process";import{parseArgs as pn}from"util";import Pr from"chalk";import{satisfies as _c}from"semver";import Rs from"chalk";import lc from"indent-string";import cc from"widest-line";import uc from"wrap-ansi";import Da from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Da.gray(`[${r}]`),...e)}c(T,"cliDebugPrint");import{realpathSync as Fa}from"fs";import{dirname as ka}from"path";import ct from"chalk";function ze(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}c(ze,"internalLog");function R(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}c(R,"simpleLog");function p(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.red("Error:"),r.message]})}c(p,"error");function x(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.yellow.bold("Warning:"),r.message]})}c(x,"warning");function $(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.green("Success:"),r.message]})}c($,"success");function he(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.gray("Run:"),r.message]})}c(he,"run");function b(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.white("Info:"),r.message]})}c(b,"info");function cs(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.blue(r.message),r.url]})}c(cs,"link");var si="0.0.0";var Ua="0.21.10-beta.21",Ma="f51ac8c35c23b72392161cb864248bdfd1f4076c";function ja(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return"bundle";let r=process.argv[1];if(!r)return x({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Fa(r);return process.env.VOLTA_HOME&&e.includes(process.env.VOLTA_HOME)?"volta":e.includes("homebrew/Cellar")||e.includes("linuxbrew/Cellar")?"homebrew":process.env.PNPM_HOME&&e.includes(process.env.PNPM_HOME)?"pnpm":process.env.BUN_INSTALL&&e.includes(process.env.BUN_INSTALL)?"bun":"npm"}c(ja,"detectInstallMethod");function Va(){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}}c(Va,"getRuntimeInfo");var Et=null;function K(){if(Et)return Et;let r=ja(),e=Va();return Et={version:Ua,hash:Ma,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform==="win32"?"windows":process.platform,runtime:e,extraRuntimeData:e.nodeVersion?`(emulating node ${e.nodeVersion})`:"",installMethod:r,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${e.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:""}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes("beta")||this.version==="0.21.10-beta.21"}},r==="bundle"&&(Et.installPath=ka(process.execPath)),Et}c(K,"useCLIMetadata");import{existsSync as vl,mkdirSync as Tl,readFileSync as Il,writeFileSync as Cl}from"fs";import{dirname as El}from"path";import{cryptoRandomObjectId as $l}from"@apify/utilities";import{homedir as Ga}from"os";import{join as Xe}from"path";import{KEY_VALUE_STORE_KEYS as Ya,META_ORIGINS as Ha}from"@apify/consts";var ii={name:"apify-cli",version:"0.21.10-beta.21",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '\\[api\\]'","test:python":"vitest run --testNamePattern '\\[python\\]'","test:cucumber":'cross-env NODE_OPTIONS="--import tsx" cucumber-js',lint:"eslint src test scripts features --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts features --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=20"},dependencies:{"@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.15.1","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^10.1.15","@inquirer/input":"^4.2.1","@inquirer/password":"^4.0.17","@inquirer/select":"^4.3.1","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.17.1","apify-client":"^2.12.6",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.5.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.1.0",globby:"~14.1.0",handlebars:"~4.7.8","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","lodash.clonedeep":"^4.5.0",mime:"~4.0.4",open:"~10.2.0",rimraf:"~6.0.1",semver:"~7.7.0","string-width":"^7.2.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",which:"^5.0.0","widest-line":"^5.0.0","wrap-ansi":"^9.0.0"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@cucumber/cucumber":"^12.0.0","@types/adm-zip":"^0.5.5","@types/archiver":"^6.0.2","@types/bun":"^1.2.5","@types/chai":"^4.3.17","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11","@types/is-ci":"^3.0.4","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/lodash.clonedeep":"^4","@types/mime":"^4.0.0","@types/node":"^22.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4",chai:"^4.4.1","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","lint-staged":"^16.0.0","mdast-util-from-markdown":"^2.0.2","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^5.8.3","typescript-eslint":"^8.31.0",vitest:"^3.0.0"},volta:{node:"22.18.0",yarn:"4.9.2"},packageManager:"yarn@4.9.2",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"}};var Ze="storage",us="apify_storage",ms=1,tr={actorSpecification:ms,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},ni=1440*60*1e3,ut=c(()=>{let r=Xe(Ga(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?Xe(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),ne=c(()=>Xe(ut(),"auth.json"),"AUTH_FILE_PATH"),rr=c(()=>Xe(ut(),"secrets.json"),"SECRETS_FILE_PATH"),or=c(()=>Xe(ut(),"state.json"),"STATE_FILE_PATH"),sr=c(()=>Xe(ut(),"telemetry.json"),"TELEMETRY_FILE_PATH"),ir="apify.json",ds=".actor",Ja="actor.json",j=Xe(ds,Ja),ps=new RegExp(`^${Ya.INPUT}\\..*`),ye=ii.engines.node,ai={"X-Apify-Request-Origin":Ha.CLI},Qe="3.9.0",li=".venv";import{createWriteStream as el,existsSync as le,mkdirSync as tl,readdirSync as fi,readFileSync as Ot,writeFileSync as ar}from"fs";import{mkdir as rl,readFile as ol}from"fs/promises";import{get as sl}from"https";import{dirname as gi,join as we}from"path";import ae from"process";import{finished as il}from"stream/promises";import{DurationFormatter as hi,TimeTypes as et}from"@sapphire/duration";import{Timestamp as fs}from"@sapphire/timestamp";import nl from"adm-zip";import al from"ajv/dist/2019.js";import{ApifyClient as yi}from"apify-client";import ll from"archiver";import{AxiosHeaders as cl}from"axios";import ul from"escape-string-regexp";import{globby as wi}from"globby";import{getEncoding as ml}from"istextorbinary";import{Mime as dl}from"mime";import pl from"mime/types/other.js";import fl from"mime/types/standard.js";import{gte as gl,minVersion as hl,satisfies as yl}from"semver";import{ACTOR_ENV_VARS as gs,ACTOR_JOB_TERMINAL_STATUSES as wl,ACTOR_NAME as xt,APIFY_ENV_VARS as Al,KEY_VALUE_STORE_KEYS as pi,LOCAL_ACTOR_ENV_VARS as hs,LOCAL_STORAGE_SUBDIRS as ys,SOURCE_FILE_FORMATS as Rt}from"@apify/consts";import{existsSync as Ka,mkdirSync as qa}from"fs";import{readFile as Wa,stat as ci,unlink as za,writeFile as Xa}from"fs/promises";import{join as ui,sep as Za}from"path";import{rimraf as Qa}from"rimraf";var mi=c(async(r,e={},t=null)=>{let o=await Wa(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await Xa(r,JSON.stringify(i,null," "))},"updateLocalJson"),nr=c((r,e)=>{e||(e=r,r="."),e.split(Za).reduce((o,s)=>(o=ui(o,s),Ka(o)||qa(o),o),r)},"ensureFolderExistsSync"),$t=c(async r=>{await Qa(r)},"rimrafPromised"),_t=c(async r=>{(await ci(r)).isFile()&&await za(r)},"deleteFile"),di=c(async(r,e)=>(await Promise.all(r.map(async s=>ci(ui(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var mt=al,lr=c(async r=>new Promise((e,t)=>{sl(r,o=>{o.statusCode===301||o.statusCode===302?(e(lr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),ce=c(()=>{let r=Al.LOCAL_STORAGE_DIR;return ae.env[r]||ae.env.CRAWLEE_STORAGE_DIR||Ze},"getLocalStorageDir"),Ie=c(r=>{let e=gs.DEFAULT_KEY_VALUE_STORE_ID,t=r||ae.env[e]||hs[e];return we(ce(),ys.keyValueStores,t)},"getLocalKeyValueStorePath"),Ai=c(r=>{let e=gs.DEFAULT_DATASET_ID,t=r||ae.env[e]||hs[e];return we(ce(),ys.datasets,t)},"getLocalDatasetPath"),Si=c(r=>{let e=gs.DEFAULT_REQUEST_QUEUE_ID,t=r||ae.env[e]||hs[e];return we(ce(),ys.requestQueues,t)},"getLocalRequestQueuePath"),D=c(async()=>{let r={};try{let e=await ol(ne(),"utf-8");r=JSON.parse(e)}catch{return{}}if(!r.username&&!r.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return r},"getLocalUserInfo");async function C(){let r=await Nt();if(!r)throw new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}c(C,"getLoggedClientOrThrow");var bi=c(r=>{if(!r&&le(ut())&&le(ne())){let e=Ot(ne(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),ws=c((r,e)=>(r=bi(r),{token:r,baseUrl:e||ae.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new cl;for(let[o,s]of Object.entries(ai))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Nt(r,e){r=bi(r);let t=new yi(ws(r,e)),o;try{o=await t.user("me").get()}catch{return null}return Ss(ne()),ar(ne(),JSON.stringify({token:t.token,...o},null," ")),t}c(Nt,"getLoggedClient");var As=c(r=>we(r,j),"getLocalConfigPath"),Ce=c(r=>{if(le(r))return JSON.parse(Ot(r,{encoding:"utf-8"}))},"getJsonFileContent"),Fe=c(r=>Ce(As(r)),"getLocalConfig"),cr=c(async(r,e)=>{let t=we(e||ae.cwd(),j);await rl(gi(t),{recursive:!0}),ar(t,JSON.stringify(r,null," "))},"setLocalConfig"),Sl=[ce(),"node_modules",".venv"],ur=c(async r=>{let e=Ie();nr(r,Ai()),nr(r,Si()),nr(r,e);let t=we(r,".gitignore"),o="";le(t)&&(o=Ot(t,{encoding:"utf-8"}));let s=[];for(let i of Sl)RegExp(`^${ul(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),ar(t,`
1
+ var Pa=Object.defineProperty;var c=(r,e)=>Pa(r,"name",{value:e,configurable:!0});import Te from"process";import{parseArgs as pn}from"util";import Lr from"chalk";import{satisfies as $c}from"semver";import _s from"chalk";import ac from"indent-string";import lc from"widest-line";import cc from"wrap-ansi";import La from"chalk";function I(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(La.gray(`[${r}]`),...e)}c(I,"cliDebugPrint");import{realpathSync as Da}from"fs";import{dirname as Fa}from"path";import ct from"chalk";function ze(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}c(ze,"internalLog");function _(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}c(_,"simpleLog");function p(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.red("Error:"),r.message]})}c(p,"error");function x(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.yellow.bold("Warning:"),r.message]})}c(x,"warning");function $(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.green("Success:"),r.message]})}c($,"success");function ye(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.gray("Run:"),r.message]})}c(ye,"run");function v(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.white("Info:"),r.message]})}c(v,"info");function cs(r){ze({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.blue(r.message),r.url]})}c(cs,"link");var si="0.0.0";var ka="0.21.10-beta.23",Ua="79c0aef4785e5b359c3bad3f6a60190fd9f78c4a";function Ma(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return"bundle";let r=process.argv[1];if(!r)return x({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Da(r);return process.env.VOLTA_HOME&&e.includes(process.env.VOLTA_HOME)?"volta":e.includes("homebrew/Cellar")||e.includes("linuxbrew/Cellar")?"homebrew":process.env.PNPM_HOME&&e.includes(process.env.PNPM_HOME)?"pnpm":process.env.BUN_INSTALL&&e.includes(process.env.BUN_INSTALL)?"bun":"npm"}c(Ma,"detectInstallMethod");function ja(){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}}c(ja,"getRuntimeInfo");var $t=null;function K(){if($t)return $t;let r=Ma(),e=ja();return $t={version:ka,hash:Ua,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform==="win32"?"windows":process.platform,runtime:e,extraRuntimeData:e.nodeVersion?`(emulating node ${e.nodeVersion})`:"",installMethod:r,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${e.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:""}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes("beta")||this.version==="0.21.10-beta.23"}},r==="bundle"&&($t.installPath=Fa(process.execPath)),$t}c(K,"useCLIMetadata");import{existsSync as bl,mkdirSync as vl,readFileSync as Tl,writeFileSync as Il}from"fs";import{dirname as Cl}from"path";import{cryptoRandomObjectId as El}from"@apify/utilities";import{homedir as Ba}from"os";import{join as Xe}from"path";import{KEY_VALUE_STORE_KEYS as Ga,META_ORIGINS as Ya}from"@apify/consts";var ii={name:"apify-cli",version:"0.21.10-beta.23",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '\\[api\\]'","test:python":"vitest run --testNamePattern '\\[python\\]'","test:cucumber":'cross-env NODE_OPTIONS="--import tsx" cucumber-js',lint:"eslint src test scripts features --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts features --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=20"},dependencies:{"@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.18.0","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^10.1.15","@inquirer/input":"^4.2.1","@inquirer/password":"^4.0.17","@inquirer/select":"^4.3.1","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.17.1","apify-client":"^2.14.0",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.5.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.1.0",globby:"~14.1.0",handlebars:"~4.7.8","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","lodash.clonedeep":"^4.5.0",mime:"~4.0.4",open:"~10.2.0",rimraf:"~6.0.1",semver:"~7.7.0","string-width":"^7.2.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",which:"^5.0.0","widest-line":"^5.0.0","wrap-ansi":"^9.0.0"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@cucumber/cucumber":"^12.0.0","@types/adm-zip":"^0.5.5","@types/archiver":"^6.0.2","@types/bun":"^1.2.5","@types/chai":"^4.3.17","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11","@types/is-ci":"^3.0.4","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/lodash.clonedeep":"^4","@types/mime":"^4.0.0","@types/node":"^22.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4",chai:"^4.4.1","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","lint-staged":"^16.0.0","mdast-util-from-markdown":"^2.0.2","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^5.8.3","typescript-eslint":"^8.31.0",vitest:"^3.0.0"},volta:{node:"22.18.0",yarn:"4.9.2"},packageManager:"yarn@4.9.2",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"}};var Ze="storage",us="apify_storage",ms=1,rr={actorSpecification:ms,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},ni=1440*60*1e3,ut=c(()=>{let r=Xe(Ba(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?Xe(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),ne=c(()=>Xe(ut(),"auth.json"),"AUTH_FILE_PATH"),or=c(()=>Xe(ut(),"secrets.json"),"SECRETS_FILE_PATH"),sr=c(()=>Xe(ut(),"state.json"),"STATE_FILE_PATH"),ir=c(()=>Xe(ut(),"telemetry.json"),"TELEMETRY_FILE_PATH"),nr="apify.json",ds=".actor",Ha="actor.json",j=Xe(ds,Ha),ps=new RegExp(`^${Ga.INPUT}\\..*`),we=ii.engines.node,ai={"X-Apify-Request-Origin":Ya.CLI},Qe="3.9.0",li=".venv";import{createWriteStream as Qa,existsSync as le,mkdirSync as el,readdirSync as fi,readFileSync as Nt,writeFileSync as lr}from"fs";import{mkdir as tl,readFile as rl}from"fs/promises";import{get as ol}from"https";import{dirname as gi,join as Ae}from"path";import ae from"process";import{finished as sl}from"stream/promises";import{DurationFormatter as hi,TimeTypes as et}from"@sapphire/duration";import{Timestamp as fs}from"@sapphire/timestamp";import il from"adm-zip";import nl from"ajv/dist/2019.js";import{ApifyClient as yi}from"apify-client";import al from"archiver";import{AxiosHeaders as ll}from"axios";import cl from"escape-string-regexp";import{globby as wi}from"globby";import{getEncoding as ul}from"istextorbinary";import{Mime as ml}from"mime";import dl from"mime/types/other.js";import pl from"mime/types/standard.js";import{gte as fl,minVersion as gl,satisfies as hl}from"semver";import{ACTOR_ENV_VARS as gs,ACTOR_JOB_TERMINAL_STATUSES as yl,ACTOR_NAME as Ot,APIFY_ENV_VARS as wl,KEY_VALUE_STORE_KEYS as pi,LOCAL_ACTOR_ENV_VARS as hs,LOCAL_STORAGE_SUBDIRS as ys,SOURCE_FILE_FORMATS as xt}from"@apify/consts";import{existsSync as Ja,mkdirSync as Ka}from"fs";import{readFile as qa,stat as ci,unlink as Wa,writeFile as za}from"fs/promises";import{join as ui,sep as Xa}from"path";import{rimraf as Za}from"rimraf";var mi=c(async(r,e={},t=null)=>{let o=await qa(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await za(r,JSON.stringify(i,null," "))},"updateLocalJson"),ar=c((r,e)=>{e||(e=r,r="."),e.split(Xa).reduce((o,s)=>(o=ui(o,s),Ja(o)||Ka(o),o),r)},"ensureFolderExistsSync"),Rt=c(async r=>{await Za(r)},"rimrafPromised"),_t=c(async r=>{(await ci(r)).isFile()&&await Wa(r)},"deleteFile"),di=c(async(r,e)=>(await Promise.all(r.map(async s=>ci(ui(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var mt=nl,cr=c(async r=>new Promise((e,t)=>{ol(r,o=>{o.statusCode===301||o.statusCode===302?(e(cr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),ce=c(()=>{let r=wl.LOCAL_STORAGE_DIR;return ae.env[r]||ae.env.CRAWLEE_STORAGE_DIR||Ze},"getLocalStorageDir"),Ce=c(r=>{let e=gs.DEFAULT_KEY_VALUE_STORE_ID,t=r||ae.env[e]||hs[e];return Ae(ce(),ys.keyValueStores,t)},"getLocalKeyValueStorePath"),Ai=c(r=>{let e=gs.DEFAULT_DATASET_ID,t=r||ae.env[e]||hs[e];return Ae(ce(),ys.datasets,t)},"getLocalDatasetPath"),Si=c(r=>{let e=gs.DEFAULT_REQUEST_QUEUE_ID,t=r||ae.env[e]||hs[e];return Ae(ce(),ys.requestQueues,t)},"getLocalRequestQueuePath"),F=c(async()=>{let r={};try{let e=await rl(ne(),"utf-8");r=JSON.parse(e)}catch{return{}}if(!r.username&&!r.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return r},"getLocalUserInfo");async function C(){let r=await Pt();if(!r)throw new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}c(C,"getLoggedClientOrThrow");var bi=c(r=>{if(!r&&le(ut())&&le(ne())){let e=Nt(ne(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),ws=c((r,e)=>(r=bi(r),{token:r,baseUrl:e||ae.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new ll;for(let[o,s]of Object.entries(ai))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Pt(r,e){r=bi(r);let t=new yi(ws(r,e)),o;try{o=await t.user("me").get()}catch{return null}return Ss(ne()),lr(ne(),JSON.stringify({token:t.token,...o},null," ")),t}c(Pt,"getLoggedClient");var As=c(r=>Ae(r,j),"getLocalConfigPath"),Ee=c(r=>{if(le(r))return JSON.parse(Nt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Fe=c(r=>Ee(As(r)),"getLocalConfig"),ur=c(async(r,e)=>{let t=Ae(e||ae.cwd(),j);await tl(gi(t),{recursive:!0}),lr(t,JSON.stringify(r,null," "))},"setLocalConfig"),Al=[ce(),"node_modules",".venv"],mr=c(async r=>{let e=Ce();ar(r,Ai()),ar(r,Si()),ar(r,e);let t=Ae(r,".gitignore"),o="";le(t)&&(o=Nt(t,{encoding:"utf-8"}));let s=[];for(let i of Al)RegExp(`^${cl(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),lr(t,`
2
2
  ${s.join(`
3
3
  `)}
4
- `,{flag:"a"})):ar(t,`${s.join(`
4
+ `,{flag:"a"})):lr(t,`${s.join(`
5
5
  `)}
6
- `,{flag:"w"}))},"setLocalEnv"),vi=new dl(fl,pl).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),bl=c((r,e)=>{let t=vi.getType(r);return t?t.startsWith("text/")||t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("application/node")||t.includes("application/toml")||t.includes("application/x-sh")||t.includes("application/x-httpd-php")?Rt.TEXT:Rt.BASE64:ml(e)==="binary"?Rt.BASE64:Rt.TEXT},"getSourceFileFormat"),Ti=c(async(r,e)=>r.map(t=>{let o=Ot(we(e,t)),s=bl(t,o);return{name:t,format:s,content:s===Rt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Ii=c(async r=>wi(["*","**/**"],{ignore:[".git/**","apify_storage","node_modules","storage","crawlee_storage"],gitignore:!0,dot:!0,cwd:r}),"getActorLocalFilePaths"),Ci=c(async(r,e,t)=>{le(r)&&await _t(r);let o=el(r),s=ll("zip");s.pipe(o),e.forEach(i=>s.glob(i,{cwd:t})),await s.finalize()},"createActZip"),Pt=c(r=>{let e=Ie();if(!le(we(r,e)))return;let s=fi(we(r,e)).find(a=>!!a.match(ps));if(!s)return;let i=Ot(we(r,e,s)),n=vi.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),Ei=c(async()=>{let r=Si();le(ce())&&le(r)&&await $t(r)},"purgeDefaultQueue"),$i=c(async()=>{let r=Ai();le(ce())&&le(r)&&await $t(r)},"purgeDefaultDataset"),_i=c(async()=>{let r=Ie();if(!le(ce())||!le(r))return;let e=fi(r),t=[];e.forEach(o=>{o.match(ps)||t.push(_t(we(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),Ee=c(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new yi({baseUrl:ae.env.APIFY_CLIENT_BASE_URL});if(wl.includes(s)){if(ae.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();ae.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let l=null;a.on("data",m=>{ae.env.APIFY_NO_LOGS_IN_TESTS||ae.stderr.write(m.toString())}),a.once("end",()=>{n("finished"),l&&clearTimeout(l)}),e&&(l=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var Ri=c(async()=>(await wi([`${ce()}/**`,`!${Ie()}/${pi.INPUT}.*`,`!${Ie()}/${pi.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Lt=c(r=>{if(!xt.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<xt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>xt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),xi=c(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<xt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,xt.MAX_LENGTH)},"sanitizeActorName"),mr=c(r=>yl(r,`^${Qe}`),"isPythonVersionSupported"),dr=c(r=>{let e=hl(ye);return gl(r,e)},"isNodeVersionSupported"),pr=c(async({url:r,pathTo:e})=>{let t=await lr(r),o=[];t.on("data",i=>o.push(i)),await il(t),new nl(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Ss(r){let e=gi(r);tl(e,{recursive:!0})}c(Ss,"ensureApifyDirectory");var V=new fs("YYYY-MM-DD [at] HH:mm:ss"),Dt=new fs(`YYYY-MM-DD[
7
- ]HH:mm:ss`),Oi=new fs("YYYY-MM-DD"),Ft=new hi,se=new hi({[et.Day]:{DEFAULT:"d"},[et.Hour]:{DEFAULT:"h"},[et.Minute]:{DEFAULT:"m"},[et.Month]:{DEFAULT:"M"},[et.Second]:{DEFAULT:"s"},[et.Week]:{DEFAULT:"w"},[et.Year]:{DEFAULT:"y"}});function fr(r,e){if("groupBy"in Object)return Object.groupBy(r,e);let t={},o=0;for(let s of r){let i=e(s,o++);t[i]||(t[i]=[]),t[i].push(s)}return t}c(fr,"objectGroupBy");function Ni(r,e){let t=new Map,o=0;for(let s of r){let i=e(s,o++),n=t.get(i);n?n.push(s):t.set(i,[s])}return t}c(Ni,"mapGroupBy");function N(r){console.log(JSON.stringify(r,null,2))}c(N,"printJsonToStdout");var _l=["Apify collects telemetry data about general usage of Apify CLI to help us improve the product.",'This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".',"You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry."].join(`
8
- `);function Pi(){return`CLI:${$l()}`}c(Pi,"createAnonymousId");async function Rl(r){if(r.version&&r.version>=1)return!1;let e=r,t=await D().catch(()=>({}));return gr({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=Pi(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}c(Rl,"migrateStateV0ToV1");async function ue(){let r=sr();if(!vl(r)){let s=await D().catch(()=>({}));return gr({version:1,enabled:!0,anonymousId:Pi(),userId:s.id}),b({message:_l}),ue()}let t=JSON.parse(Il(r,"utf-8"));return await Rl(t)?ue():t}c(ue,"useTelemetryState");function gr(r,e){let t={...r};e?.(t);let o=sr(),s=El(o);Tl(s,{recursive:!0}),Cl(sr(),JSON.stringify(t,null," "))}c(gr,"updateTelemetryState");async function hr(r){let e=await ue();gr(e,t=>{t.userId=r})}c(hr,"updateUserId");async function yr(r){let e=await ue();gr(e,t=>{t.enabled=r})}c(yr,"updateTelemetryEnabled");async function Li(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&!["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return T("telemetry","disabled by env variable"),!1;let r=await ue();return T("telemetry state",{telemetryState:r}),r.enabled}c(Li,"useTelemetryEnabled");async function Di(){let r=await ue();return{anonymousId:r.anonymousId,userId:r.userId}}c(Di,"useTelemetryIdentifiers");var kt=K(),xl="https://api.segment.io/v1/track",Ol=kt.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function Fi(r,e){let t=await Di(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:kt.version,build:kt.hash},library:{name:"apify-cli",version:kt.version},os:{name:kt.platform},userAgent:tt,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:Ol};if(T("trackEvent",o),!await Li()){T("trackEvent","telemetry disabled");return}let i=await fetch(xl,{method:"POST",body:JSON.stringify(o)});if(!i.ok){T("trackEvent","failed to send event",await i.text());return}T("trackEvent","event sent")}c(Fi,"trackEvent");import{access as Cs,readFile as ql}from"fs/promises";import{basename as zi,dirname as Wl,join as H,resolve as Xi}from"path";import zl from"process";import{ok as Is}from"@sapphire/result";import{existsSync as ji,readdirSync as Ul}from"fs";import{join as br,resolve as Ml}from"path";import jl from"configparser";import Fl from"@inquirer/input";import Dl from"is-ci";import{constants as ki,fstat as Nl}from"fs";import Ui from"process";import{promisify as Pl}from"util";var Ll=Pl(Nl),bs;async function wr(){if(bs)return bs;let r=Ui.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Ll(0).then(o=>{if(T("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),Ui.platform==="win32"){if((o.mode&ki.S_IFIFO)===ki.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return T("useStdin",{hasData:e.hasData,waitDelay:e.waitDelay,isTTY:e.isTTY,pipedIn:t,readableEnded:r.readableEnded}),(!r.isTTY||t!==!1&&(r.isTTY!==void 0||!r.readableEnded))&&(e.hasData=!0),typeof t=="number"&&(e.waitDelay=t),bs=e,e}c(wr,"useStdin");var vs="confirm",Mi=`no-${vs}`;function $e(r,{errorMessageForStdin:e=`Please use the --${vs}/--${Mi} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await wr(),n=t;if(Dl||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${vs}/--${Mi} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}c($e,"stdinCheckWrapper");var rt=$e(async({message:r,validate:e,default:t})=>await Fl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as kl}from"fs";var Ar=class{static{c(this,"Spider")}name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}};var Sr=class{static{c(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=kl(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Ar({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var ot=class{static{c(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return ji(br(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new jl,t=Ml(br(this.pathname,"scrapy.cfg"));if(!ji(t))throw new Error(`scrapy.cfg not found in "${t}".
9
- Are you sure there is a Scrapy project there?`);e.read(t),this.configuration=e}async loadSettings(){let e=this.configuration.get("settings","default").split(".")[0],t=await rt({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await rt({message:"What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):",default:`${e}.spiders`});this.settings={BOT_NAME:t,SPIDER_MODULES:typeof o=="string"?[o]:o}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw new Error("SPIDER_MODULES path not found in settings.");let t=[];for(let o of e){let s=br(this.pathname,o.replaceAll(".","/")),i=Ul(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new Sr(br(s,n.name)).getSpiders())}return t}};import Ts from"process";import{none as Vi,some as Bi}from"@sapphire/result";import{execa as Yi}from"execa";import Gi from"which";import{isAbsolute as Vl}from"path";function ke(r){return r?r.startsWith('"')?r:Vl(r)&&r.includes(" ")?`"${r}"`:r:null}c(ke,"normalizeExecutablePath");var vr=new Map,Bl={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function Gl(r,e){try{let t=await Yi(r,e,{shell:!0,windowsHide:!0,verbose:Ts.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}c(Gl,"getRuntimeVersion");async function Yl(r){let e=await Yi(r,["--version"],{shell:!0,windowsHide:!0,verbose:Ts.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}c(Yl,"getNpmVersion");async function Hi(r=Ts.cwd()){let e=vr.get(r);if(e)return T("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(Bl))try{let s=ke(await Gi(t)),i=await Gl(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=ke(await Gi("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Yl(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return vr.set(r,Bi(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:vr.get(r)?.unwrap()}),Bi(n)}}catch{}return vr.set(r,Vi),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),Vi}c(Hi,"useJavaScriptRuntime");import{platform as Hl}from"os";import{join as Ji}from"path";import Tr from"process";import{none as Ki,some as qi}from"@sapphire/result";import{execa as Jl}from"execa";import Kl from"which";var Ue=new Map;async function Wi(r){try{let e=await Jl(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Tr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}c(Wi,"getPythonVersion");async function Ut({cwd:r=Tr.cwd(),force:e=!1}={}){let t=Ue.get(r);if(t&&!e)return T("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=Hl()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Tr.env.VIRTUAL_ENV?i=Ji(Tr.env.VIRTUAL_ENV,...s):i=Ji(r,".venv",...s),i=ke(i);try{let a=await Wi(i);if(a)return Ue.set(r,qi({executablePath:i,version:a})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ue.get(r)?.unwrap()}),Ue.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let l=ke(await Kl(a)),m=await Wi(l);if(m)return Ue.set(r,qi({executablePath:l,version:m})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ue.get(r)?.unwrap()}),Ue.get(r)}catch{}return Ue.set(r,Ki),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),Ki}c(Ut,"usePythonRuntime");var Zi=new Map;async function Me({cwd:r=zl.cwd()}={}){let e=Zi.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),Is(e);let t={type:3},s=await c(async()=>{if(await Zl(r)){t.type=2;let l=await Ut({cwd:r});t.runtime=l.unwrapOr(void 0);let m=new ot(r);if(m.loadScrapyCfg(),m.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:m.configuration.get("apify","mainpy_location")};else{let u=await Qi(r);u&&(t.entrypoint={path:u})}return}let n=await Qi(r);if(n){t.type=1;let l=await Ut({cwd:r});t.entrypoint={path:n},t.runtime=l.unwrapOr(void 0);return}let a=await Xl(r);if(a){t.type=0;let l=await Hi();t.runtime=l.unwrapOr(void 0),a.type==="file"?t.entrypoint={path:a.path}:a.type==="script"&&(t.entrypoint={script:a.script});return}return Is(t)},"check")();return s?.isErr()?(T("useCwdProject",{cacheHit:!1,error:s}),s):(T("useCwdProject",{cacheHit:!1,project:t}),Zi.set(r,t),Is(t))}c(Me,"useCwdProject");async function Xl(r){let e=H(r,"package.json");try{let o=await ql(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await Cs(Xi(r,s.main)),{path:Xi(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[H(r,"index.js"),H(r,"index.mjs"),H(r,"index.cjs"),H(r,"main.js"),H(r,"main.mjs"),H(r,"main.cjs"),H(r,"src","index.js"),H(r,"src","index.mjs"),H(r,"src","index.cjs"),H(r,"src","main.js"),H(r,"src","main.mjs"),H(r,"src","main.cjs"),H(r,"dist","index.js"),H(r,"dist","index.mjs"),H(r,"dist","index.cjs"),H(r,"dist","main.js"),H(r,"dist","main.mjs"),H(r,"dist","main.cjs")];for(let o of t)try{return await Cs(o),{path:o,type:"file"}}catch{}return null}c(Xl,"checkNodeProject");async function Qi(r){let e=zi(r),t=[H(r,"src","__main__.py"),H(r,"__main__.py"),H(r,e,"__main__.py"),H(r,e.replaceAll("-","_").replaceAll(" ","_"),"__main__.py")];for(let o of t)try{return await Cs(o),zi(Wl(o))}catch{}return null}c(Qi,"checkPythonProject");async function Zl(r){return ot.isApplicable(r)}c(Zl,"checkScrapyProject");import G from"chalk";import jt from"chalk";import rn from"indent-string";import on from"widest-line";import sn from"wrap-ansi";import Ir from"chalk";import Es from"indent-string";import rc from"string-width";import oc from"strip-ansi";import tn from"widest-line";import $s from"wrap-ansi";import Ql from"chalk";import ec from"indent-string";import en from"string-width";import tc from"wrap-ansi";var je;function oe(){if(je)return je;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))je=r;else if(!process.stdout.isTTY)je=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?je=80:e<40?je=40:je=e}return je}c(oe,"getMaxLineWidth");var dt=class{static{c(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){this.command.shortDescription?e.push(this.command.shortDescription,""):this.command.description&&e.push(this.command.description.split(`
10
- `)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(Ql.bold("DESCRIPTION"));let t=tc(this.command.description,oe()-2,{trim:!1}),o=ec(t,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=en(e.join(" ").split(`
6
+ `,{flag:"w"}))},"setLocalEnv"),vi=new ml(pl,dl).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),Sl=c((r,e)=>{let t=vi.getType(r);return t?t.startsWith("text/")||t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("application/node")||t.includes("application/toml")||t.includes("application/x-sh")||t.includes("application/x-httpd-php")?xt.TEXT:xt.BASE64:ul(e)==="binary"?xt.BASE64:xt.TEXT},"getSourceFileFormat"),Ti=c(async(r,e)=>r.map(t=>{let o=Nt(Ae(e,t)),s=Sl(t,o);return{name:t,format:s,content:s===xt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Ii=c(async r=>wi(["*","**/**"],{ignore:[".git/**","apify_storage","node_modules","storage","crawlee_storage"],gitignore:!0,dot:!0,cwd:r}),"getActorLocalFilePaths"),Ci=c(async(r,e,t)=>{le(r)&&await _t(r);let o=Qa(r),s=al("zip");s.pipe(o),e.forEach(i=>s.glob(i,{cwd:t})),await s.finalize()},"createActZip"),Lt=c(r=>{let e=Ce();if(!le(Ae(r,e)))return;let s=fi(Ae(r,e)).find(a=>!!a.match(ps));if(!s)return;let i=Nt(Ae(r,e,s)),n=vi.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),Ei=c(async()=>{let r=Si();le(ce())&&le(r)&&await Rt(r)},"purgeDefaultQueue"),$i=c(async()=>{let r=Ai();le(ce())&&le(r)&&await Rt(r)},"purgeDefaultDataset"),Ri=c(async()=>{let r=Ce();if(!le(ce())||!le(r))return;let e=fi(r),t=[];e.forEach(o=>{o.match(ps)||t.push(_t(Ae(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),$e=c(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new yi({baseUrl:ae.env.APIFY_CLIENT_BASE_URL});if(yl.includes(s)){if(ae.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();ae.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let l=null;a.on("data",m=>{ae.env.APIFY_NO_LOGS_IN_TESTS||ae.stderr.write(m.toString())}),a.once("end",()=>{n("finished"),l&&clearTimeout(l)}),e&&(l=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var _i=c(async()=>(await wi([`${ce()}/**`,`!${Ce()}/${pi.INPUT}.*`,`!${Ce()}/${pi.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Dt=c(r=>{if(!Ot.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<Ot.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>Ot.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),xi=c(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<Ot.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,Ot.MAX_LENGTH)},"sanitizeActorName"),dr=c(r=>hl(r,`^${Qe}`),"isPythonVersionSupported"),pr=c(r=>{let e=gl(we);return fl(r,e)},"isNodeVersionSupported"),fr=c(async({url:r,pathTo:e})=>{let t=await cr(r),o=[];t.on("data",i=>o.push(i)),await sl(t),new il(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Ss(r){let e=gi(r);el(e,{recursive:!0})}c(Ss,"ensureApifyDirectory");var V=new fs("YYYY-MM-DD [at] HH:mm:ss"),Ft=new fs(`YYYY-MM-DD[
7
+ ]HH:mm:ss`),Oi=new fs("YYYY-MM-DD"),kt=new hi,se=new hi({[et.Day]:{DEFAULT:"d"},[et.Hour]:{DEFAULT:"h"},[et.Minute]:{DEFAULT:"m"},[et.Month]:{DEFAULT:"M"},[et.Second]:{DEFAULT:"s"},[et.Week]:{DEFAULT:"w"},[et.Year]:{DEFAULT:"y"}});function gr(r,e){if("groupBy"in Object)return Object.groupBy(r,e);let t={},o=0;for(let s of r){let i=e(s,o++);t[i]||(t[i]=[]),t[i].push(s)}return t}c(gr,"objectGroupBy");function Ni(r,e){let t=new Map,o=0;for(let s of r){let i=e(s,o++),n=t.get(i);n?n.push(s):t.set(i,[s])}return t}c(Ni,"mapGroupBy");function L(r){console.log(JSON.stringify(r,null,2))}c(L,"printJsonToStdout");var $l=["Apify collects telemetry data about general usage of Apify CLI to help us improve the product.",'This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".',"You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry."].join(`
8
+ `);function Pi(){return`CLI:${El()}`}c(Pi,"createAnonymousId");async function Rl(r){if(r.version&&r.version>=1)return!1;let e=r,t=await F().catch(()=>({}));return hr({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=Pi(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}c(Rl,"migrateStateV0ToV1");async function ue(){let r=ir();if(!bl(r)){let s=await F().catch(()=>({}));return hr({version:1,enabled:!0,anonymousId:Pi(),userId:s.id}),v({message:$l}),ue()}let t=JSON.parse(Tl(r,"utf-8"));return await Rl(t)?ue():t}c(ue,"useTelemetryState");function hr(r,e){let t={...r};e?.(t);let o=ir(),s=Cl(o);vl(s,{recursive:!0}),Il(ir(),JSON.stringify(t,null," "))}c(hr,"updateTelemetryState");async function yr(r){let e=await ue();hr(e,t=>{t.userId=r})}c(yr,"updateUserId");async function wr(r){let e=await ue();hr(e,t=>{t.enabled=r})}c(wr,"updateTelemetryEnabled");async function Li(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&!["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return I("telemetry","disabled by env variable"),!1;let r=await ue();return I("telemetry state",{telemetryState:r}),r.enabled}c(Li,"useTelemetryEnabled");async function Di(){let r=await ue();return{anonymousId:r.anonymousId,userId:r.userId}}c(Di,"useTelemetryIdentifiers");var Ut=K(),_l="https://api.segment.io/v1/track",xl=Ut.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function Fi(r,e){let t=await Di(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:Ut.version,build:Ut.hash},library:{name:"apify-cli",version:Ut.version},os:{name:Ut.platform},userAgent:tt,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:xl};if(I("trackEvent",o),!await Li()){I("trackEvent","telemetry disabled");return}let i=await fetch(_l,{method:"POST",body:JSON.stringify(o)});if(!i.ok){I("trackEvent","failed to send event",await i.text());return}I("trackEvent","event sent")}c(Fi,"trackEvent");import{access as Cs,readFile as Kl}from"fs/promises";import{basename as zi,dirname as ql,join as H,resolve as Xi}from"path";import Wl from"process";import{ok as Is}from"@sapphire/result";import{existsSync as ji,readdirSync as kl}from"fs";import{join as vr,resolve as Ul}from"path";import Ml from"configparser";import Dl from"@inquirer/input";import Ll from"is-ci";import{constants as ki,fstat as Ol}from"fs";import Ui from"process";import{promisify as Nl}from"util";var Pl=Nl(Ol),bs;async function Ar(){if(bs)return bs;let r=Ui.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Pl(0).then(o=>{if(I("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),Ui.platform==="win32"){if((o.mode&ki.S_IFIFO)===ki.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return I("useStdin",{hasData:e.hasData,waitDelay:e.waitDelay,isTTY:e.isTTY,pipedIn:t,readableEnded:r.readableEnded}),(!r.isTTY||t!==!1&&(r.isTTY!==void 0||!r.readableEnded))&&(e.hasData=!0),typeof t=="number"&&(e.waitDelay=t),bs=e,e}c(Ar,"useStdin");var vs="confirm",Mi=`no-${vs}`;function Re(r,{errorMessageForStdin:e=`Please use the --${vs}/--${Mi} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await Ar(),n=t;if(Ll||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${vs}/--${Mi} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}c(Re,"stdinCheckWrapper");var rt=Re(async({message:r,validate:e,default:t})=>await Dl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as Fl}from"fs";var Sr=class{static{c(this,"Spider")}name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}};var br=class{static{c(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=Fl(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Sr({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var ot=class{static{c(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return ji(vr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Ml,t=Ul(vr(this.pathname,"scrapy.cfg"));if(!ji(t))throw new Error(`scrapy.cfg not found in "${t}".
9
+ Are you sure there is a Scrapy project there?`);e.read(t),this.configuration=e}async loadSettings(){let e=this.configuration.get("settings","default").split(".")[0],t=await rt({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await rt({message:"What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):",default:`${e}.spiders`});this.settings={BOT_NAME:t,SPIDER_MODULES:typeof o=="string"?[o]:o}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw new Error("SPIDER_MODULES path not found in settings.");let t=[];for(let o of e){let s=vr(this.pathname,o.replaceAll(".","/")),i=kl(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new br(vr(s,n.name)).getSpiders())}return t}};import Ts from"process";import{none as Vi,some as Bi}from"@sapphire/result";import{execa as Yi}from"execa";import Gi from"which";import{isAbsolute as jl}from"path";function ke(r){return r?r.startsWith('"')?r:jl(r)&&r.includes(" ")?`"${r}"`:r:null}c(ke,"normalizeExecutablePath");var Tr=new Map,Vl={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function Bl(r,e){try{let t=await Yi(r,e,{shell:!0,windowsHide:!0,verbose:Ts.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}c(Bl,"getRuntimeVersion");async function Gl(r){let e=await Yi(r,["--version"],{shell:!0,windowsHide:!0,verbose:Ts.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}c(Gl,"getNpmVersion");async function Hi(r=Ts.cwd()){let e=Tr.get(r);if(e)return I("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(Vl))try{let s=ke(await Gi(t)),i=await Bl(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=ke(await Gi("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Gl(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return Tr.set(r,Bi(n)),I("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:Tr.get(r)?.unwrap()}),Bi(n)}}catch{}return Tr.set(r,Vi),I("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),Vi}c(Hi,"useJavaScriptRuntime");import{platform as Yl}from"os";import{join as Ji}from"path";import Ir from"process";import{none as Ki,some as qi}from"@sapphire/result";import{execa as Hl}from"execa";import Jl from"which";var Ue=new Map;async function Wi(r){try{let e=await Hl(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Ir.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}c(Wi,"getPythonVersion");async function Mt({cwd:r=Ir.cwd(),force:e=!1}={}){let t=Ue.get(r);if(t&&!e)return I("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=Yl()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Ir.env.VIRTUAL_ENV?i=Ji(Ir.env.VIRTUAL_ENV,...s):i=Ji(r,".venv",...s),i=ke(i);try{let a=await Wi(i);if(a)return Ue.set(r,qi({executablePath:i,version:a})),I("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ue.get(r)?.unwrap()}),Ue.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let l=ke(await Jl(a)),m=await Wi(l);if(m)return Ue.set(r,qi({executablePath:l,version:m})),I("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ue.get(r)?.unwrap()}),Ue.get(r)}catch{}return Ue.set(r,Ki),I("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),Ki}c(Mt,"usePythonRuntime");var Zi=new Map;async function Me({cwd:r=Wl.cwd()}={}){let e=Zi.get(r);if(e)return I("useCwdProject",{cacheHit:!0,project:e}),Is(e);let t={type:3},s=await c(async()=>{if(await Xl(r)){t.type=2;let l=await Mt({cwd:r});t.runtime=l.unwrapOr(void 0);let m=new ot(r);if(m.loadScrapyCfg(),m.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:m.configuration.get("apify","mainpy_location")};else{let u=await Qi(r);u&&(t.entrypoint={path:u})}return}let n=await Qi(r);if(n){t.type=1;let l=await Mt({cwd:r});t.entrypoint={path:n},t.runtime=l.unwrapOr(void 0);return}let a=await zl(r);if(a){t.type=0;let l=await Hi();t.runtime=l.unwrapOr(void 0),a.type==="file"?t.entrypoint={path:a.path}:a.type==="script"&&(t.entrypoint={script:a.script});return}return Is(t)},"check")();return s?.isErr()?(I("useCwdProject",{cacheHit:!1,error:s}),s):(I("useCwdProject",{cacheHit:!1,project:t}),Zi.set(r,t),Is(t))}c(Me,"useCwdProject");async function zl(r){let e=H(r,"package.json");try{let o=await Kl(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await Cs(Xi(r,s.main)),{path:Xi(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[H(r,"index.js"),H(r,"index.mjs"),H(r,"index.cjs"),H(r,"main.js"),H(r,"main.mjs"),H(r,"main.cjs"),H(r,"src","index.js"),H(r,"src","index.mjs"),H(r,"src","index.cjs"),H(r,"src","main.js"),H(r,"src","main.mjs"),H(r,"src","main.cjs"),H(r,"dist","index.js"),H(r,"dist","index.mjs"),H(r,"dist","index.cjs"),H(r,"dist","main.js"),H(r,"dist","main.mjs"),H(r,"dist","main.cjs")];for(let o of t)try{return await Cs(o),{path:o,type:"file"}}catch{}return null}c(zl,"checkNodeProject");async function Qi(r){let e=zi(r),t=[H(r,"src","__main__.py"),H(r,"__main__.py"),H(r,e,"__main__.py"),H(r,e.replaceAll("-","_").replaceAll(" ","_"),"__main__.py")];for(let o of t)try{return await Cs(o),zi(ql(o))}catch{}return null}c(Qi,"checkPythonProject");async function Xl(r){return ot.isApplicable(r)}c(Xl,"checkScrapyProject");import Y from"chalk";import Vt from"chalk";import rn from"indent-string";import on from"widest-line";import sn from"wrap-ansi";import Cr from"chalk";import Es from"indent-string";import tc from"string-width";import rc from"strip-ansi";import tn from"widest-line";import $s from"wrap-ansi";import Zl from"chalk";import Ql from"indent-string";import en from"string-width";import ec from"wrap-ansi";var je;function oe(){if(je)return je;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))je=r;else if(!process.stdout.isTTY)je=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?je=80:e<40?je=40:je=e}return je}c(oe,"getMaxLineWidth");var dt=class{static{c(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){this.command.shortDescription?e.push(this.command.shortDescription,""):this.command.description&&e.push(this.command.description.split(`
10
+ `)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(Zl.bold("DESCRIPTION"));let t=ec(this.command.description,oe()-2,{trim:!1}),o=Ql(t,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=en(e.join(" ").split(`
11
11
  `).at(-1)||"")+o,i=en(t);s+i>oe()&&e.push(`
12
- `),e.push(t)}kebabFlagName(e){return Ae(Se(e)).toLowerCase()}makeFlagString(e,t){let o=this.kebabFlagName(e),s=t.char?`-${t.char}`:`--${o}`;switch(t.flagTag){case"boolean":return s;case"string":case"integer":{let i=t.choices?.length?`${t.choices.join("|")}`:"<value>";return`${s} ${i}`}default:throw new RangeError(`Unhandled flag type: ${t.flagTag}`)}}};var Cr=class extends dt{static{c(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
12
+ `),e.push(t)}kebabFlagName(e){return Se(be(e)).toLowerCase()}makeFlagString(e,t){let o=this.kebabFlagName(e),s=t.char?`-${t.char}`:`--${o}`;switch(t.flagTag){case"boolean":return s;case"string":case"integer":{let i=t.choices?.length?`${t.choices.join("|")}`:"<value>";return`${s} ${i}`}default:throw new RangeError(`Unhandled flag type: ${t.flagTag}`)}}};var Er=class extends dt{static{c(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
13
13
  `).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showUsageString&&this.pushUsageString(t),e.showDescription&&this.command.description&&this.pushDescription(t),t.join(`
14
- `).trim()}pushUsageString(e){e.push(Ir.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+rc(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[f,d]of i){if(typeof d=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:d.required?`<${f}>`:`[${f}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,f])=>{if(typeof f=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!f.hidden});this.command.enableJsonFlag&&n.push(["json",{choices:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((f,d)=>{if(typeof f[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof d[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return f[1].required&&!d[1].required?-1:!f[1].required&&d[1].required?1:f[0].localeCompare(d[0])})),l=new Set;if(n.length)for(let[f,d]of a){if(typeof d=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(l.has(f))continue;let g=d.required,S=[this.makeFlagString(f,d)];if(d.exclusive?.length)for(let I of d.exclusive){l.add(I);let v=a.get(I),E=this.makeFlagString(I,v);S.push(E),v.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?S.join(" | "):`[${S.join(" | ")}]`,indentSize:o})}let m=$s(s.join(" "),oe()-o),u=Es(m,o+1).trim();e.push(` ${u}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Ir.bold("ARGUMENTS"));let o=tn(t.map(([s])=>s).join(`
15
- `));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=$s(n,oe()-o-2),l=Es(a,o+2+2).trim();e.push(` ${l}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Ir.bold("FLAGS"));let o=new Map;for(let[i,n]of t){let a=[];switch(n.char?a.push(`-${n.char},`):a.push(" ".repeat(3)),n.flagTag){case"boolean":a.push(`--${this.kebabFlagName(i)}`);break;case"string":case"integer":{let l=n.choices?"<option>":"<value>";a.push(`--${this.kebabFlagName(i)}=${Ir.underline(l)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=tn([...o.keys()].join(`
16
- `));for(let[i,n]of o){let a=s-oc(i).length,l=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(l+=`
14
+ `).trim()}pushUsageString(e){e.push(Cr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+tc(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[f,d]of i){if(typeof d=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:d.required?`<${f}>`:`[${f}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,f])=>{if(typeof f=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!f.hidden});this.command.enableJsonFlag&&n.push(["json",{choices:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((f,d)=>{if(typeof f[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof d[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return f[1].required&&!d[1].required?-1:!f[1].required&&d[1].required?1:f[0].localeCompare(d[0])})),l=new Set;if(n.length)for(let[f,d]of a){if(typeof d=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(l.has(f))continue;let g=d.required,S=[this.makeFlagString(f,d)];if(d.exclusive?.length)for(let b of d.exclusive){l.add(b);let T=a.get(b),E=this.makeFlagString(b,T);S.push(E),T.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?S.join(" | "):`[${S.join(" | ")}]`,indentSize:o})}let m=$s(s.join(" "),oe()-o),u=Es(m,o+1).trim();e.push(` ${u}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Cr.bold("ARGUMENTS"));let o=tn(t.map(([s])=>s).join(`
15
+ `));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=$s(n,oe()-o-2),l=Es(a,o+2+2).trim();e.push(` ${l}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Cr.bold("FLAGS"));let o=new Map;for(let[i,n]of t){let a=[];switch(n.char?a.push(`-${n.char},`):a.push(" ".repeat(3)),n.flagTag){case"boolean":a.push(`--${this.kebabFlagName(i)}`);break;case"string":case"integer":{let l=n.choices?"<option>":"<value>";a.push(`--${this.kebabFlagName(i)}=${Cr.underline(l)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=tn([...o.keys()].join(`
16
+ `));for(let[i,n]of o){let a=s-rc(i).length,l=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(l+=`
17
17
  <options: ${n.choices.join("|")}>`);let m=$s(l,oe()-s),u=Es(m,s).trim().split(`
18
18
  `).map(f=>/^-[a-z]/.test(f.trim())?f:` ${f}`).join(`
19
- `);e.push(` ${u}`)}e.push("")}};import sc from"chalk";import ic from"indent-string";import nc from"widest-line";import ac from"wrap-ansi";var Mt=class extends dt{static{c(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
19
+ `);e.push(` ${u}`)}e.push("")}};import oc from"chalk";import sc from"indent-string";import ic from"widest-line";import nc from"wrap-ansi";var jt=class extends dt{static{c(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
20
20
  `).trim()}selectiveRender(e){let t=[];return e.showShortDescription&&this.pushShortDescription(t),e.showDescription&&this.command.description&&this.pushDescription(t),e.showSubcommands&&this.pushSubcommands(t),t.join(`
21
- `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(sc.bold("SUBCOMMANDS"));let t=nc(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
21
+ `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(oc.bold("SUBCOMMANDS"));let t=ic(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
22
22
  `));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
23
- `)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=ac(i,oe()-t-2),a=ic(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var Vt=new Map;function _s(r,e){if(e.name.toLowerCase()!==e.name){p({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){Vt.set(e,new Mt(r,e));for(let t of e.subcommands)_s(`${r} ${e.name}`,t)}else Vt.set(e,new Cr(r,e))}c(_s,"registerCommandForHelpGeneration");function Er(r){let e=Vt.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}c(Er,"renderHelpForCommand");function $r(r,e){let t=Vt.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}c($r,"selectiveRenderHelpForCommand");function nn(r,e){return r[0].name.localeCompare(e[0].name)}c(nn,"sortByName");function _r(r){let e=K(),t=[];t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(jt.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(jt.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=Ni(Vt,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof Mt?"subcommand":"command"),s=o.get("subcommand")?.sort(nn),i=o.get("command")?.sort(nn);if(s?.length){t.push(jt.bold("TOPICS"));let n=[],a=on(s.map(([l])=>l.name).join(`
23
+ `)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=nc(i,oe()-t-2),a=sc(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var Bt=new Map;function Rs(r,e){if(e.name.toLowerCase()!==e.name){p({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){Bt.set(e,new jt(r,e));for(let t of e.subcommands)Rs(`${r} ${e.name}`,t)}else Bt.set(e,new Er(r,e))}c(Rs,"registerCommandForHelpGeneration");function $r(r){let e=Bt.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}c($r,"renderHelpForCommand");function Rr(r,e){let t=Bt.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}c(Rr,"selectiveRenderHelpForCommand");function nn(r,e){return r[0].name.localeCompare(e[0].name)}c(nn,"sortByName");function _r(r){let e=K(),t=[];t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(Vt.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(Vt.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=Ni(Bt,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof jt?"subcommand":"command"),s=o.get("subcommand")?.sort(nn),i=o.get("command")?.sort(nn);if(s?.length){t.push(Vt.bold("TOPICS"));let n=[],a=on(s.map(([l])=>l.name).join(`
24
24
  `));for(let[l]of s){if(l.hidden)continue;let m=l.shortDescription||l.description?.split(`
25
- `)[0]||"",u=`${l.name.padEnd(a)} ${m}`,f=sn(u,oe()-a-2);n.push(` ${rn(f,a+2+2).trim()}`)}t.push(...n,"")}if(i?.length){t.push(jt.bold("COMMANDS"));let n=[],a=on(i.map(([l])=>l.name).join(`
25
+ `)[0]||"",u=`${l.name.padEnd(a)} ${m}`,f=sn(u,oe()-a-2);n.push(` ${rn(f,a+2+2).trim()}`)}t.push(...n,"")}if(i?.length){t.push(Vt.bold("COMMANDS"));let n=[],a=on(i.map(([l])=>l.name).join(`
26
26
  `));for(let[l]of i){if(l.hidden)continue;let m=l.shortDescription||l.description?.split(`
27
- `)[0]||"",u=`${l.name.padEnd(a)} ${m}`,f=sn(u,oe()-a-2);n.push(` ${rn(f,a+2+2).trim()}`)}t.push(...n,"")}return t.push(jt.bold("TROUBLESHOOTING")," For general support, reach out to us at https://apify.com/contact",""," If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new"),t.join(`
28
- `).trim()}c(_r,"renderMainHelpMenu");var Rr=(u=>(u[u.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",u[u.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",u[u.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",u[u.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",u[u.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",u[u.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",u[u.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",u[u.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",u[u.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",u[u.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",u))(Rr||{}),ie=class r extends Error{static{c(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(Rr[e])),this.code=e,this.metadata=o,this.command=s}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
27
+ `)[0]||"",u=`${l.name.padEnd(a)} ${m}`,f=sn(u,oe()-a-2);n.push(` ${rn(f,a+2+2).trim()}`)}t.push(...n,"")}return t.push(Vt.bold("TROUBLESHOOTING")," For general support, reach out to us at https://apify.com/contact",""," If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new"),t.join(`
28
+ `).trim()}c(_r,"renderMainHelpMenu");var xr=(u=>(u[u.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",u[u.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",u[u.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",u[u.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",u[u.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",u[u.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",u[u.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",u[u.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",u[u.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",u[u.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",u))(xr||{}),ie=class r extends Error{static{c(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(xr[e])),this.code=e,this.metadata=o,this.command=s}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
29
29
 
30
30
  Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '--(?<optionName>[a-zA-Z0-9]+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
31
31
 
32
- Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion}}default:throw new Error("Not implemented")}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return r.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),t=$r(this.command,{showUsageString:!0});return[G.gray(`Unknown flag provided: ${G.white.bold(`--${e.name}`)}`),e.unknownOptionSuggestion?G.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
33
- `)}case 3:{let e=`--${this.metadata.flag}`;return G.gray(`Flag ${G.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=G.whiteBright(String(this.metadata.value));return G.gray(`The provided value for the '${G.white.bold(e)}' flag could not be processed as an integer. Received: ${t}.`)}case 6:{let{flag:e,matcher:t,providedButReceivedNoValue:o}=this.metadata,s=`'${G.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${G.white.bold(`--${t}`)}')`),o?G.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):G.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[G.gray("The following errors occurred:")],o=G.red(" > ");for(let[s,i]of e)t.push(G.gray(`${o}${G.white.bold(s)} cannot also be provided when using ${G.white.bold(i)}`));return t.push(G.gray(`${o}See more help with ${G.white.bold("--help")}`)),t.join(`
34
- `)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return G.gray(`Flag ${G.white.bold(`--${e}`)} and ${G.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=K();return["The CLI encountered an unhandled argument parsing error!","Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:","",`- Error code: ${this.code} (${Rr[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
35
- ${this.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(process.argv.slice(2))}`,"",`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${be?"Yes":"No"}`].join(`
36
- `)}}}static buildMessageFromFlagData(e){let t=[`Flag ${G.white.bold(`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
32
+ Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion}}default:throw new Error("Not implemented")}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return r.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),t=Rr(this.command,{showUsageString:!0});return[Y.gray(`Unknown flag provided: ${Y.white.bold(`--${e.name}`)}`),e.unknownOptionSuggestion?Y.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
33
+ `)}case 3:{let e=`--${this.metadata.flag}`;return Y.gray(`Flag ${Y.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=Y.whiteBright(String(this.metadata.value));return Y.gray(`The provided value for the '${Y.white.bold(e)}' flag could not be processed as an integer. Received: ${t}.`)}case 6:{let{flag:e,matcher:t,providedButReceivedNoValue:o}=this.metadata,s=`'${Y.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${Y.white.bold(`--${t}`)}')`),o?Y.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):Y.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[Y.gray("The following errors occurred:")],o=Y.red(" > ");for(let[s,i]of e)t.push(Y.gray(`${o}${Y.white.bold(s)} cannot also be provided when using ${Y.white.bold(i)}`));return t.push(Y.gray(`${o}See more help with ${Y.white.bold("--help")}`)),t.join(`
34
+ `)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return Y.gray(`Flag ${Y.white.bold(`--${e}`)} and ${Y.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=K();return["The CLI encountered an unhandled argument parsing error!","Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:","",`- Error code: ${this.code} (${xr[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
35
+ ${this.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(process.argv.slice(2))}`,"",`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${ve?"Yes":"No"}`].join(`
36
+ `)}}}static buildMessageFromFlagData(e){let t=[`Flag ${Y.white.bold(`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
37
37
  ${e.ambiguousMessage.split(`
38
38
  `).map(o=>` ${o}`).join(`
39
- `)}`):t.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?t.push("expects a value"):t.push("does not take an argument"),t.map(o=>G.gray(o)).join(" ")}static into(e,t){if(e instanceof r)return e;if(e instanceof Error&&"code"in e){let o=e;switch(o.code){case"ERR_PARSE_ARGS_INVALID_OPTION_VALUE":return new r({code:0,message:o.message,command:t});case"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL":return new r({code:1,message:o.message,command:t});case"ERR_PARSE_ARGS_UNKNOWN_OPTION":return new r({code:2,message:o.message,command:t});default:return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function an(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}c(an,"camelCaseString");function Ae(r){return r.replace(/[\s_]+/g,"-")}c(Ae,"kebabCaseString");function Se(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}c(Se,"camelCaseToKebabCase");var mc={type:"boolean",multiple:!1,short:"h"},dc={type:"boolean",multiple:!1},q=new Map,pc=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],y=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;skipTelemetry=!1;constructor(e,t){this.entrypoint=e,this.commandString=t;let o=K();this.telemetryData.installMethod=o.installMethod,this.telemetryData.osArch=o.arch,this.telemetryData.runtime=o.runtime.runtime,this.telemetryData.runtimeVersion=o.runtime.version,this.telemetryData.runtimeNodeVersion=o.runtime.nodeVersion??o.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log(Er(this)),process.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(e){let{values:t,positionals:o,tokens:s}=e;t.help&&this.ctor.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof t.json=="boolean"?this.flags.json=t.json:this.flags.json=!1);let i=new Map;if(this.ctor.args){let n=0;for(let[a,l]of Object.entries(this.ctor.args)){if(typeof l=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let m=an(a),u=o[n++];if(u)switch(l.argTag){case"string":default:this.args[m]=String(u),u==="-"&&l.stdin&&(this.args[m]=this._handleStdin(l.stdin)),l.catchAll&&(this.args[m]=o.slice(n-1).join(" "));break}else l.required&&i.set(a,l)}}if(i.size){this._printMissingRequiredArgs(i);return}this._parseFlags(t,s);try{await this.run()}catch(n){p({message:n.message})}finally{!this.telemetryData.actorLanguage&&pc.includes(this.commandString)&&(await Me()).inspect(a=>{a.type===0?(this.telemetryData.actorLanguage="javascript",this.telemetryData.actorRuntime=a.runtime.runtimeShorthand||"node",this.telemetryData.actorRuntimeVersion=a.runtime.version):(a.type===1||a.type===2)&&(this.telemetryData.actorLanguage="python",this.telemetryData.actorRuntime="python",this.telemetryData.actorRuntimeVersion=a.runtime.version)}),this.telemetryData.flagsUsed=Object.keys(this.flags),this.skipTelemetry||await Fi(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData)}}_userFlagNameToRegisteredName(e,t){let o=Ae(Se(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ae(Se(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ae(Se(e)).toLowerCase();return t.startsWith("no-")&&(t=t.slice(3)),t}_parseFlags(e,t){if(!this.ctor.flags)return;let o=new Map,s;for(let[n,a]of Object.entries(this.ctor.flags)){if(typeof a=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let{allMatchers:l,baseFlagName:m,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(n,a),f=an(u),d=t.some(S=>S.kind==="option"&&S.name===m);if(a.exclusive?.length){let S=o.get(m)??new Set;for(let I of a.exclusive)S.add(this._commandFlagKeyToKebabCaseRegisteredName(I));o.set(m,S);for(let I of a.exclusive){let v=this._commandFlagKeyToKebabCaseRegisteredName(I),E=o.get(v)??new Set;E.add(m),o.set(v,E)}}let g=l.filter(S=>e[S]);if(g.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:m}});let h=e[g[0]];if(!h&&a.required)throw new ie({code:6,command:this.ctor,metadata:{flag:m,matcher:g[0]}});if(Array.isArray(h)){if(h.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:m}});h=h[0]}if(d&&typeof h=="string"&&h.startsWith("=")&&(h=h.slice(1)),typeof h<"u")switch(a.flagTag){case"boolean":{this.flags[f]=u.startsWith("no-")?!h:h;break}case"integer":{let S=Number(h);if(Number.isNaN(S)||!Number.isInteger(S))throw new ie({code:4,command:this.ctor,metadata:{flag:m,value:String(h)}});this.flags[f]=S;break}case"string":default:{if(this.flags[f]=h,h==="-"&&a.stdin){if(s)throw new ie({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:m}});s=m,this.flags[f]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[f]=a.hasDefault);if(this.flags[f]&&a.choices&&!a.choices.includes(this.flags[f]))throw new ie({code:5,command:this.ctor,metadata:{flag:m,choices:a.choices.map(S=>Rs.white.bold(S)).join(", ")}});if(this.flags[f]==null&&(a.required||h!=null))throw new ie({code:6,command:this.ctor,metadata:{flag:m,matcher:g[0],providedButReceivedNoValue:!!h}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let l of a){if(e[l]==null)continue;let m=e[n][0],u=e[l][0],f=c((d,g)=>typeof g=="boolean"?g?`--${d}`:`--no-${d}`:`--${d}=${g}`,"flagRepresentation");i.push([f(n,m),f(l,u)]);break}if(i.length)throw new ie({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t=$r(this.ctor,{showUsageString:!0}),o=cc([...e.keys()].join(`
40
- `)),s=[];for(let[i,n]of e){let a=`${i.padEnd(o)} ${n.description}`,l=uc(a,oe()-o-2),m=lc(l,o+2+2).trim();s.push(` ${Rs.red(">")} ${m}`)}p({message:[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,Rs.gray(" See more help with --help"),"",t].join(`
41
- `)})}_handleStdin(e){switch(e){case 2:return(be?.toString("utf8")??"").trim();default:return be}}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:mc}};if(this.ctor.flags)for(let[t,o]of Object.entries(this.ctor.flags)){if(typeof o=="string")throw new RangeError("Do not provide the string for the json flag! It is a type level assertion!");if(t.toLowerCase()==="json")continue;let s=Ae(Se(t)).toLowerCase();s.startsWith("no-")&&(s=s.slice(3));let i=o.builder(s);for(let{flagName:n,option:a}of i)e.options[n]=a}return this.ctor.enableJsonFlag&&(e.options.json=dc),e}static registerCommand(e){if(_s(e,this),q.set(this.name,this),this.aliases?.length)for(let t of this.aliases)q.set(t,this);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)q.set(t,this);if(this.subcommands?.length)for(let t of this.subcommands){if(q.set(`${this.name} ${t.name}`,t),this.aliases?.length)for(let o of this.aliases)q.set(`${o} ${t.name}`,t);if(this.hiddenAliases?.length)for(let o of this.hiddenAliases)q.set(`${o} ${t.name}`,t);if(t.aliases?.length)for(let o of t.aliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}if(t.hiddenAliases?.length)for(let o of t.hiddenAliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}}}};async function ln(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[l,m]=n.split("_");if(l==="args")o.positionals[s++]=a;else{let u=Ae(Se(m)).toLowerCase();u.startsWith("no-")?o.values[u.slice(3)]=!a:o.values[u]=a}}let i=new e(r,e.name);i.skipTelemetry=!0,await i._run(o)}c(ln,"internalRunCommand");import{once as fc}from"events";async function cn(){let r=await wr(),{hasData:e,waitDelay:t,stream:o}=r;if(!e)return;let s=[],i=new AbortController,n=null;t&&(n=setTimeout(()=>{i.abort()},t).unref()),o.on("data",l=>{s.push(l),n&&(clearTimeout(n),n=null)});try{await fc(o,"end",{signal:i.signal})}catch(l){if(l.name==="AbortError")return}n&&clearTimeout(n),r.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}c(cn,"readStdin");import{gt as vc}from"semver";import{existsSync as gc,mkdirSync as hc,readFileSync as yc,writeFileSync as wc}from"fs";import{dirname as Ac}from"path";function Sc(r){if(r.version&&r.version>=1)return!1;let e=r;if(e.latestNpmVersionCheckedAt){let t=new Date(e.latestNpmVersionCheckedAt).getTime(),o=e.latestNpmVersion;T("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:r,newState:{versionCheck:{lastChecked:t,lastVersion:o}}}),Os({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}c(Sc,"migrateStateV0ToV1");var bc={version:1};function xs(){let r=or();if(!gc(r))return bc;let t=JSON.parse(yc(r,"utf-8"));return Sc(t)?xs():t}c(xs,"useLocalState");function Os(r,e){let t={...r};e(t);let o=or(),s=Ac(o);hc(s,{recursive:!0}),wc(or(),JSON.stringify(t,null," "))}c(Os,"updateLocalState");var Or=K(),un=`Apify CLI/${Or.version} (https://github.com/apify/apify-cli)`,Tc=["https://1.1.1.1","https://8.8.8.8"];async function Ic(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Tc.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":un},keepalive:!1}))).catch(()=>null);return clearTimeout(t),o?o.ok?(T("isOnline",{state:"online",site:o.url}),!0):(T("isOnline",{state:"offline"}),!1):(T("isOnline",{state:"timeout"}),!1)}c(Ic,"isOnline");async function Cc(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":un}});if(!e.ok)return T("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),x({message:"Failed to fetch latest version of Apify CLI, using the cached version instead."}),null;let o=(await e.json()).tag_name.replace(/^v/,"");return T("useCLIVersionCheck","Fetched latest version",{version:o}),Os(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}c(Cc,"getLatestVersion");function mn(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}c(mn,"shouldSkipVersionCheck");async function dn(r=!1){let e=xs(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>ni,o=r||t&&await Ic(),s=o?await Cc(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:Or.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=vc(s,Or.version);return{currentVersion:Or.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}c(dn,"useCLIVersionCheck");import{jaroWinkler as Ec}from"@skyra/jaro-winkler";import $c from"js-levenshtein";function Nr(r){let e=[...q.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),l=a[a.length-1].toLowerCase(),m=i.aliases?.includes(l)||i.hiddenAliases?.includes(l)||!1,u=$c(t,n),f=Ec(t,n),d=u<=2||f>=.975;return d?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:d,levenshtein:u,jaroWinkler:f}),m?{string:`${n} (alias for ${i.name})`,distance:f}:{string:`${n}`,distance:f}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}c(Nr,"useCommandSuggestions");var be=await cn(),Bt=K(),tt=`Apify CLI/${Bt.version} (https://github.com/apify/apify-cli)`;function Ph(r){Bt.installMethod!=="bundle"&&(_c(ve.version,ye)||(p({message:`${r} CLI requires Node.js version ${ye}. Your current version is ${ve.version}.`}),ve.exit(1)))}c(Ph,"processVersionCheck");function Rc(r){r.values.version===!0&&r.positionals.length===0&&(console.log(Bt.fullVersionString),ve.exit(0))}c(Rc,"printCLIVersionAndExitIfFlagUsed");function xc(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(_r(e)),ve.exit(0))}c(xc,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function fn(r){let e=Nr(String(r)),t=Pr.gray(`Command ${Pr.whiteBright(r)} not found`);e.length&&(t+=`
42
- `,t+=Pr.gray(`Did you mean: ${e.map(o=>Pr.whiteBright(o)).join(", ")}?`)),p({message:t}),ve.exit(1)}c(fn,"handleCommandNotFound");async function Oc(r,e){let t=q.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){T("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(mn()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await ln(r,t,{flags_internalAutomaticCall:!0})}c(Oc,"runVersionCheck");async function Lh(r){T("CLIMetadata",{...Bt,fullVersionString:Bt.fullVersionString,argv:ve.argv,cwd:ve.cwd(),execPath:ve.execPath});let e=ve.argv.slice(2);T("ProcessArgv",e);let t=pn({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Rc(t),xc(t,r),await Oc(r,t.positionals[0]),T("TopLevelOptions",t);let[o,s]=t.positionals,i=!1,n=q.get(o);if(!n)return fn(o);let a=n;if(n.subcommands?.length){if(!s)return n.printHelp();i=!0,a=q.get(`${o} ${s}`)}if(!a)return fn(`${o} ${s}`);let l=[...e],m=l.indexOf(o);if(T("CommandNameIndex",m),l.splice(m,1),i){let d=l.indexOf(s);T("SubcommandNameIndex",d),l.splice(d,1)}T("RebuiltArgs",l),T("CommandToRun",a);let u=new a(r,i?`${n.name} ${s}`:n.name),f=u._buildParseArgsOption();T("ParserOptionsForCommand",f);try{let d=pn({...f,args:l});await u._run(d),T("CommandArgsResult",d)}catch(d){let g=ie.into(d,a);p({message:g.getPrettyMessage()}),ve.exit(1)}}c(Lh,"runCLI");import{APIFY_ENV_VARS as Vc}from"@apify/consts";import Gt from"process";import{pipeline as Nc}from"stream/promises";import{MemoryStorage as Pc}from"@crawlee/memory-storage";import{ApifyClient as Lc}from"apify-client";import{ACTOR_ENV_VARS as gn,APIFY_ENV_VARS as hn,KEY_VALUE_STORE_KEYS as Dc,LOCAL_ACTOR_ENV_VARS as Fc}from"@apify/consts";var Yt={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},Ns=c(async()=>{let r=Gt.env[hn.TOKEN];if(r)return r;let e=await D();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),st=c(async(r={},e=Reflect.has(Gt.env,hn.IS_AT_HOME))=>{let t=ce();if(t&&!e)return new Pc({localDataDirectory:t,...r});let o=await Ns();return new Lc({...ws(o),...r})},"getApifyStorageClient"),Ht=c(r=>{let e=gn[`DEFAULT_${r}_ID`];return Gt.env[e]||Fc[e]},"getDefaultStorageId"),Ps=c(async r=>{let e=await st(),t=Ht(Yt.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await Nc(o.value,Gt.stdout,{end:!1})},"outputRecordFromDefaultStore"),yn=c(async()=>Ps(Gt.env[gn.INPUT_KEY]||Dc.INPUT),"outputInputFromDefaultStore");function kc(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}c(kc,"stringArg");var w={string:kc};var A={string:Uc,boolean:Mc,integer:jc};function Uc(r){return{flagTag:"string",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ae(Se(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:r.choices,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??2,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(Uc,"stringFlag");function Mc(r){return{flagTag:"boolean",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"boolean",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ae(Se(s)).toLowerCase(),option:{type:"boolean",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(Mc,"booleanFlag");function jc(r){return{flagTag:"integer",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Ae(Se(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(jc,"integerFlag");var pt=class extends y{static name="charge";static description="Charge for a specific event in the pay-per-event Actor run.";static args={eventName:w.string({description:"Name of the event to charge for",required:!0})};static flags={count:A.integer({description:"Number of events to charge",required:!1,default:1}),"idempotency-key":A.string({description:"Idempotency key for the charge request",required:!1}),"test-pay-per-event":A.boolean({description:"Test pay-per-event charging without actually charging",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){b({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){b({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await Ns(),a=await Nt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let l=process.env[Vc.ACTOR_RUN_ID];if(!l)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(l).get())?.pricingInfo?.pricingModel!=="PAY_PER_EVENT")throw new Error("Charge command can only be used with pay-per-event pricing model.");b({message:`Charging ${t} events of type "${e}" with idempotency key "${s??"not-provided"}" (runId: ${l}).`,stdout:!0}),await a.run(l).charge({eventName:e,count:t,idempotencyKey:s})}};var ft=class extends y{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";async run(){await yn()}};import{ACTOR_ENV_VARS as Ls,APIFY_ENV_VARS as wn}from"@apify/consts";import{createHmacSignature as Bc}from"@apify/utilities";var gt=class extends y{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[wn.IS_AT_HOME])){p({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[wn.API_PUBLIC_BASE_URL],o=process.env[Ls.DEFAULT_KEY_VALUE_STORE_ID];if(!o){p({message:`Missing environment variable: ${Ls.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let i=await(await st()).keyValueStore(o).get(),n=new URL(`${t}/v2/key-value-stores/${o}/records/${e}`);if(!i){p({message:`Key-Value store with ID '${o}' was not found. Ensure the store exists and that the correct ID is set in ${Ls.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let{urlSigningSecretKey:a}=i;a&&n.searchParams.append("signature",Bc(a,e)),console.log(n.toString())}};var ht=class extends y{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;await Ps(e)}};var yt=class extends y{static name="push-data";static description=`Saves data to Actor's run default dataset.
39
+ `)}`):t.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?t.push("expects a value"):t.push("does not take an argument"),t.map(o=>Y.gray(o)).join(" ")}static into(e,t){if(e instanceof r)return e;if(e instanceof Error&&"code"in e){let o=e;switch(o.code){case"ERR_PARSE_ARGS_INVALID_OPTION_VALUE":return new r({code:0,message:o.message,command:t});case"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL":return new r({code:1,message:o.message,command:t});case"ERR_PARSE_ARGS_UNKNOWN_OPTION":return new r({code:2,message:o.message,command:t});default:return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function an(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}c(an,"camelCaseString");function Se(r){return r.replace(/[\s_]+/g,"-")}c(Se,"kebabCaseString");function be(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}c(be,"camelCaseToKebabCase");var uc={type:"boolean",multiple:!1,short:"h"},mc={type:"boolean",multiple:!1},q=new Map,dc=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],y=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;skipTelemetry=!1;constructor(e,t){this.entrypoint=e,this.commandString=t;let o=K();this.telemetryData.installMethod=o.installMethod,this.telemetryData.osArch=o.arch,this.telemetryData.runtime=o.runtime.runtime,this.telemetryData.runtimeVersion=o.runtime.version,this.telemetryData.runtimeNodeVersion=o.runtime.nodeVersion??o.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log($r(this)),process.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(e){let{values:t,positionals:o,tokens:s}=e;t.help&&this.ctor.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof t.json=="boolean"?this.flags.json=t.json:this.flags.json=!1);let i=new Map;if(this.ctor.args){let n=0;for(let[a,l]of Object.entries(this.ctor.args)){if(typeof l=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let m=an(a),u=o[n++];if(u)switch(l.argTag){case"string":default:this.args[m]=String(u),u==="-"&&l.stdin&&(this.args[m]=this._handleStdin(l.stdin)),l.catchAll&&(this.args[m]=o.slice(n-1).join(" "));break}else l.required&&i.set(a,l)}}if(i.size){this._printMissingRequiredArgs(i);return}this._parseFlags(t,s);try{await this.run()}catch(n){p({message:n.message})}finally{!this.telemetryData.actorLanguage&&dc.includes(this.commandString)&&(await Me()).inspect(a=>{a.type===0?(this.telemetryData.actorLanguage="javascript",this.telemetryData.actorRuntime=a.runtime.runtimeShorthand||"node",this.telemetryData.actorRuntimeVersion=a.runtime.version):(a.type===1||a.type===2)&&(this.telemetryData.actorLanguage="python",this.telemetryData.actorRuntime="python",this.telemetryData.actorRuntimeVersion=a.runtime.version)}),this.telemetryData.flagsUsed=Object.keys(this.flags),this.skipTelemetry||await Fi(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData)}}_userFlagNameToRegisteredName(e,t){let o=Se(be(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Se(be(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Se(be(e)).toLowerCase();return t.startsWith("no-")&&(t=t.slice(3)),t}_parseFlags(e,t){if(!this.ctor.flags)return;let o=new Map,s;for(let[n,a]of Object.entries(this.ctor.flags)){if(typeof a=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let{allMatchers:l,baseFlagName:m,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(n,a),f=an(u),d=t.some(S=>S.kind==="option"&&S.name===m);if(a.exclusive?.length){let S=o.get(m)??new Set;for(let b of a.exclusive)S.add(this._commandFlagKeyToKebabCaseRegisteredName(b));o.set(m,S);for(let b of a.exclusive){let T=this._commandFlagKeyToKebabCaseRegisteredName(b),E=o.get(T)??new Set;E.add(m),o.set(T,E)}}let g=l.filter(S=>e[S]);if(g.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:m}});let h=e[g[0]];if(!h&&a.required)throw new ie({code:6,command:this.ctor,metadata:{flag:m,matcher:g[0]}});if(Array.isArray(h)){if(h.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:m}});h=h[0]}if(d&&typeof h=="string"&&h.startsWith("=")&&(h=h.slice(1)),typeof h<"u")switch(a.flagTag){case"boolean":{this.flags[f]=u.startsWith("no-")?!h:h;break}case"integer":{let S=Number(h);if(Number.isNaN(S)||!Number.isInteger(S))throw new ie({code:4,command:this.ctor,metadata:{flag:m,value:String(h)}});this.flags[f]=S;break}case"string":default:{if(this.flags[f]=h,h==="-"&&a.stdin){if(s)throw new ie({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:m}});s=m,this.flags[f]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[f]=a.hasDefault);if(this.flags[f]&&a.choices&&!a.choices.includes(this.flags[f]))throw new ie({code:5,command:this.ctor,metadata:{flag:m,choices:a.choices.map(S=>_s.white.bold(S)).join(", ")}});if(this.flags[f]==null&&(a.required||h!=null))throw new ie({code:6,command:this.ctor,metadata:{flag:m,matcher:g[0],providedButReceivedNoValue:!!h}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let l of a){if(e[l]==null)continue;let m=e[n][0],u=e[l][0],f=c((d,g)=>typeof g=="boolean"?g?`--${d}`:`--no-${d}`:`--${d}=${g}`,"flagRepresentation");i.push([f(n,m),f(l,u)]);break}if(i.length)throw new ie({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t=Rr(this.ctor,{showUsageString:!0}),o=lc([...e.keys()].join(`
40
+ `)),s=[];for(let[i,n]of e){let a=`${i.padEnd(o)} ${n.description}`,l=cc(a,oe()-o-2),m=ac(l,o+2+2).trim();s.push(` ${_s.red(">")} ${m}`)}p({message:[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,_s.gray(" See more help with --help"),"",t].join(`
41
+ `)})}_handleStdin(e){switch(e){case 2:return(ve?.toString("utf8")??"").trim();default:return ve}}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:uc}};if(this.ctor.flags)for(let[t,o]of Object.entries(this.ctor.flags)){if(typeof o=="string")throw new RangeError("Do not provide the string for the json flag! It is a type level assertion!");if(t.toLowerCase()==="json")continue;let s=Se(be(t)).toLowerCase();s.startsWith("no-")&&(s=s.slice(3));let i=o.builder(s);for(let{flagName:n,option:a}of i)e.options[n]=a}return this.ctor.enableJsonFlag&&(e.options.json=mc),e}static registerCommand(e){if(Rs(e,this),q.set(this.name,this),this.aliases?.length)for(let t of this.aliases)q.set(t,this);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)q.set(t,this);if(this.subcommands?.length)for(let t of this.subcommands){if(q.set(`${this.name} ${t.name}`,t),this.aliases?.length)for(let o of this.aliases)q.set(`${o} ${t.name}`,t);if(this.hiddenAliases?.length)for(let o of this.hiddenAliases)q.set(`${o} ${t.name}`,t);if(t.aliases?.length)for(let o of t.aliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}if(t.hiddenAliases?.length)for(let o of t.hiddenAliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}}}};async function ln(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[l,m]=n.split("_");if(l==="args")o.positionals[s++]=a;else{let u=Se(be(m)).toLowerCase();u.startsWith("no-")?o.values[u.slice(3)]=!a:o.values[u]=a}}let i=new e(r,e.name);i.skipTelemetry=!0,await i._run(o)}c(ln,"internalRunCommand");import{once as pc}from"events";async function cn(){let r=await Ar(),{hasData:e,waitDelay:t,stream:o}=r;if(!e)return;let s=[],i=new AbortController,n=null;t&&(n=setTimeout(()=>{i.abort()},t).unref()),o.on("data",l=>{s.push(l),n&&(clearTimeout(n),n=null)});try{await pc(o,"end",{signal:i.signal})}catch(l){if(l.name==="AbortError")return}n&&clearTimeout(n),r.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}c(cn,"readStdin");import{gt as bc}from"semver";import{existsSync as fc,mkdirSync as gc,readFileSync as hc,writeFileSync as yc}from"fs";import{dirname as wc}from"path";function Ac(r){if(r.version&&r.version>=1)return!1;let e=r;if(e.latestNpmVersionCheckedAt){let t=new Date(e.latestNpmVersionCheckedAt).getTime(),o=e.latestNpmVersion;I("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:r,newState:{versionCheck:{lastChecked:t,lastVersion:o}}}),Os({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}c(Ac,"migrateStateV0ToV1");var Sc={version:1};function xs(){let r=sr();if(!fc(r))return Sc;let t=JSON.parse(hc(r,"utf-8"));return Ac(t)?xs():t}c(xs,"useLocalState");function Os(r,e){let t={...r};e(t);let o=sr(),s=wc(o);gc(s,{recursive:!0}),yc(sr(),JSON.stringify(t,null," "))}c(Os,"updateLocalState");var Nr=K(),un=`Apify CLI/${Nr.version} (https://github.com/apify/apify-cli)`,vc=["https://1.1.1.1","https://8.8.8.8"];async function Tc(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(vc.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":un},keepalive:!1}))).catch(()=>null);return clearTimeout(t),o?o.ok?(I("isOnline",{state:"online",site:o.url}),!0):(I("isOnline",{state:"offline"}),!1):(I("isOnline",{state:"timeout"}),!1)}c(Tc,"isOnline");async function Ic(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":un}});if(!e.ok)return I("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),x({message:"Failed to fetch latest version of Apify CLI, using the cached version instead."}),null;let o=(await e.json()).tag_name.replace(/^v/,"");return I("useCLIVersionCheck","Fetched latest version",{version:o}),Os(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}c(Ic,"getLatestVersion");function mn(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}c(mn,"shouldSkipVersionCheck");async function dn(r=!1){let e=xs(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>ni,o=r||t&&await Tc(),s=o?await Ic(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:Nr.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=bc(s,Nr.version);return{currentVersion:Nr.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}c(dn,"useCLIVersionCheck");import{jaroWinkler as Cc}from"@skyra/jaro-winkler";import Ec from"js-levenshtein";function Pr(r){let e=[...q.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),l=a[a.length-1].toLowerCase(),m=i.aliases?.includes(l)||i.hiddenAliases?.includes(l)||!1,u=Ec(t,n),f=Cc(t,n),d=u<=2||f>=.975;return d?(I("useCommandSuggestions",{inputString:t,lowercased:n,matches:d,levenshtein:u,jaroWinkler:f}),m?{string:`${n} (alias for ${i.name})`,distance:f}:{string:`${n}`,distance:f}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}c(Pr,"useCommandSuggestions");var ve=await cn(),Gt=K(),tt=`Apify CLI/${Gt.version} (https://github.com/apify/apify-cli)`;function Ph(r){Gt.installMethod!=="bundle"&&($c(Te.version,we)||(p({message:`${r} CLI requires Node.js version ${we}. Your current version is ${Te.version}.`}),Te.exit(1)))}c(Ph,"processVersionCheck");function Rc(r){r.values.version===!0&&r.positionals.length===0&&(console.log(Gt.fullVersionString),Te.exit(0))}c(Rc,"printCLIVersionAndExitIfFlagUsed");function _c(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(_r(e)),Te.exit(0))}c(_c,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function fn(r){let e=Pr(String(r)),t=Lr.gray(`Command ${Lr.whiteBright(r)} not found`);e.length&&(t+=`
42
+ `,t+=Lr.gray(`Did you mean: ${e.map(o=>Lr.whiteBright(o)).join(", ")}?`)),p({message:t}),Te.exit(1)}c(fn,"handleCommandNotFound");async function xc(r,e){let t=q.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){I("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(mn()){I("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await ln(r,t,{flags_internalAutomaticCall:!0})}c(xc,"runVersionCheck");async function Lh(r){I("CLIMetadata",{...Gt,fullVersionString:Gt.fullVersionString,argv:Te.argv,cwd:Te.cwd(),execPath:Te.execPath});let e=Te.argv.slice(2);I("ProcessArgv",e);let t=pn({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Rc(t),_c(t,r),await xc(r,t.positionals[0]),I("TopLevelOptions",t);let[o,s]=t.positionals,i=!1,n=q.get(o);if(!n)return fn(o);let a=n;if(n.subcommands?.length){if(!s)return n.printHelp();i=!0,a=q.get(`${o} ${s}`)}if(!a)return fn(`${o} ${s}`);let l=[...e],m=l.indexOf(o);if(I("CommandNameIndex",m),l.splice(m,1),i){let d=l.indexOf(s);I("SubcommandNameIndex",d),l.splice(d,1)}I("RebuiltArgs",l),I("CommandToRun",a);let u=new a(r,i?`${n.name} ${s}`:n.name),f=u._buildParseArgsOption();I("ParserOptionsForCommand",f);try{let d=pn({...f,args:l});await u._run(d),I("CommandArgsResult",d)}catch(d){let g=ie.into(d,a);p({message:g.getPrettyMessage()}),Te.exit(1)}}c(Lh,"runCLI");import{APIFY_ENV_VARS as jc}from"@apify/consts";import Yt from"process";import{pipeline as Oc}from"stream/promises";import{MemoryStorage as Nc}from"@crawlee/memory-storage";import{ApifyClient as Pc}from"apify-client";import{ACTOR_ENV_VARS as gn,APIFY_ENV_VARS as hn,KEY_VALUE_STORE_KEYS as Lc,LOCAL_ACTOR_ENV_VARS as Dc}from"@apify/consts";var Ht={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},Ns=c(async()=>{let r=Yt.env[hn.TOKEN];if(r)return r;let e=await F();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),st=c(async(r={},e=Reflect.has(Yt.env,hn.IS_AT_HOME))=>{let t=ce();if(t&&!e)return new Nc({localDataDirectory:t,...r});let o=await Ns();return new Pc({...ws(o),...r})},"getApifyStorageClient"),Jt=c(r=>{let e=gn[`DEFAULT_${r}_ID`];return Yt.env[e]||Dc[e]},"getDefaultStorageId"),Ps=c(async r=>{let e=await st(),t=Jt(Ht.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await Oc(o.value,Yt.stdout,{end:!1})},"outputRecordFromDefaultStore"),yn=c(async()=>Ps(Yt.env[gn.INPUT_KEY]||Lc.INPUT),"outputInputFromDefaultStore");function Fc(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}c(Fc,"stringArg");var w={string:Fc};var A={string:kc,boolean:Uc,integer:Mc};function kc(r){return{flagTag:"string",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Se(be(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:r.choices,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??2,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(kc,"stringFlag");function Uc(r){return{flagTag:"boolean",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"boolean",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Se(be(s)).toLowerCase(),option:{type:"boolean",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(Uc,"booleanFlag");function Mc(r){return{flagTag:"integer",builder:c(e=>{let t=new Set([...r.aliases??[]]);t.delete(e);let o=[{flagName:e,option:{type:"string",multiple:!0}}];r.char&&(o[0].option.short=r.char);for(let s of t)o.push({flagName:Se(be(s)).toLowerCase(),option:{type:"string",multiple:!0}});return o},"builder"),choices:null,required:r.required??!1,hasDefault:r.default,stdin:r.stdin??1,description:r.description,aliases:r.aliases,char:r.char,hidden:r.hidden,exclusive:r.exclusive}}c(Mc,"integerFlag");var pt=class extends y{static name="charge";static description="Charge for a specific event in the pay-per-event Actor run.";static args={eventName:w.string({description:"Name of the event to charge for",required:!0})};static flags={count:A.integer({description:"Number of events to charge",required:!1,default:1}),"idempotency-key":A.string({description:"Idempotency key for the charge request",required:!1}),"test-pay-per-event":A.boolean({description:"Test pay-per-event charging without actually charging",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){v({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){v({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await Ns(),a=await Pt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let l=process.env[jc.ACTOR_RUN_ID];if(!l)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(l).get())?.pricingInfo?.pricingModel!=="PAY_PER_EVENT")throw new Error("Charge command can only be used with pay-per-event pricing model.");v({message:`Charging ${t} events of type "${e}" with idempotency key "${s??"not-provided"}" (runId: ${l}).`,stdout:!0}),await a.run(l).charge({eventName:e,count:t,idempotencyKey:s})}};var ft=class extends y{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";async run(){await yn()}};import{ACTOR_ENV_VARS as Ls,APIFY_ENV_VARS as Vc}from"@apify/consts";var gt=class extends y{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[Vc.IS_AT_HOME])){p({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[Ls.DEFAULT_KEY_VALUE_STORE_ID];if(!t){p({message:`Missing environment variable: ${Ls.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let o=await st();if(!await o.keyValueStore(t).get()){p({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${Ls.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let i=await o.keyValueStore(t).getRecordPublicUrl(e);console.log(i)}};var ht=class extends y{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;await Ps(e)}};var yt=class extends y{static name="push-data";static description=`Saves data to Actor's run default dataset.
43
43
 
44
44
  Accept input as:
45
45
  - JSON argument:
46
46
  $ apify actor push-data {"key": "value"}
47
47
  - Piped stdin:
48
- $ cat ./test.json | apify actor push-data`;static args={item:w.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,t=e||be;if(!t){p({message:"No item was provided."});return}let o=await st(),s=Ht(Yt.DATASET),i;try{i=JSON.parse(t.toString("utf8"))}catch(n){throw new Error(`Failed to parse data as JSON string: ${n.message}`)}await o.dataset(s).pushItems(i)}};var wt=class extends y{static name="set-value";static description=`Sets or removes record into the default key-value store associated with the Actor run.
48
+ $ cat ./test.json | apify actor push-data`;static args={item:w.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,t=e||ve;if(!t){p({message:"No item was provided."});return}let o=await st(),s=Jt(Ht.DATASET),i;try{i=JSON.parse(t.toString("utf8"))}catch(n){throw new Error(`Failed to parse data as JSON string: ${n.message}`)}await o.dataset(s).pushItems(i)}};var wt=class extends y{static name="set-value";static description=`Sets or removes record into the default key-value store associated with the Actor run.
49
49
 
50
50
  It is possible to pass data using argument or stdin.
51
51
 
@@ -56,107 +56,107 @@ Passing data using stdin with pipe:
56
56
  $ cat ./my-text-file.txt | apify actor set-value KEY --contentType text/plain`;static args={key:w.string({required:!0,description:"Key of the record in key-value store."}),value:w.string({required:!1,description:`Record data, which can be one of the following values:
57
57
  - If empty, the record in the key-value store is deleted.
58
58
  - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
59
- - If options.contentType is set, value is taken as is.`})};static flags={contentType:A.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:o="application/json; charset=utf-8"}=this.flags,s=t||process.stdin,n=(await st()).keyValueStore(Ht(Yt.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var Dr=class extends y{static name="actor";static description="Manages runtime data operations inside of a running Actor.";static subcommands=[wt,yt,ht,gt,ft,pt];async run(){this.printHelp()}};import _e from"chalk";import Gc from"process";async function Ve({providedActorNameOrId:r,client:e}){let t=await D(),o=t.username||t.id,s=Fe(Gc.cwd())||{};if(r?.includes("/")){let i=await e.actor(r).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with ID "${r}" was not found`}}if(r){let i=await e.actor(r).get();if(i)return{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id};let n=await e.actor(`${o}/${r.toLowerCase()}`).get();return n?{valid:!0,userFriendlyId:`${n.username}/${n.name}`,id:n.id}:{valid:!1,reason:`Actor with name or ID "${r}" was not found`}}if(s.name){let i=await e.actor(`${o}/${s.name}`).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with name "${s.name}" was not found`}}return{valid:!1,reason:"Unable to detect what Actor to create a build for"}}c(Ve,"resolveActorContext");var At=class extends y{static name="create";static description="Creates a new build of the Actor.";static flags={tag:A.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:A.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:A.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:w.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:e,version:t,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await C(),a=await Ve({providedActorNameOrId:i,client:n});if(!a.valid){p({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await n.actor(a.id).get(),u=fr(l.versions,E=>E.buildTag??"latest")[e??"latest"],f=l.versions.find(E=>E.versionNumber===t),d,g=e;if(f){if(e&&(!u||!u.some(E=>E.versionNumber===t))){p({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}d=t,g=f.buildTag??"latest"}else if(u&&(d=u[0].versionNumber,g=e??"latest",u.length>1&&!t)){p({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
60
- Available versions for this tag: ${u.map(E=>_e.yellow(E.versionNumber)).join(", ")}`,stdout:!0});return}if(!d){p({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let h=await n.actor(a.id).build(d,{tag:e});if(o){N(h);return}let S=[`${_e.yellow("Actor")}: ${l?.username?`${l.username}/`:""}${l?.name??"unknown-actor"} (${_e.gray(h.actId)})`,` ${_e.yellow("Version")}: ${d} (tagged with ${_e.yellow(g)})`,"",`${_e.greenBright("Build Started")} (ID: ${_e.gray(h.id)})`,` ${_e.yellow("Build Number")}: ${h.buildNumber} (will get tagged once finished)`,` ${_e.yellow("Started")}: ${V.display(h.startedAt)}`,""],I=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,v=`${_e.blue("View in Apify Console")}: ${I}`;if(R({message:S.join(`
61
- `),stdout:!0}),s){try{await Ee({job:h,apifyClient:n})}catch(E){p({message:`Failed to print log for build with ID "${h.id}": ${E.message}`,stdout:!0})}R({message:"",stdout:!0})}R({message:v,stdout:!0})}};var Fr=class extends At{static name="build"};import vn from"process";import{DownloadItemsFormat as qc}from"apify-client";import re from"chalk";import{access as Yc,readFile as Hc}from"fs/promises";import Jc,{resolve as An}from"path";import Re from"process";import Kc from"mime";function Sn(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Pt(r);s&&(Kc.getExtension(s.contentType)==="json"?(t=JSON.parse(s.body.toString("utf8")),o="application/json"):(t=s.body,o=s.contentType))}return!t||!o?null:{inputToUse:t,contentType:o}}c(Sn,"resolveInput");async function St(r,e,t){let o,s;if(!e&&!t){let i=be;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return p({message:"The provided input is invalid. It should be an object, not an array."}),Re.exitCode=5,!1;o=n,s="stdin"}catch(n){return p({message:`Cannot parse JSON input from standard input.
62
- ${n.message}`}),Re.exitCode=5,!1}}if(e)switch(e[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),Re.exitCode=5,!1;default:{let i=await Yc(An(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Jc.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return p({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),Re.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),Re.exitCode=5,!1;o=a,s="input"}catch(a){return p({message:`Cannot parse JSON input.
63
- ${a.message}`}),Re.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),Re.exitCode=5,!1;default:{let i=An(r,t),n;try{let a=await Hc(i,"utf8"),l=JSON.parse(a);if(Array.isArray(l))return p({message:"The provided input is invalid. It should be an object, not an array."}),Re.exitCode=5,!1;o=l,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),Re.exitCode=5,!1;o=a,s=t}catch{return p({message:`Cannot read input file at path "${i}".
64
- ${n.message}`}),Re.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}c(St,"getInputOverride");import Ds from"process";import kr from"chalk";import{ACTOR_JOB_STATUSES as Be}from"@apify/consts";var bn=[Be.SUCCEEDED,Be.ABORTED,Be.FAILED,Be.TIMED_OUT];async function*bt(r,e){let t=Ds.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:l,waitForRunToFinish:m,printRunLogs:u}=e,f=i==="Actor"?"actor":"task",d=Sn(t,a);l||(i==="Actor"?he({message:`Calling ${i} ${o.userFriendlyId} (${kr.gray(o.id)})
65
- `}):o.title?he({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${kr.gray(o.id)})
66
- `}):he({message:`Calling ${i} ${o.userFriendlyId} (${kr.gray(o.id)})
67
- `}));let g;try{d&&i==="Actor"?g=await r[f](o.id).start(d.inputToUse,{...s,contentType:d.contentType}):g=await r[f](o.id).start(void 0,s)}catch(h){throw h.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):h}if(yield g,!l&&u)try{await Ee({job:g,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
68
- ${kr.gray("Timeout for printing logs was hit, there may be future logs.")}
69
- `):console.error()}catch(h){x({message:"Can not get log:"}),console.error(h)}if(g=await r.run(g.id).get(),m)for(;!bn.includes(g.status)&&(g=await r.run(g.id).get(),!bn.includes(g.status));)await new Promise(h=>{setTimeout(h,1e3)});l||(g.status===Be.SUCCEEDED?$({message:`${i} finished.`}):g.status===Be.RUNNING?x({message:`${i} is still running!`}):g.status===Be.ABORTED||g.status===Be.ABORTING?(x({message:`${i} was aborted!`}),Ds.exitCode=3):(p({message:`${i} failed!`}),Ds.exitCode=1)),yield g}c(bt,"runActorOrTaskOnCloud");var vt=c(r=>({build:A.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:A.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:A.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var Ge=class r extends y{static name="call";static description=`Executes Actor remotely using your authenticated account.
70
- Reads input from local key-value store by default.`;static flags={...vt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({char:"f",description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:A.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":A.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=vn.cwd(),t=Fe(e)||{},o=await C(),s=await D(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){p({message:"You cannot use both the --json and --output-dataset flags when running this command."}),vn.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:l}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),m={waitForFinish:2};this.flags.build&&(m.build=this.flags.build),this.flags.timeout&&(m.timeout=this.flags.timeout),this.flags.memory&&(m.memory=this.flags.memory);let u=await St(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=!1,d,g,h,S=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:m,type:"Actor",inputOverride:u?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let I of S)if(d=I,!f&&(f=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${I.id}`,h=`https://console.apify.com/storage/datasets/${I.defaultDatasetId}`;let v=[`${re.yellow("Started")}: ${V.display(I.startedAt)}`];I.containerUrl&&v.push(`${re.yellow("Container URL")}: ${re.blue(I.containerUrl)}`);let E=d.buildNumber.split(".").slice(0,2).join("."),P=l.versions.find(Y=>Y.versionNumber===E),L=Object.entries(l.taggedBuilds??{}).find(([,Y])=>Y.buildNumber===I.buildNumber)?.[0],M=[`${re.yellow("Build")}:`,re.cyan(d.buildNumber)];L?M.push(`(${re.yellow(L)})`):M.push(`(${re.gray("N/A")})`),P&&M.push(`| ${re.gray("Actor version:")} ${re.cyan(P.versionNumber)} (${re.yellow(P.buildTag)})`),v.push(M.join(" ")),v.push(`${re.yellow("Timeout")}: ${d.options.timeoutSecs.toLocaleString("en-US")} seconds`),v.push(`${re.yellow("Memory")}: ${d.options.memoryMbytes} MB`),v.push(`${re.blue("View on Apify Console")}: ${g}`,""),R({message:v.join(`
71
- `),stdout:!this.flags.json})}if(this.flags.json){N(d);return}if(this.flags.silent||R({message:["",`${re.blue("Export results")}: ${h}`,`${re.blue("View on Apify Console")}: ${g}`].join(`
72
- `),stdout:!0}),this.flags.outputDataset){let I=d.defaultDatasetId,v,E=4;do{if(v=await o.dataset(I).get(),v?.itemCount)break;await new Promise(L=>{setTimeout(L,250)})}while(E--);let P=await o.dataset(I).downloadItems(qc.JSON,{clean:!0});console.log(P.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:o,providedActorNameOrId:s}){if(s?.includes("/")){let i=await e.actor(s).get();if(!i)throw new Error(`Cannot find Actor with ID '${s}' in your account.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}if(s){let i=await e.actor(s).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};let n=await e.actor(`${o}/${s.toLowerCase()}`).get();if(n)return{userFriendlyId:`${n.username}/${n.name}`,id:n.id,actorData:n};throw new Error(`Cannot find Actor with name or ID '${s}' in your account.`)}if(t){let i=await e.actor(`${o}/${t}`).get();if(!i)throw new Error(`Cannot find Actor with ID '${o}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}throw new Error("Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.")}};import O from"chalk";import Wc from"cli-table3";var zc={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},Xc={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Zc={left:"",right:"",mid:"","bottom-left":"","bottom-mid":"","bottom-right":"",top:"","top-left":"","top-mid":"","top-right":"","left-mid":"","mid-mid":"","right-mid":"",bottom:"",middle:" "};var Qc={[-1]:void 0,0:zc,1:Xc,2:Zc};function eu(r){return Array.from({length:r},()=>"cyan")}c(eu,"generateHeaderColors");var tu=process.stdout.columns??100,Ur=Symbol.for("@apify/cli:responsive-table:skip-column"),B=class r{static{c(this,"ResponsiveTable")}options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=r.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,o=eu(t.length),s=e===0||e===2,i=Qc[e],n=[],a=[],l=[];for(let u of t)this.options.hiddenColumns?.includes(u)||this.rows.some(f=>f[u]===Ur)||(n.push(this.options.columnAlignments?.[u]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[u]?.label??u),l.push(this.options.breakpointOverrides?.small?.[u]?.valueFrom??u)):(a.push(u),l.push(u)));let m=new Wc({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let u of this.rows){let f=l.map(d=>u[d]);m.push(f)}return m.toString()}static isSmallTerminal(){return tu<100}};var Mr="\u200B",jr="\u200B\u200B",Tn=new B({allColumns:[Mr,jr],mandatoryColumns:[Mr,jr],columnAlignments:{[Mr]:"left",[jr]:"right"}}),Vr=class extends y{static name="info";static description="Get information about an Actor.";static flags={readme:A.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:A.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:w.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:t,input:o,json:s}=this.flags,i=await C(),n=await Ve({providedActorNameOrId:e,client:i});if(!n.valid){p({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),l=await i.user(a.userId).get();a.actorMaker=l;for(let d of Object.values(a.taggedBuilds??{})){if(!d.buildId)continue;let g=await i.build(d.buildId).get();d.build=g}if(s){N(a);return}let m=a.taggedBuilds?.latest;if(t){if(!m){p({message:"No README found for this Actor.",stdout:!0});return}if(!m.build?.readme){p({message:"No README found for this Actor.",stdout:!0});return}R({message:m.build.readme,stdout:!0})}if(o){if(!m){p({message:"No input schema found for this Actor.",stdout:!0});return}if(!m.build?.inputSchema){p({message:"No input schema found for this Actor.",stdout:!0});return}R({message:m.build.inputSchema,stdout:!0})}let u=[`Information about Actor ${O.yellow(`${a.username}/${a.name}`)} (${O.gray(a.id)})`,""];a.title&&u.push(`${O.yellow("Title:")} ${O.bold(a.title)}`),a.description&&u.push(`${O.yellow("Description:")} ${a.description}`),u.push(`${O.yellow("Created at:")} ${O.cyan(V.display(a.createdAt))} ${O.gray("|")} ${O.yellow("Updated at:")} ${O.cyan(V.display(a.modifiedAt))}`),a.actorMaker&&(u.push("",`${O.yellow("Made by:")} ${O.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(u[u.length-1]+=` ${O.bgGray("Maintained by Apify")}`)),a.isPublic?u.push("",`${O.yellow("Actor is")} ${O.green("PUBLIC")}`):u.push("",`${O.yellow("Actor is")} ${O.cyan("PRIVATE")}`),a.isDeprecated&&u.push("",`${O.yellow("Actor is")} ${O.red("DEPRECATED")}`);let f=Reflect.get(a,"pricingInfos");if(f?.length){let d=f.at(-1);switch(d.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${d.pricePerUnitUsd}/month + usage`)}`),d.trialMinutes){let g=d.trialMinutes*60*1e3,h=Ft.format(g);u.push(` ${O.yellow("Trial duration:")} ${O.bold(h)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=d.pricePerUnitUsd*1e3;u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay per event")}`);let g=Object.values(d.pricingPerEvent?.actorChargeEvents??{});for(let I of g)Tn.pushRow({[Mr]:I.eventTitle,[jr]:O.bold(`$${I.eventPriceUsd.toFixed(2)}`)});let S=Tn.render(0).split(`
59
+ - If options.contentType is set, value is taken as is.`})};static flags={contentType:A.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:o="application/json; charset=utf-8"}=this.flags,s=t||process.stdin,n=(await st()).keyValueStore(Jt(Ht.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var Fr=class extends y{static name="actor";static description="Manages runtime data operations inside of a running Actor.";static subcommands=[wt,yt,ht,gt,ft,pt];async run(){this.printHelp()}};import _e from"chalk";import Bc from"process";async function Ve({providedActorNameOrId:r,client:e}){let t=await F(),o=t.username||t.id,s=Fe(Bc.cwd())||{};if(r?.includes("/")){let i=await e.actor(r).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with ID "${r}" was not found`}}if(r){let i=await e.actor(r).get();if(i)return{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id};let n=await e.actor(`${o}/${r.toLowerCase()}`).get();return n?{valid:!0,userFriendlyId:`${n.username}/${n.name}`,id:n.id}:{valid:!1,reason:`Actor with name or ID "${r}" was not found`}}if(s.name){let i=await e.actor(`${o}/${s.name}`).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with name "${s.name}" was not found`}}return{valid:!1,reason:"Unable to detect what Actor to create a build for"}}c(Ve,"resolveActorContext");var At=class extends y{static name="create";static description="Creates a new build of the Actor.";static flags={tag:A.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:A.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:A.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:w.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:e,version:t,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await C(),a=await Ve({providedActorNameOrId:i,client:n});if(!a.valid){p({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let l=await n.actor(a.id).get(),u=gr(l.versions,E=>E.buildTag??"latest")[e??"latest"],f=l.versions.find(E=>E.versionNumber===t),d,g=e;if(f){if(e&&(!u||!u.some(E=>E.versionNumber===t))){p({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}d=t,g=f.buildTag??"latest"}else if(u&&(d=u[0].versionNumber,g=e??"latest",u.length>1&&!t)){p({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
60
+ Available versions for this tag: ${u.map(E=>_e.yellow(E.versionNumber)).join(", ")}`,stdout:!0});return}if(!d){p({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let h=await n.actor(a.id).build(d,{tag:e});if(o){L(h);return}let S=[`${_e.yellow("Actor")}: ${l?.username?`${l.username}/`:""}${l?.name??"unknown-actor"} (${_e.gray(h.actId)})`,` ${_e.yellow("Version")}: ${d} (tagged with ${_e.yellow(g)})`,"",`${_e.greenBright("Build Started")} (ID: ${_e.gray(h.id)})`,` ${_e.yellow("Build Number")}: ${h.buildNumber} (will get tagged once finished)`,` ${_e.yellow("Started")}: ${V.display(h.startedAt)}`,""],b=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,T=`${_e.blue("View in Apify Console")}: ${b}`;if(_({message:S.join(`
61
+ `),stdout:!0}),s){try{await $e({job:h,apifyClient:n})}catch(E){p({message:`Failed to print log for build with ID "${h.id}": ${E.message}`,stdout:!0})}_({message:"",stdout:!0})}_({message:T,stdout:!0})}};var kr=class extends At{static name="build"};import bn from"process";import{DownloadItemsFormat as Kc}from"apify-client";import re from"chalk";import{access as Gc,readFile as Yc}from"fs/promises";import Hc,{resolve as wn}from"path";import xe from"process";import Jc from"mime";function An(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Lt(r);s&&(Jc.getExtension(s.contentType)==="json"?(t=JSON.parse(s.body.toString("utf8")),o="application/json"):(t=s.body,o=s.contentType))}return!t||!o?null:{inputToUse:t,contentType:o}}c(An,"resolveInput");async function St(r,e,t){let o,s;if(!e&&!t){let i=ve;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return p({message:"The provided input is invalid. It should be an object, not an array."}),xe.exitCode=5,!1;o=n,s="stdin"}catch(n){return p({message:`Cannot parse JSON input from standard input.
62
+ ${n.message}`}),xe.exitCode=5,!1}}if(e)switch(e[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),xe.exitCode=5,!1;default:{let i=await Gc(wn(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Hc.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return p({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),xe.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),xe.exitCode=5,!1;o=a,s="input"}catch(a){return p({message:`Cannot parse JSON input.
63
+ ${a.message}`}),xe.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),xe.exitCode=5,!1;default:{let i=wn(r,t),n;try{let a=await Yc(i,"utf8"),l=JSON.parse(a);if(Array.isArray(l))return p({message:"The provided input is invalid. It should be an object, not an array."}),xe.exitCode=5,!1;o=l,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),xe.exitCode=5,!1;o=a,s=t}catch{return p({message:`Cannot read input file at path "${i}".
64
+ ${n.message}`}),xe.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}c(St,"getInputOverride");import Ds from"process";import Ur from"chalk";import{ACTOR_JOB_STATUSES as Be}from"@apify/consts";var Sn=[Be.SUCCEEDED,Be.ABORTED,Be.FAILED,Be.TIMED_OUT];async function*bt(r,e){let t=Ds.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:l,waitForRunToFinish:m,printRunLogs:u}=e,f=i==="Actor"?"actor":"task",d=An(t,a);l||(i==="Actor"?ye({message:`Calling ${i} ${o.userFriendlyId} (${Ur.gray(o.id)})
65
+ `}):o.title?ye({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${Ur.gray(o.id)})
66
+ `}):ye({message:`Calling ${i} ${o.userFriendlyId} (${Ur.gray(o.id)})
67
+ `}));let g;try{d&&i==="Actor"?g=await r[f](o.id).start(d.inputToUse,{...s,contentType:d.contentType}):g=await r[f](o.id).start(void 0,s)}catch(h){throw h.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):h}if(yield g,!l&&u)try{await $e({job:g,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
68
+ ${Ur.gray("Timeout for printing logs was hit, there may be future logs.")}
69
+ `):console.error()}catch(h){x({message:"Can not get log:"}),console.error(h)}if(g=await r.run(g.id).get(),m)for(;!Sn.includes(g.status)&&(g=await r.run(g.id).get(),!Sn.includes(g.status));)await new Promise(h=>{setTimeout(h,1e3)});l||(g.status===Be.SUCCEEDED?$({message:`${i} finished.`}):g.status===Be.RUNNING?x({message:`${i} is still running!`}):g.status===Be.ABORTED||g.status===Be.ABORTING?(x({message:`${i} was aborted!`}),Ds.exitCode=3):(p({message:`${i} failed!`}),Ds.exitCode=1)),yield g}c(bt,"runActorOrTaskOnCloud");var vt=c(r=>({build:A.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:A.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:A.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var Ge=class r extends y{static name="call";static description=`Executes Actor remotely using your authenticated account.
70
+ Reads input from local key-value store by default.`;static flags={...vt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({char:"f",description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:A.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":A.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=bn.cwd(),t=Fe(e)||{},o=await C(),s=await F(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){p({message:"You cannot use both the --json and --output-dataset flags when running this command."}),bn.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:l}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),m={waitForFinish:2};this.flags.build&&(m.build=this.flags.build),this.flags.timeout&&(m.timeout=this.flags.timeout),this.flags.memory&&(m.memory=this.flags.memory);let u=await St(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=!1,d,g,h,S=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:m,type:"Actor",inputOverride:u?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let b of S)if(d=b,!f&&(f=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${b.id}`,h=`https://console.apify.com/storage/datasets/${b.defaultDatasetId}`;let T=[`${re.yellow("Started")}: ${V.display(b.startedAt)}`];b.containerUrl&&T.push(`${re.yellow("Container URL")}: ${re.blue(b.containerUrl)}`);let E=d.buildNumber.split(".").slice(0,2).join("."),N=l.versions.find(B=>B.versionNumber===E),P=Object.entries(l.taggedBuilds??{}).find(([,B])=>B.buildNumber===b.buildNumber)?.[0],M=[`${re.yellow("Build")}:`,re.cyan(d.buildNumber)];P?M.push(`(${re.yellow(P)})`):M.push(`(${re.gray("N/A")})`),N&&M.push(`| ${re.gray("Actor version:")} ${re.cyan(N.versionNumber)} (${re.yellow(N.buildTag)})`),T.push(M.join(" ")),T.push(`${re.yellow("Timeout")}: ${d.options.timeoutSecs.toLocaleString("en-US")} seconds`),T.push(`${re.yellow("Memory")}: ${d.options.memoryMbytes} MB`),T.push(`${re.blue("View on Apify Console")}: ${g}`,""),_({message:T.join(`
71
+ `),stdout:!this.flags.json})}if(this.flags.json){L(d);return}if(this.flags.silent||_({message:["",`${re.blue("Export results")}: ${h}`,`${re.blue("View on Apify Console")}: ${g}`].join(`
72
+ `),stdout:!0}),this.flags.outputDataset){let b=d.defaultDatasetId,T,E=4;do{if(T=await o.dataset(b).get(),T?.itemCount)break;await new Promise(P=>{setTimeout(P,250)})}while(E--);let N=await o.dataset(b).downloadItems(Kc.JSON,{clean:!0});console.log(N.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:o,providedActorNameOrId:s}){if(s?.includes("/")){let i=await e.actor(s).get();if(!i)throw new Error(`Cannot find Actor with ID '${s}' in your account.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}if(s){let i=await e.actor(s).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};let n=await e.actor(`${o}/${s.toLowerCase()}`).get();if(n)return{userFriendlyId:`${n.username}/${n.name}`,id:n.id,actorData:n};throw new Error(`Cannot find Actor with name or ID '${s}' in your account.`)}if(t){let i=await e.actor(`${o}/${t}`).get();if(!i)throw new Error(`Cannot find Actor with ID '${o}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}throw new Error("Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.")}};import O from"chalk";import qc from"cli-table3";var Wc={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},zc={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Xc={left:"",right:"",mid:"","bottom-left":"","bottom-mid":"","bottom-right":"",top:"","top-left":"","top-mid":"","top-right":"","left-mid":"","mid-mid":"","right-mid":"",bottom:"",middle:" "};var Zc={[-1]:void 0,0:Wc,1:zc,2:Xc};function Qc(r){return Array.from({length:r},()=>"cyan")}c(Qc,"generateHeaderColors");var eu=process.stdout.columns??100,Mr=Symbol.for("@apify/cli:responsive-table:skip-column"),G=class r{static{c(this,"ResponsiveTable")}options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=r.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,o=Qc(t.length),s=e===0||e===2,i=Zc[e],n=[],a=[],l=[];for(let u of t)this.options.hiddenColumns?.includes(u)||this.rows.some(f=>f[u]===Mr)||(n.push(this.options.columnAlignments?.[u]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[u]?.label??u),l.push(this.options.breakpointOverrides?.small?.[u]?.valueFrom??u)):(a.push(u),l.push(u)));let m=new qc({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let u of this.rows){let f=l.map(d=>u[d]);m.push(f)}return m.toString()}static isSmallTerminal(){return eu<100}};var jr="\u200B",Vr="\u200B\u200B",vn=new G({allColumns:[jr,Vr],mandatoryColumns:[jr,Vr],columnAlignments:{[jr]:"left",[Vr]:"right"}}),Br=class extends y{static name="info";static description="Get information about an Actor.";static flags={readme:A.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:A.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:w.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:t,input:o,json:s}=this.flags,i=await C(),n=await Ve({providedActorNameOrId:e,client:i});if(!n.valid){p({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),l=await i.user(a.userId).get();a.actorMaker=l;for(let d of Object.values(a.taggedBuilds??{})){if(!d.buildId)continue;let g=await i.build(d.buildId).get();d.build=g}if(s){L(a);return}let m=a.taggedBuilds?.latest;if(t){if(!m){p({message:"No README found for this Actor.",stdout:!0});return}if(!m.build?.readme){p({message:"No README found for this Actor.",stdout:!0});return}_({message:m.build.readme,stdout:!0})}if(o){if(!m){p({message:"No input schema found for this Actor.",stdout:!0});return}if(!m.build?.inputSchema){p({message:"No input schema found for this Actor.",stdout:!0});return}_({message:m.build.inputSchema,stdout:!0})}let u=[`Information about Actor ${O.yellow(`${a.username}/${a.name}`)} (${O.gray(a.id)})`,""];a.title&&u.push(`${O.yellow("Title:")} ${O.bold(a.title)}`),a.description&&u.push(`${O.yellow("Description:")} ${a.description}`),u.push(`${O.yellow("Created at:")} ${O.cyan(V.display(a.createdAt))} ${O.gray("|")} ${O.yellow("Updated at:")} ${O.cyan(V.display(a.modifiedAt))}`),a.actorMaker&&(u.push("",`${O.yellow("Made by:")} ${O.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(u[u.length-1]+=` ${O.bgGray("Maintained by Apify")}`)),a.isPublic?u.push("",`${O.yellow("Actor is")} ${O.green("PUBLIC")}`):u.push("",`${O.yellow("Actor is")} ${O.cyan("PRIVATE")}`),a.isDeprecated&&u.push("",`${O.yellow("Actor is")} ${O.red("DEPRECATED")}`);let f=Reflect.get(a,"pricingInfos");if(f?.length){let d=f.at(-1);switch(d.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${d.pricePerUnitUsd}/month + usage`)}`),d.trialMinutes){let g=d.trialMinutes*60*1e3,h=kt.format(g);u.push(` ${O.yellow("Trial duration:")} ${O.bold(h)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=d.pricePerUnitUsd*1e3;u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay per event")}`);let g=Object.values(d.pricingPerEvent?.actorChargeEvents??{});for(let b of g)vn.pushRow({[jr]:b.eventTitle,[Vr]:O.bold(`$${b.eventPriceUsd.toFixed(2)}`)});let S=vn.render(0).split(`
73
73
  `);S.splice(1,1),u.push(S.join(`
74
- `));break}case"FREE":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);break}default:u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`Unknown pricing model (${O.yellow(d.pricingModel)})`)}`)}}else u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(u.push("",O.yellow("SEO information:")),a.seoTitle&&u.push(` ${O.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&u.push(` ${O.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){u.push("",O.yellow("Builds:"));let d=a.taggedBuilds.latest;d&&u.push(` ${O.yellow("-")} ${O.cyan(d.buildNumber)} ${O.gray("/")} ${O.yellow("latest")}`);for(let[g,h]of Object.entries(a.taggedBuilds))g!=="latest"&&u.push(` ${O.yellow("-")} ${O.cyan(h.buildNumber)} ${O.gray("/")} ${O.yellow(g)}`)}R({message:u.join(`
75
- `),stdout:!0})}};import{Time as ru}from"@sapphire/duration";import W from"chalk";import Ne from"chalk";function Te(r){switch(r){case"READY":return Ne.green("Ready");case"RUNNING":return Ne.blue("Running");case"SUCCEEDED":return Ne.green("Succeeded");case"FAILED":return Ne.red("Failed");case"ABORTING":return Ne.yellow("Aborting");case"ABORTED":return Ne.red("Aborted");case"TIMING-OUT":return Ne.yellow("Timing Out");case"TIMED-OUT":return Ne.red("Timed Out");default:return Ne.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}c(Te,"prettyPrintStatus");var ou={"TIMED-OUT":W.gray("after"),"TIMING-OUT":W.gray("after"),ABORTED:W.gray("after"),ABORTING:W.gray("after"),FAILED:W.gray("after"),READY:W.gray("for"),RUNNING:W.gray("for"),SUCCEEDED:W.gray("after")},su=new B({allColumns:["Name","Runs","Last run started at","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run status","Last run duration"],columnAlignments:{Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},hiddenColumns:["_Small_LastRunText"],breakpointOverrides:{small:{"Last run status":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),iu=new B({allColumns:["Name","Modified at","Builds","Default build","Runs","Last run","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run","Last run duration"],hiddenColumns:["_Small_LastRunText"],columnAlignments:{Builds:"right",Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},breakpointOverrides:{small:{"Last run":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Br=class extends y{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static flags={my:A.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:A.integer({description:"Number of Actors that will be skipped.",default:0}),limit:A.integer({description:"Number of Actors that will be listed.",default:20}),desc:A.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,my:s,json:i}=this.flags,n=await C(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){N(a);return}b({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let l={...a,items:await Promise.all(a.items.map(async f=>{let d=await n.actor(f.id).get(),g=await n.actor(f.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...f,actor:d??null,lastRun:g.items[0]??null}}))};if(l.items=s?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),i){N(l);return}let m=s?iu:su,u=l.items.reduce((f,d)=>{let g=`${d.username}/${d.name}`;return g.length>f?g.length:f},0)+2+6;for(let f of l.items){let d=f.stats.lastRunStartedAt?Dt.display(f.stats.lastRunStartedAt):"",g=f.lastRun?(()=>{if(f.lastRun.finishedAt)return se.format(f.lastRun.finishedAt.getTime()-f.lastRun.startedAt.getTime());let I=Date.now()-f.lastRun.startedAt.getTime();return`${se.format(I)}\u2026`})():"",h=f.actor?(()=>{let I=Object.entries(f.actor.taggedBuilds??{}).find(([v,E])=>E.buildNumber===f.actor.defaultRunOptions.build||v===f.actor.defaultRunOptions.build);return I?`${W.yellow(I[0])} / ${W.cyan(I[1].buildNumber??f.actor.defaultRunOptions.build)}`:W.gray("Unknown")})():W.gray("Unknown"),S=(()=>{if(f.lastRun){let v=[Te(f.lastRun.status)];if(g&&v.push(ou[f.lastRun.status],W.cyan(g)),f.lastRun.finishedAt){let E=Date.now()-f.lastRun.finishedAt.getTime();E<ru.Week?v.push(`
76
- `,W.gray(`${se.format(E)} ago`)):v.push(`
77
- `,W.gray("On",Oi.display(f.lastRun.finishedAt)))}return v.join(" ")}return""})();m.pushRow({Name:`${f.title}
78
- ${W.gray(`${f.username}/${f.name}`)}`,Runs:B.isSmallTerminal()&&u>=56?Ur:W.cyan(`${f.stats?.totalRuns??0}`),"Last run started at":d,"Last run":d,"Last run status":f.lastRun?Te(f.lastRun.status):"","Modified at":Dt.display(f.modifiedAt),Builds:f.actor?W.cyan(f.actor.stats.totalBuilds):W.gray("Unknown"),"Last run duration":B.isSmallTerminal()?Ur:W.cyan(g),"Default build":h,_Small_LastRunText:S})}R({message:m.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((t,o)=>{let s=new Date(t.modifiedAt);return new Date(o.modifiedAt).getTime()-s.getTime()})}sortByLastRun(e){return e.sort((t,o)=>{let s=new Date(t.stats?.lastRunStartedAt??"1970-01-01T00:00Z");return new Date(o.stats?.lastRunStartedAt??"1970-01-01T00:00Z").getTime()-s.getTime()})}};import{mkdirSync as Rn,readdirSync as bu,writeFileSync as xn}from"fs";import{dirname as vu,join as Tu}from"path";import On from"process";import Iu from"adm-zip";import Cu from"axios";import Nn from"jju";import{gt as Eu}from"semver";import $u from"tiged";import{mkdir as mu,rename as _n,writeFile as du}from"fs/promises";import{dirname as pu,join as fu}from"path";import $n from"process";import{inspect as gu}from"util";import{err as Jt,ok as Yr}from"@sapphire/result";import{createPrompt as nu,isEnterKey as au,makeTheme as lu,useKeypress as cu,usePrefix as uu,useState as In}from"@inquirer/core";function Fs(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}c(Fs,"getBooleanValue");function Cn(r){return r?"Yes":"No"}c(Cn,"boolToString");var En=nu((r,e)=>{let t=Cn,[o,s]=In("idle"),[i,n]=In(""),a=lu(),l=uu({status:o,theme:a});cu((d,g)=>{if(au(d)){let h=Fs(i,r.default);n(t(h)),s("done"),e(h);return}if(d.name==="tab"){let h=Cn(!Fs(i,r.default));g.clearLine(0),g.write(h),n(h);return}if(d.name==="y"||d.name==="n"){let h=Fs(d.name,r.default);n(t(h)),s("done"),e(h);return}g.clearLine(0),g.write(i),n(g.line)});let m=i,u="";o==="done"?m=a.style.answer(i):u=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let f=a.style.message(r.message,o);return`${l} ${f}${u} ${m}`});var z=$e(async({message:r,default:e})=>await En({message:r,default:e}));var hu=c(r=>fu(r,ir),"getDeprecatedLocalConfigPath"),Gr=new Map;async function Ye({cwd:r=$n.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:$n.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=Gr.get(r);if(o)return T("useActorConfig",{cacheHit:!0,config:o}),Yr(o);let s=As(r),i=hu(r),n,a;try{n=Ce(s)}catch(m){return Jt({message:`Failed to read local config at path: '${s}':`,cause:m,exists:!1,config:{}})}try{a=Ce(i)}catch(m){return Jt({message:`Failed to read local config at path: '${i}':`,cause:m,exists:!1,config:{}})}if(n&&a&&t&&await yu(i),!n&&!a)return Gr.set(r,{exists:!1,migrated:!1,config:{}}),Yr({exists:!1,migrated:!1,config:{}});let l=!1;if(!n&&a&&e){let m=await Au(a,i,s);if(m.isErr())return Jt(m.unwrapErr());n=m.unwrap(),l=!0}return Gr.set(r,{exists:!0,migrated:l,config:n||a||{}}),T("useActorConfig",{cacheHit:!1,config:Gr.get(r)}),Yr({exists:!0,migrated:l,config:n||a||{}})}c(Ye,"useActorConfig");async function yu(r){if(!await z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?'})){x({message:'The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.'});return}try{await _n(r,`${r}.deprecated`),b({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(t){t instanceof Error?p({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
74
+ `));break}case"FREE":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);break}default:u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`Unknown pricing model (${O.yellow(d.pricingModel)})`)}`)}}else u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(u.push("",O.yellow("SEO information:")),a.seoTitle&&u.push(` ${O.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&u.push(` ${O.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){u.push("",O.yellow("Builds:"));let d=a.taggedBuilds.latest;d&&u.push(` ${O.yellow("-")} ${O.cyan(d.buildNumber)} ${O.gray("/")} ${O.yellow("latest")}`);for(let[g,h]of Object.entries(a.taggedBuilds))g!=="latest"&&u.push(` ${O.yellow("-")} ${O.cyan(h.buildNumber)} ${O.gray("/")} ${O.yellow(g)}`)}_({message:u.join(`
75
+ `),stdout:!0})}};import{Time as tu}from"@sapphire/duration";import W from"chalk";import Pe from"chalk";function Ie(r){switch(r){case"READY":return Pe.green("Ready");case"RUNNING":return Pe.blue("Running");case"SUCCEEDED":return Pe.green("Succeeded");case"FAILED":return Pe.red("Failed");case"ABORTING":return Pe.yellow("Aborting");case"ABORTED":return Pe.red("Aborted");case"TIMING-OUT":return Pe.yellow("Timing Out");case"TIMED-OUT":return Pe.red("Timed Out");default:return Pe.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}c(Ie,"prettyPrintStatus");var ru={"TIMED-OUT":W.gray("after"),"TIMING-OUT":W.gray("after"),ABORTED:W.gray("after"),ABORTING:W.gray("after"),FAILED:W.gray("after"),READY:W.gray("for"),RUNNING:W.gray("for"),SUCCEEDED:W.gray("after")},ou=new G({allColumns:["Name","Runs","Last run started at","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run status","Last run duration"],columnAlignments:{Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},hiddenColumns:["_Small_LastRunText"],breakpointOverrides:{small:{"Last run status":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),su=new G({allColumns:["Name","Modified at","Builds","Default build","Runs","Last run","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run","Last run duration"],hiddenColumns:["_Small_LastRunText"],columnAlignments:{Builds:"right",Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},breakpointOverrides:{small:{"Last run":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Gr=class extends y{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static flags={my:A.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:A.integer({description:"Number of Actors that will be skipped.",default:0}),limit:A.integer({description:"Number of Actors that will be listed.",default:20}),desc:A.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,my:s,json:i}=this.flags,n=await C(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){L(a);return}v({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let l={...a,items:await Promise.all(a.items.map(async f=>{let d=await n.actor(f.id).get(),g=await n.actor(f.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...f,actor:d??null,lastRun:g.items[0]??null}}))};if(l.items=s?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),i){L(l);return}let m=s?su:ou,u=l.items.reduce((f,d)=>{let g=`${d.username}/${d.name}`;return g.length>f?g.length:f},0)+2+6;for(let f of l.items){let d=f.stats.lastRunStartedAt?Ft.display(f.stats.lastRunStartedAt):"",g=f.lastRun?(()=>{if(f.lastRun.finishedAt)return se.format(f.lastRun.finishedAt.getTime()-f.lastRun.startedAt.getTime());let b=Date.now()-f.lastRun.startedAt.getTime();return`${se.format(b)}\u2026`})():"",h=f.actor?(()=>{let b=Object.entries(f.actor.taggedBuilds??{}).find(([T,E])=>E.buildNumber===f.actor.defaultRunOptions.build||T===f.actor.defaultRunOptions.build);return b?`${W.yellow(b[0])} / ${W.cyan(b[1].buildNumber??f.actor.defaultRunOptions.build)}`:W.gray("Unknown")})():W.gray("Unknown"),S=(()=>{if(f.lastRun){let T=[Ie(f.lastRun.status)];if(g&&T.push(ru[f.lastRun.status],W.cyan(g)),f.lastRun.finishedAt){let E=Date.now()-f.lastRun.finishedAt.getTime();E<tu.Week?T.push(`
76
+ `,W.gray(`${se.format(E)} ago`)):T.push(`
77
+ `,W.gray("On",Oi.display(f.lastRun.finishedAt)))}return T.join(" ")}return""})();m.pushRow({Name:`${f.title}
78
+ ${W.gray(`${f.username}/${f.name}`)}`,Runs:G.isSmallTerminal()&&u>=56?Mr:W.cyan(`${f.stats?.totalRuns??0}`),"Last run started at":d,"Last run":d,"Last run status":f.lastRun?Ie(f.lastRun.status):"","Modified at":Ft.display(f.modifiedAt),Builds:f.actor?W.cyan(f.actor.stats.totalBuilds):W.gray("Unknown"),"Last run duration":G.isSmallTerminal()?Mr:W.cyan(g),"Default build":h,_Small_LastRunText:S})}_({message:m.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((t,o)=>{let s=new Date(t.modifiedAt);return new Date(o.modifiedAt).getTime()-s.getTime()})}sortByLastRun(e){return e.sort((t,o)=>{let s=new Date(t.stats?.lastRunStartedAt??"1970-01-01T00:00Z");return new Date(o.stats?.lastRunStartedAt??"1970-01-01T00:00Z").getTime()-s.getTime()})}};import{mkdirSync as Rn,readdirSync as Su,writeFileSync as _n}from"fs";import{dirname as bu,join as vu}from"path";import xn from"process";import Tu from"adm-zip";import Iu from"axios";import On from"jju";import{gt as Cu}from"semver";import Eu from"tiged";import{mkdir as uu,rename as $n,writeFile as mu}from"fs/promises";import{dirname as du,join as pu}from"path";import En from"process";import{inspect as fu}from"util";import{err as Kt,ok as Hr}from"@sapphire/result";import{createPrompt as iu,isEnterKey as nu,makeTheme as au,useKeypress as lu,usePrefix as cu,useState as Tn}from"@inquirer/core";function Fs(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}c(Fs,"getBooleanValue");function In(r){return r?"Yes":"No"}c(In,"boolToString");var Cn=iu((r,e)=>{let t=In,[o,s]=Tn("idle"),[i,n]=Tn(""),a=au(),l=cu({status:o,theme:a});lu((d,g)=>{if(nu(d)){let h=Fs(i,r.default);n(t(h)),s("done"),e(h);return}if(d.name==="tab"){let h=In(!Fs(i,r.default));g.clearLine(0),g.write(h),n(h);return}if(d.name==="y"||d.name==="n"){let h=Fs(d.name,r.default);n(t(h)),s("done"),e(h);return}g.clearLine(0),g.write(i),n(g.line)});let m=i,u="";o==="done"?m=a.style.answer(i):u=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let f=a.style.message(r.message,o);return`${l} ${f}${u} ${m}`});var z=Re(async({message:r,default:e})=>await Cn({message:r,default:e}));var gu=c(r=>pu(r,nr),"getDeprecatedLocalConfigPath"),Yr=new Map;async function Ye({cwd:r=En.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:En.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=Yr.get(r);if(o)return I("useActorConfig",{cacheHit:!0,config:o}),Hr(o);let s=As(r),i=gu(r),n,a;try{n=Ee(s)}catch(m){return Kt({message:`Failed to read local config at path: '${s}':`,cause:m,exists:!1,config:{}})}try{a=Ee(i)}catch(m){return Kt({message:`Failed to read local config at path: '${i}':`,cause:m,exists:!1,config:{}})}if(n&&a&&t&&await hu(i),!n&&!a)return Yr.set(r,{exists:!1,migrated:!1,config:{}}),Hr({exists:!1,migrated:!1,config:{}});let l=!1;if(!n&&a&&e){let m=await wu(a,i,s);if(m.isErr())return Kt(m.unwrapErr());n=m.unwrap(),l=!0}return Yr.set(r,{exists:!0,migrated:l,config:n||a||{}}),I("useActorConfig",{cacheHit:!1,config:Yr.get(r)}),Hr({exists:!0,migrated:l,config:n||a||{}})}c(Ye,"useActorConfig");async function hu(r){if(!await z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?'})){x({message:'The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.'});return}try{await $n(r,`${r}.deprecated`),v({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(t){t instanceof Error?p({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
79
79
  ${t.message||t}`}):p({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
80
- ${gu(t,{showHidden:!1})}`})}}c(yu,"handleBothConfigVersionsFound");var wu=["name","version","buildTag"];async function Au(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=Su(o)),o={actorSpecification:ms,environmentVariables:r?.env||void 0,...wu.reduce((i,n)=>(i[n]=r[n],i),{})},!await z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?'}))return Jt({message:'Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.',exists:!0,config:o});try{await mu(pu(t),{recursive:!0}),await du(t,JSON.stringify(o,null," "))}catch(i){let n=i;return Jt({message:`Failed to write the new "actor.json" file to path: '${t}'.
81
- ${n.message||n}`,exists:!0,config:o})}try{await _n(e,`${e}.deprecated`)}catch(i){let n=i;x({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
82
- ${n.message||n}`})}return b({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),Yr(o)}c(Au,"handleMigrationFlow");function Su(r){let e={name:r.name,template:r.template,version:r.version.versionNumber,buildTag:r.version.buildTag,env:null};if(r.version.envVars?.length){let t={};r.version.envVars.forEach(o=>{o.name&&o.value&&(t[o.name]=o.value)}),e.env=t}return e}c(Su,"updateLocalConfigStructure");var Pn=c(async(r,e)=>{let{data:t}=await Cu.get(r,{responseType:"arraybuffer"}),o=new Iu(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),Tt=class extends y{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static flags={version:A.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version",required:!1}),dir:A.string({description:"Directory where the Actor should be pulled to",required:!1})};static args={actorId:w.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=On.cwd(),t=await Ye({cwd:e});if(t.isErr()){p({message:t.unwrapErr().message}),On.exitCode=5;return}let{config:o}=t.unwrap(),s=await D(),i=await C(),n=!this.args.actorId,a=s.username||s.id,l=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!l)throw new Error("Cannot find Actor in this directory.");let m;try{m=await i.actor(l).get()}catch{throw new Error(`Cannot find Actor with ID/name '${l}' in your account.`)}if(!m)throw new Error(`Cannot find Actor with ID/name '${l}' in your account.`);let{name:u,versions:f}=m;if(m.isSourceCodeHidden&&!m.versions.length)throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.");let d=null;if(this.flags.version&&(d=f.find(h=>h.versionNumber===this.flags.version),!d))throw new Error(`Cannot find version ${this.flags.version} of Actor ${l}.`);d||(d=f.reduce((h,S)=>Eu(`${S.versionNumber}.0`,`${h.versionNumber}.0`)?S:h));let g=n?e:Tu(e,this.flags.dir??u);if(Rn(g,{recursive:!0}),!n&&bu(g).length!==0){p({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}switch(d.sourceType){case"TARBALL":{await Pn(d.tarballUrl,g);break}case"SOURCE_FILES":{let{sourceFiles:h}=d;for(let S of h){let I=vu(S.name);if(Rn(`${g}/${I}`,{recursive:!0}),!S.folder){let v=S.format==="BASE64"?Buffer.from(S.content,"base64").toString():S.content;if(S.name===j){let E=Nn.parse(v);E.name=m.name,xn(`${g}/${S.name}`,Nn.update(v,E))}else xn(`${g}/${S.name}`,v)}}break}case"GIT_REPO":{let{gitRepoUrl:h}=d,[S,I]=h.split("#"),v,E;I&&([v,E]=I.split(":"));let P=S;E&&(P+=`/${E}`),v&&(P+=`#${v}`);let L=$u(P);try{await L.clone(g)}catch(M){throw new Error(`Failed to pull Actor from ${h}. ${M.message}`)}break}case"GITHUB_GIST":{await Pn(`${d.gitHubGistUrl}/archive/master.zip`,g);break}default:throw new Error(`Unknown source type: ${d.sourceType}`)}$({message:n?`Actor ${u} updated at ${g}/`:`Pulled to ${g}/`})}};import{readFileSync as xu,statSync as Ou,unlinkSync as Nu}from"fs";import{join as Pu,resolve as Lu}from"path";import nt from"process";import Du from"open";import{fetchManifest as Fu}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as at,ACTOR_SOURCE_TYPES as Us,MAX_MULTIFILE_BYTES as Bn}from"@apify/consts";import{readFileSync as _u,writeFileSync as Ru}from"fs";var ks="@",Ln=100,Dn=5e4,Hr=c(()=>{try{return JSON.parse(_u(rr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Fn=c(r=>(Ss(rr()),Ru(rr(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),kn=c((r,e)=>{let t=Hr();if(t[r])throw new Error(`Secret with name ${r} already exists. Call "apify secrets rm ${r}" to remove it.`);if(typeof r!="string"||r.length>Ln)throw new Error(`Secret name has to be string with maximum length ${Ln}.`);if(typeof e!="string"||e.length>Dn)throw new Error(`Secret value has to be string with maximum length ${Dn}.`);return t[r]=e,Fn(t)},"addSecret"),Un=c(r=>{let e=Hr();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Fn(e)},"removeSecret"),Mn=c(r=>new RegExp(`^${ks}.{1}`).test(r),"isSecretKey"),jn=c((r,e)=>{e=e||Hr();let t={};return Object.keys(r).forEach(o=>{if(Mn(r[o])){let s=r[o].replace(new RegExp(`^${ks}`),"");e[s]?t[o]=e[s]:x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t[o]=r[o]}),t},"replaceSecretsValue"),Vn=c((r,e)=>{e=e||Hr();let t=[];return Object.keys(r).forEach(o=>{if(Mn(r[o])){let s=r[o].replace(new RegExp(`^${ks}`),"");e[s]?t.push({name:o,value:e[s],isSecret:!0}):x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t.push({name:o,value:r[o]})}),t},"transformEnvToEnvVars");var Ms="temp_file.zip",ku={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Gn="0.0",Uu="latest",It=class extends y{static name="push";static description=`Deploys Actor to Apify platform using settings from '${j}'.
83
- Files under '${Bn/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
84
- Use --force to override newer remote versions.`;static flags={version:A.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${j}' file.`,required:!1}),"build-tag":A.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${j}' file`,required:!1}),"wait-for-finish":A.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:A.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:A.boolean({description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:A.string({description:"Directory where the Actor is located",required:!1})};static args={actorId:w.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 '${j}' file.`})};async run(){let e=Lu(nt.cwd(),this.flags.dir??"."),t=await Ii(e);if(!t.length){p({message:"You need to call this command from a folder that has an Actor in it!"}),nt.exitCode=4;return}if(![ir,"actor.json",".actor/actor.json",".actor"].some(F=>t.some(te=>te===F||te.startsWith(F)))){p({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(`
85
- `)}),nt.exitCode=4;return}let o=await C(),s=await Ye({cwd:e});if(s.isErr()){p({message:s.unwrapErr().message}),nt.exitCode=5;return}let{config:i}=s.unwrap(),n=await D(),l=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",m,u,f=!1,d=this.flags.version||i?.version||Gn,g=this.flags.buildTag||i?.buildTag;!g&&d===Gn&&(g=Uu);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,S=this.args.actorId;if(S){if(u=await o.actor(S).get(),!u)throw new Error(`Cannot find Actor with ID '${S}' in your account.`);m=u.id}else{let F=n.username||n.id;if(u=await o.actor(`${F}/${i.name}`).get(),u)m=u.id;else{let{templates:te}=await Fu(),De=te.find(er=>er.name===i.template)?.defaultRunOptions||ku,ls={name:i.name,defaultRunOptions:De,versions:[{versionNumber:d,buildTag:g,sourceType:Us.SOURCE_FILES,sourceFiles:[]}]};u=await o.actors().create(ls),m=u.id,f=!0,b({message:`Created Actor with name ${i.name} on Apify.`})}}b({message:`Deploying Actor '${i.name}' to Apify.`});let I=await di(t,e),v=o.actor(m),E,P,L;if(I<Bn){let F=await v.get();if(!f){let te=t.reduce((De,ls)=>{let{mtimeMs:er,ctimeMs:ri}=Ou(Pu(e,ls)),oi=er>ri?er:ri;return De>oi?De:oi},0),ge=F?.modifiedAt.valueOf();if(!this.flags.force&&ge&&te<ge&&(i?.name||S))throw new Error(`Actor with identifier "${i?.name||S}" is already on the platform and was modified there since modified locally.
86
- Skipping push. Use --force to override.`)}P=await Ti(t,e),E=Us.SOURCE_FILES}else{he({message:"Zipping Actor files"}),await Ci(Ms,t,e);let F=await o.keyValueStores().getOrCreate(`actor-${m}-source`),te=`version-${d}.zip`,ge=xu(Ms);await o.keyValueStore(F.id).setRecord({key:te,value:ge,contentType:"application/zip"}),Nu(Ms),L=`${o.baseUrl}/key-value-stores/${F.id}/records/${te}?disableRedirect=true`,E=Us.TARBALL}let M=await v.version(d).get(),Y=i.environmentVariables?Vn(i.environmentVariables):void 0;if(M){let F={tarballUrl:L,sourceFiles:P,buildTag:g,sourceType:E,envVars:Y};await v.version(d).update(F),he({message:`Updated version ${d} for Actor ${u.name}.`})}else{let F={versionNumber:d,tarballUrl:L,sourceFiles:P,buildTag:g,sourceType:E,envVars:Y};await v.versions().create({...F}),he({message:`Created version ${d} for Actor ${u.name}.`})}he({message:`Building Actor ${u.name}`});let J=await v.build(d,{useCache:!0,waitForFinish:2});try{await Ee({job:J,timeoutMillis:h,apifyClient:o})}catch(F){x({message:"Can not get log:"}),console.error(F)}J=await o.build(J.id).get(),cs({message:"Actor build detail",url:`https://console.apify.com${l}/actors/${J.actId}#/builds/${J.buildNumber}`}),cs({message:"Actor detail",url:`https://console.apify.com${l}/actors/${J.actId}`}),this.flags.open&&await Du(`https://console.apify.com${l}/actors/${J.actId}`),J.status===at.SUCCEEDED?$({message:"Actor was deployed to Apify cloud and built there."}):J.status===at.READY?x({message:"Build is waiting for allocation."}):J.status===at.RUNNING?x({message:"Build is still running."}):J.status===at.ABORTED||J.status===at.ABORTING?(x({message:"Build was aborted!"}),nt.exitCode=3):J.status===at.TIMED_OUT||J.status===at.TIMING_OUT?(x({message:"Build timed out!"}),nt.exitCode=2):(p({message:"Build failed!"}),nt.exitCode=1)}};var Jr=class extends y{static name="rm";static description="Permanently removes an Actor from your account.";static args={actorId:w.string({description:"The Actor ID to delete.",required:!0})};async run(){let{actorId:e}=this.args,t=await C();if(!await t.actor(e).get()){p({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await z({message:"Are you sure you want to delete this Actor?"})){b({message:`Deletion of Actor "${e}" was canceled.`});return}try{await t.actor(e).delete(),$({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete Actor "${e}".
87
- ${n.message||n}`})}}};import Q from"chalk";var Kr=class extends y{static name="start";static description=`Starts Actor remotely and returns run details immediately.
88
- Uses authenticated account and local key-value store for input.`;static flags={...vt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=process.cwd(),t=Fe(e)||{},o=await C(),s=await D(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:l}=await Ge.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),m={};this.flags.build&&(m.build=this.flags.build),this.flags.timeout&&(m.timeout=this.flags.timeout),this.flags.memory&&(m.memory=this.flags.memory);let u=await St(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:m,type:"Actor",inputOverride:u?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),d;for await(let L of f)d=L;if(this.flags.json){N(d);return}let g=`https://console.apify.com/actors/${n}/runs/${d.id}`,h=`https://console.apify.com/storage/datasets/${d.defaultDatasetId}`,S=[`${Q.gray("Run:")} Calling Actor ${a} (${Q.gray(n)})`,"",`${Q.yellow("Started")}: ${V.display(d.startedAt)}`];d.containerUrl&&S.push(`${Q.yellow("Container URL")}: ${Q.blue(d.containerUrl)}`);let I=d.buildNumber.split(".").slice(0,2).join("."),v=l.versions.find(L=>L.versionNumber===I),E=Object.entries(l.taggedBuilds??{}).find(([,L])=>L.buildNumber===d.buildNumber)?.[0],P=[`${Q.yellow("Build")}:`,Q.cyan(d.buildNumber)];E?P.push(`(${Q.yellow(E)})`):P.push(`(${Q.gray("N/A")})`),v&&P.push(`| ${Q.gray("Actor version:")} ${Q.cyan(v.versionNumber)} (${Q.yellow(v.buildTag)})`),S.push(P.join(" ")),S.push(`${Q.yellow("Timeout")}: ${d.options.timeoutSecs.toLocaleString("en-US")} seconds`),S.push(`${Q.yellow("Memory")}: ${d.options.memoryMbytes} MB`),S.push("",`${Q.blue("Export results")}: ${h}`,`${Q.blue("View on Apify Console")}: ${g}`),R({message:S.join(`
89
- `),stdout:!0})}};var qr=class extends y{static name="actors";static description="Manages Actor creation, deployment, and execution on the Apify platform.";static subcommands=[Kr,Jr,It,Tt,Br,Vr,Ge,Fr];async run(){this.printHelp()}};import Z from"chalk";var Mu=c(r=>r,"noColor");function X({bytes:r,shortBytes:e=!1,colorFunc:t=Mu,precision:o=2}){let s=[e?"B":"Bytes","KB","MB","GB","TB"];if(r===0)return e?`${0 .toPrecision(o)} B`:`${0 .toPrecision(o)} Byte`;let i=Math.floor(Math.log(r)/Math.log(1e3));return`${(r/1e3**i).toFixed(o)} ${t(s[i])}`}c(X,"prettyPrintBytes");var Wr=class extends y{static name="info";static description="Prints information about a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){N(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[g,h]of Object.entries(s.taggedBuilds))if(h.buildId===o.id){i=g;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",l=i?` (tagged as ${Z.yellow(i)})`:"",m=typeof n<"u"?` (exit code: ${Z.gray(n)})`:"",u=[`${Z.yellow("Actor")}: ${a} (${Z.gray(o.actId)})`,"",`${Z.yellow("Build Information")} (ID: ${Z.gray(o.id)})`,` ${Z.yellow("Build Number")}: ${o.buildNumber}${l}`,` ${Z.yellow("Status")}: ${Te(o.status)}${m}`,` ${Z.yellow("Started")}: ${V.display(o.startedAt)}`];if(o.finishedAt)u.push(` ${Z.yellow("Finished")}: ${V.display(o.finishedAt)} (took ${Z.gray(Ft.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();u.push(` ${Z.yellow("Finished")}: ${Z.gray(`Running for ${Ft.format(g)}`)}`)}o.stats?.computeUnits&&u.push(` ${Z.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let f=Reflect.get(o.stats??{},"imageSizeBytes");f&&u.push(` ${Z.yellow("Docker Image Size")}: ${X({bytes:f})}`),u.push(` ${Z.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),u.push("");let d=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;u.push(`${Z.blue("View in Apify Console")}: ${d}`),R({message:u.join(`
90
- `),stdout:!0})}};var zr=class extends y{static name="log";static description="Prints the log of a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for build with ID "${e}":
91
- `});try{await Ee({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import me from"chalk";var ju=c(()=>new B({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Xr=class extends y{static name="ls";static description="Lists all builds of the Actor.";static flags={offset:A.integer({description:"Number of builds that will be skipped.",default:0}),limit:A.integer({description:"Number of builds that will be listed.",default:10}),desc:A.boolean({description:"Sort builds in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),l=await Ve({providedActorNameOrId:n,client:a});if(!l.valid){p({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let m=await a.actor(l.id).builds().list({desc:e,limit:t,offset:o}),u=await a.actor(l.id).get(),f=fr(m.items,h=>{let S=Reflect.get(h,"buildNumber"),[I,v]=S.split(".");return`${I}.${v}`}),d=Object.entries(u.taggedBuilds??{}).reduce((h,[S,I])=>(h[I.buildNumber]=S,h),{});if(i){for(let h of m.items){let S=Reflect.get(h,"buildNumber"),I=d[S];I&&Reflect.set(h,"buildTag",I)}N(m);return}R({message:`${me.reset("Showing")} ${me.yellow(m.items.length)} out of ${me.yellow(m.total)} builds for Actor ${me.yellow(l.userFriendlyId)} (${me.gray(l.id)})
92
- `,stdout:!0});let g=Object.entries(f).sort((h,S)=>h[0].localeCompare(S[0]));for(let[h,S]of g){if(!S?.length){R({message:`No builds for version ${h}`,stdout:!0});continue}let I=u.versions.find(L=>L.versionNumber===h)?.buildTag,v=this.generateTableForActorVersion({buildsForVersion:S,buildTagToActorVersion:d}),E=I?` (latest build gets tagged with ${me.yellow(I)})`:"",P=[me.reset(`Builds for Actor Version ${me.yellow(h)}${E}`),v.render(s?0:-1),""];R({message:P.join(`
93
- `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=ju();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${me.yellow(t[i])})`:"",a;if(s.finishedAt){let l=s.finishedAt.getTime()-s.startedAt.getTime();a=me.gray(`${se.format(l,void 0,{left:""})}`)}else{let l=Date.now()-s.startedAt.getTime();a=me.gray(`Running for ${se.format(l,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:me.gray(s.id),Status:Te(s.status),Took:a})}return o}};import Vu from"@inquirer/input";var Yn=$e(async({message:r,expectedValue:e,failureMessage:t})=>await Vu({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Zr=class extends y{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static args={buildId:w.string({description:"The build ID to delete.",required:!0})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[a,l]of Object.entries(s.taggedBuilds))if(e===l.buildId){i=a;break}}if(!await(i?Yn:z)({message:`Are you sure you want to delete this Actor Build?${i?` If so, please type in "${i}":`:""}`,expectedValue:i??"",failureMessage:"Your provided value does not match the build tag."})){b({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await t.build(e).delete(),$({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete build "${e}".
94
- ${l.message||l}`,stdout:!0})}}};var Qr=class extends y{static name="builds";static description="Manages Actor build processes and versioning.";static subcommands=[Zr,Xr,zr,Wr,At];async run(){this.printHelp()}};var eo=class extends Ge{static name="call"};import Bu from"assert";import{existsSync as to}from"fs";import{mkdir as Gu,readFile as Yu,symlink as Hu,unlink as Ju,writeFile as Hn}from"fs/promises";import{basename as Ku,join as de}from"path";import He from"chalk";var qu=c(r=>de(r,".install-marker"),"pathToInstallMarker"),js=c(r=>r.startsWith(process.env.HOME)?r.replace(process.env.HOME,"~"):r,"tildify"),Kt=class extends y{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:t,version:o}=K();if(e!=="bundle"){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}Bu(t,"When CLI is installed via bundles, the install path must be set");let s=qu(t);if(to(s)){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}await this.symlinkToLocalBin(t),await this.promptAddToShell(),await Hn(s,o),T("[install] install marker written to",s),R({message:""}),$({message:"To get started, run:"}),R({message:He.white.bold(` apify --help
95
- actor --help`)})}async symlinkToLocalBin(e){let t=process.env.HOME;if(T("[install] user home directory",t),!t){T("[install] user home directory not found"),x({message:He.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=de(t,".local","bin");to(o)||await Gu(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=de(e,i);if(!to(n)){T("[install] file not found for symlinking",i,n),x({message:He.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=de(o,i);await Ju(a).catch(()=>{}),await Hu(n,a),T("[install] symlink created for item",i,a)}b({message:He.gray(`Symlinked apify, actor, and apify-cli to ${o}`)})}async promptAddToShell(){let e=process.env.PROVIDED_INSTALL_DIR;if(!e){x({message:He.gray("Install directory not found, cannot add to shell")});return}let t=process.env.FINAL_BIN_DIR;R({message:""});let o=await z({message:"Should the CLI handle adding itself to your shell automatically? (If you say no, you will receive the lines to add to your shell config file)",providedConfirmFromStdin:!1}),s=Ku(process.env.SHELL??"sh"),i=`"${e.replaceAll('"','\\"')}"`,n=[],a="";switch(s){case"bash":{n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');let l=[de(process.env.HOME,".bashrc"),de(process.env.HOME,".bash_profile")];process.env.XDG_CONFIG_HOME&&l.push(de(process.env.XDG_CONFIG_HOME,".bashrc"),de(process.env.XDG_CONFIG_HOME,".bash_profile"),de(process.env.XDG_CONFIG_HOME,"bashrc"),de(process.env.XDG_CONFIG_HOME,"bash_profile"));for(let m of l)if(to(m)){a=m;break}break}case"zsh":n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a=de(process.env.HOME,".zshrc");break;case"fish":{n.push(`set --export APIFY_CLI_INSTALL ${i}`),n.push(`set --export PATH ${t} $PATH`),a=de(process.env.HOME,".config","fish","config.fish");break}default:n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a="~/.bashrc";break}if(R({message:""}),o&&a){let m=`${await Yu(a,"utf-8")}
80
+ ${fu(t,{showHidden:!1})}`})}}c(hu,"handleBothConfigVersionsFound");var yu=["name","version","buildTag"];async function wu(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=Au(o)),o={actorSpecification:ms,environmentVariables:r?.env||void 0,...yu.reduce((i,n)=>(i[n]=r[n],i),{})},!await z({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?'}))return Kt({message:'Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.',exists:!0,config:o});try{await uu(du(t),{recursive:!0}),await mu(t,JSON.stringify(o,null," "))}catch(i){let n=i;return Kt({message:`Failed to write the new "actor.json" file to path: '${t}'.
81
+ ${n.message||n}`,exists:!0,config:o})}try{await $n(e,`${e}.deprecated`)}catch(i){let n=i;x({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
82
+ ${n.message||n}`})}return v({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),Hr(o)}c(wu,"handleMigrationFlow");function Au(r){let e={name:r.name,template:r.template,version:r.version.versionNumber,buildTag:r.version.buildTag,env:null};if(r.version.envVars?.length){let t={};r.version.envVars.forEach(o=>{o.name&&o.value&&(t[o.name]=o.value)}),e.env=t}return e}c(Au,"updateLocalConfigStructure");var Nn=c(async(r,e)=>{let{data:t}=await Iu.get(r,{responseType:"arraybuffer"}),o=new Tu(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),Tt=class extends y{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static flags={version:A.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version",required:!1}),dir:A.string({description:"Directory where the Actor should be pulled to",required:!1})};static args={actorId:w.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=xn.cwd(),t=await Ye({cwd:e});if(t.isErr()){p({message:t.unwrapErr().message}),xn.exitCode=5;return}let{config:o}=t.unwrap(),s=await F(),i=await C(),n=!this.args.actorId,a=s.username||s.id,l=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!l)throw new Error("Cannot find Actor in this directory.");let m;try{m=await i.actor(l).get()}catch{throw new Error(`Cannot find Actor with ID/name '${l}' in your account.`)}if(!m)throw new Error(`Cannot find Actor with ID/name '${l}' in your account.`);let{name:u,versions:f}=m,d=c(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!m.versions.length)throw new Error(`Actor ${l} has no versions.`);let g=null;if(this.flags.version&&(g=f.find(S=>S.versionNumber===this.flags.version),!g))throw new Error(`Cannot find version ${this.flags.version} of Actor ${l}.`);g||(g=f.reduce((S,b)=>Cu(`${b.versionNumber}.0`,`${S.versionNumber}.0`)?b:S));let h=n?e:vu(e,this.flags.dir??u);if(Rn(h,{recursive:!0}),!n&&Su(h).length!==0){p({message:`Directory ${h} is not empty. Please empty it or choose another directory.`});return}switch(g.sourceType){case"TARBALL":{g.tarballUrl||d(),await Nn(g.tarballUrl,h);break}case"SOURCE_FILES":{g.sourceFiles||d();let{sourceFiles:S}=g;for(let b of S){let T=bu(b.name);if(Rn(`${h}/${T}`,{recursive:!0}),!b.folder){let E=b.format==="BASE64"?Buffer.from(b.content,"base64").toString():b.content;if(b.name===j){let N=On.parse(E);N.name=m.name,_n(`${h}/${b.name}`,On.update(E,N))}else _n(`${h}/${b.name}`,E)}}break}case"GIT_REPO":{g.gitRepoUrl||d();let{gitRepoUrl:S}=g,[b,T]=S.split("#"),E,N;T&&([E,N]=T.split(":"));let P=b;N&&(P+=`/${N}`),E&&(P+=`#${E}`);let M=Eu(P);try{await M.clone(h)}catch(B){throw new Error(`Failed to pull Actor from ${S}. ${B.message}`)}break}case"GITHUB_GIST":{g.gitHubGistUrl||d(),await Nn(`${g.gitHubGistUrl}/archive/master.zip`,h);break}default:throw new Error(`Unknown source type: ${g.sourceType}`)}$({message:n?`Actor ${u} updated at ${h}/`:`Pulled to ${h}/`})}};import{readFileSync as _u,statSync as xu,unlinkSync as Ou}from"fs";import{join as Nu,resolve as Pu}from"path";import nt from"process";import Lu from"open";import{fetchManifest as Du}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as at,ACTOR_SOURCE_TYPES as Us,MAX_MULTIFILE_BYTES as Vn}from"@apify/consts";import{createHmacSignature as Fu}from"@apify/utilities";import{readFileSync as $u,writeFileSync as Ru}from"fs";var ks="@",Pn=100,Ln=5e4,Jr=c(()=>{try{return JSON.parse($u(or(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Dn=c(r=>(Ss(or()),Ru(or(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),Fn=c((r,e)=>{let t=Jr();if(t[r])throw new Error(`Secret with name ${r} already exists. Call "apify secrets rm ${r}" to remove it.`);if(typeof r!="string"||r.length>Pn)throw new Error(`Secret name has to be string with maximum length ${Pn}.`);if(typeof e!="string"||e.length>Ln)throw new Error(`Secret value has to be string with maximum length ${Ln}.`);return t[r]=e,Dn(t)},"addSecret"),kn=c(r=>{let e=Jr();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Dn(e)},"removeSecret"),Un=c(r=>new RegExp(`^${ks}.{1}`).test(r),"isSecretKey"),Mn=c((r,e)=>{e=e||Jr();let t={};return Object.keys(r).forEach(o=>{if(Un(r[o])){let s=r[o].replace(new RegExp(`^${ks}`),"");e[s]?t[o]=e[s]:x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t[o]=r[o]}),t},"replaceSecretsValue"),jn=c((r,e)=>{e=e||Jr();let t=[];return Object.keys(r).forEach(o=>{if(Un(r[o])){let s=r[o].replace(new RegExp(`^${ks}`),"");e[s]?t.push({name:o,value:e[s],isSecret:!0}):x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t.push({name:o,value:r[o]})}),t},"transformEnvToEnvVars");var Ms="temp_file.zip",ku={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Bn="0.0",Uu="latest",It=class extends y{static name="push";static description=`Deploys Actor to Apify platform using settings from '${j}'.
83
+ Files under '${Vn/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
84
+ Use --force to override newer remote versions.`;static flags={version:A.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${j}' file.`,required:!1}),"build-tag":A.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${j}' file`,required:!1}),"wait-for-finish":A.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:A.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:A.boolean({description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:A.string({description:"Directory where the Actor is located",required:!1})};static args={actorId:w.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 '${j}' file.`})};async run(){let e=Pu(nt.cwd(),this.flags.dir??"."),t=await Ii(e);if(!t.length){p({message:"You need to call this command from a folder that has an Actor in it!"}),nt.exitCode=4;return}if(![nr,"actor.json",".actor/actor.json",".actor"].some(D=>t.some(Q=>Q===D||Q.startsWith(D)))){p({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(`
85
+ `)}),nt.exitCode=4;return}let o=await C(),s=await Ye({cwd:e});if(s.isErr()){p({message:s.unwrapErr().message}),nt.exitCode=5;return}let{config:i}=s.unwrap(),n=await F(),l=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",m,u,f=!1,d=this.flags.version||i?.version||Bn,g=this.flags.buildTag||i?.buildTag;!g&&d===Bn&&(g=Uu);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,S=this.args.actorId;if(S){if(u=await o.actor(S).get(),!u)throw new Error(`Cannot find Actor with ID '${S}' in your account.`);m=u.id}else{let D=n.username||n.id;if(u=await o.actor(`${D}/${i.name}`).get(),u)m=u.id;else{let{templates:Q}=await Du(),he=Q.find(tr=>tr.name===i.template)?.defaultRunOptions||ku,Et={name:i.name,defaultRunOptions:he,versions:[{versionNumber:d,buildTag:g,sourceType:Us.SOURCE_FILES,sourceFiles:[]}]};u=await o.actors().create(Et),m=u.id,f=!0,v({message:`Created Actor with name ${i.name} on Apify.`})}}v({message:`Deploying Actor '${i.name}' to Apify.`});let b=await di(t,e),T=o.actor(m),E,N,P;if(b<Vn){let D=await T.get();if(!f){let Q=t.reduce((he,Et)=>{let{mtimeMs:tr,ctimeMs:ri}=xu(Nu(e,Et)),oi=tr>ri?tr:ri;return he>oi?he:oi},0),ge=D?.modifiedAt.valueOf();if(!this.flags.force&&ge&&Q<ge&&(i?.name||S))throw new Error(`Actor with identifier "${i?.name||S}" is already on the platform and was modified there since modified locally.
86
+ Skipping push. Use --force to override.`)}N=await Ti(t,e),E=Us.SOURCE_FILES}else{ye({message:"Zipping Actor files"}),await Ci(Ms,t,e);let D=await o.keyValueStores().getOrCreate(`actor-${m}-source`),Q=`version-${d}.zip`,ge=_u(Ms);await o.keyValueStore(D.id).setRecord({key:Q,value:ge,contentType:"application/zip"}),Ou(Ms);let he=new URL(`${o.baseUrl}/key-value-stores/${D.id}/records/${Q}?disableRedirect=true`);if(D?.urlSigningSecretKey){let Et=Fu(D.urlSigningSecretKey,Q);he.searchParams.set("signature",Et)}P=he.toString(),E=Us.TARBALL}let M=await T.version(d).get(),B=i.environmentVariables?jn(i.environmentVariables):void 0;if(M){let D={tarballUrl:P,sourceFiles:N,buildTag:g,sourceType:E,envVars:B};await T.version(d).update(D),ye({message:`Updated version ${d} for Actor ${u.name}.`})}else{let D={versionNumber:d,tarballUrl:P,sourceFiles:N,buildTag:g,sourceType:E,envVars:B};await T.versions().create({...D}),ye({message:`Created version ${d} for Actor ${u.name}.`})}ye({message:`Building Actor ${u.name}`});let J=await T.build(d,{useCache:!0,waitForFinish:2});try{await $e({job:J,timeoutMillis:h,apifyClient:o})}catch(D){x({message:"Can not get log:"}),console.error(D)}J=await o.build(J.id).get(),cs({message:"Actor build detail",url:`https://console.apify.com${l}/actors/${J.actId}#/builds/${J.buildNumber}`}),cs({message:"Actor detail",url:`https://console.apify.com${l}/actors/${J.actId}`}),this.flags.open&&await Lu(`https://console.apify.com${l}/actors/${J.actId}`),J.status===at.SUCCEEDED?$({message:"Actor was deployed to Apify cloud and built there."}):J.status===at.READY?x({message:"Build is waiting for allocation."}):J.status===at.RUNNING?x({message:"Build is still running."}):J.status===at.ABORTED||J.status===at.ABORTING?(x({message:"Build was aborted!"}),nt.exitCode=3):J.status===at.TIMED_OUT||J.status===at.TIMING_OUT?(x({message:"Build timed out!"}),nt.exitCode=2):(p({message:"Build failed!"}),nt.exitCode=1)}};var Kr=class extends y{static name="rm";static description="Permanently removes an Actor from your account.";static args={actorId:w.string({description:"The Actor ID to delete.",required:!0})};async run(){let{actorId:e}=this.args,t=await C();if(!await t.actor(e).get()){p({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await z({message:"Are you sure you want to delete this Actor?"})){v({message:`Deletion of Actor "${e}" was canceled.`});return}try{await t.actor(e).delete(),$({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete Actor "${e}".
87
+ ${n.message||n}`})}}};import ee from"chalk";var qr=class extends y{static name="start";static description=`Starts Actor remotely and returns run details immediately.
88
+ Uses authenticated account and local key-value store for input.`;static flags={...vt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=process.cwd(),t=Fe(e)||{},o=await C(),s=await F(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:l}=await Ge.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),m={};this.flags.build&&(m.build=this.flags.build),this.flags.timeout&&(m.timeout=this.flags.timeout),this.flags.memory&&(m.memory=this.flags.memory);let u=await St(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:m,type:"Actor",inputOverride:u?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),d;for await(let P of f)d=P;if(this.flags.json){L(d);return}let g=`https://console.apify.com/actors/${n}/runs/${d.id}`,h=`https://console.apify.com/storage/datasets/${d.defaultDatasetId}`,S=[`${ee.gray("Run:")} Calling Actor ${a} (${ee.gray(n)})`,"",`${ee.yellow("Started")}: ${V.display(d.startedAt)}`];d.containerUrl&&S.push(`${ee.yellow("Container URL")}: ${ee.blue(d.containerUrl)}`);let b=d.buildNumber.split(".").slice(0,2).join("."),T=l.versions.find(P=>P.versionNumber===b),E=Object.entries(l.taggedBuilds??{}).find(([,P])=>P.buildNumber===d.buildNumber)?.[0],N=[`${ee.yellow("Build")}:`,ee.cyan(d.buildNumber)];E?N.push(`(${ee.yellow(E)})`):N.push(`(${ee.gray("N/A")})`),T&&N.push(`| ${ee.gray("Actor version:")} ${ee.cyan(T.versionNumber)} (${ee.yellow(T.buildTag)})`),S.push(N.join(" ")),S.push(`${ee.yellow("Timeout")}: ${d.options.timeoutSecs.toLocaleString("en-US")} seconds`),S.push(`${ee.yellow("Memory")}: ${d.options.memoryMbytes} MB`),S.push("",`${ee.blue("Export results")}: ${h}`,`${ee.blue("View on Apify Console")}: ${g}`),_({message:S.join(`
89
+ `),stdout:!0})}};var Wr=class extends y{static name="actors";static description="Manages Actor creation, deployment, and execution on the Apify platform.";static subcommands=[qr,Kr,It,Tt,Gr,Br,Ge,kr];async run(){this.printHelp()}};import Z from"chalk";var Mu=c(r=>r,"noColor");function X({bytes:r,shortBytes:e=!1,colorFunc:t=Mu,precision:o=2}){let s=[e?"B":"Bytes","KB","MB","GB","TB"];if(r===0)return e?`${0 .toPrecision(o)} B`:`${0 .toPrecision(o)} Byte`;let i=Math.floor(Math.log(r)/Math.log(1e3));return`${(r/1e3**i).toFixed(o)} ${t(s[i])}`}c(X,"prettyPrintBytes");var zr=class extends y{static name="info";static description="Prints information about a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){L(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[g,h]of Object.entries(s.taggedBuilds))if(h.buildId===o.id){i=g;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",l=i?` (tagged as ${Z.yellow(i)})`:"",m=typeof n<"u"?` (exit code: ${Z.gray(n)})`:"",u=[`${Z.yellow("Actor")}: ${a} (${Z.gray(o.actId)})`,"",`${Z.yellow("Build Information")} (ID: ${Z.gray(o.id)})`,` ${Z.yellow("Build Number")}: ${o.buildNumber}${l}`,` ${Z.yellow("Status")}: ${Ie(o.status)}${m}`,` ${Z.yellow("Started")}: ${V.display(o.startedAt)}`];if(o.finishedAt)u.push(` ${Z.yellow("Finished")}: ${V.display(o.finishedAt)} (took ${Z.gray(kt.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();u.push(` ${Z.yellow("Finished")}: ${Z.gray(`Running for ${kt.format(g)}`)}`)}o.stats?.computeUnits&&u.push(` ${Z.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let f=Reflect.get(o.stats??{},"imageSizeBytes");f&&u.push(` ${Z.yellow("Docker Image Size")}: ${X({bytes:f})}`),u.push(` ${Z.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),u.push("");let d=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;u.push(`${Z.blue("View in Apify Console")}: ${d}`),_({message:u.join(`
90
+ `),stdout:!0})}};var Xr=class extends y{static name="log";static description="Prints the log of a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for build with ID "${e}":
91
+ `});try{await $e({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import me from"chalk";var ju=c(()=>new G({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Zr=class extends y{static name="ls";static description="Lists all builds of the Actor.";static flags={offset:A.integer({description:"Number of builds that will be skipped.",default:0}),limit:A.integer({description:"Number of builds that will be listed.",default:10}),desc:A.boolean({description:"Sort builds in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),l=await Ve({providedActorNameOrId:n,client:a});if(!l.valid){p({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let m=await a.actor(l.id).builds().list({desc:e,limit:t,offset:o}),u=await a.actor(l.id).get(),f=gr(m.items,h=>{let S=Reflect.get(h,"buildNumber"),[b,T]=S.split(".");return`${b}.${T}`}),d=Object.entries(u.taggedBuilds??{}).reduce((h,[S,b])=>(h[b.buildNumber]=S,h),{});if(i){for(let h of m.items){let S=Reflect.get(h,"buildNumber"),b=d[S];b&&Reflect.set(h,"buildTag",b)}L(m);return}_({message:`${me.reset("Showing")} ${me.yellow(m.items.length)} out of ${me.yellow(m.total)} builds for Actor ${me.yellow(l.userFriendlyId)} (${me.gray(l.id)})
92
+ `,stdout:!0});let g=Object.entries(f).sort((h,S)=>h[0].localeCompare(S[0]));for(let[h,S]of g){if(!S?.length){_({message:`No builds for version ${h}`,stdout:!0});continue}let b=u.versions.find(P=>P.versionNumber===h)?.buildTag,T=this.generateTableForActorVersion({buildsForVersion:S,buildTagToActorVersion:d}),E=b?` (latest build gets tagged with ${me.yellow(b)})`:"",N=[me.reset(`Builds for Actor Version ${me.yellow(h)}${E}`),T.render(s?0:-1),""];_({message:N.join(`
93
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=ju();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${me.yellow(t[i])})`:"",a;if(s.finishedAt){let l=s.finishedAt.getTime()-s.startedAt.getTime();a=me.gray(`${se.format(l,void 0,{left:""})}`)}else{let l=Date.now()-s.startedAt.getTime();a=me.gray(`Running for ${se.format(l,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:me.gray(s.id),Status:Ie(s.status),Took:a})}return o}};import Vu from"@inquirer/input";var Gn=Re(async({message:r,expectedValue:e,failureMessage:t})=>await Vu({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Qr=class extends y{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static args={buildId:w.string({description:"The build ID to delete.",required:!0})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[a,l]of Object.entries(s.taggedBuilds))if(e===l.buildId){i=a;break}}if(!await(i?Gn:z)({message:`Are you sure you want to delete this Actor Build?${i?` If so, please type in "${i}":`:""}`,expectedValue:i??"",failureMessage:"Your provided value does not match the build tag."})){v({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await t.build(e).delete(),$({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete build "${e}".
94
+ ${l.message||l}`,stdout:!0})}}};var eo=class extends y{static name="builds";static description="Manages Actor build processes and versioning.";static subcommands=[Qr,Zr,Xr,zr,At];async run(){this.printHelp()}};var to=class extends Ge{static name="call"};import Bu from"assert";import{existsSync as ro}from"fs";import{mkdir as Gu,readFile as Yu,symlink as Hu,unlink as Ju,writeFile as Yn}from"fs/promises";import{basename as Ku,join as de}from"path";import He from"chalk";var qu=c(r=>de(r,".install-marker"),"pathToInstallMarker"),js=c(r=>r.startsWith(process.env.HOME)?r.replace(process.env.HOME,"~"):r,"tildify"),qt=class extends y{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:t,version:o}=K();if(e!=="bundle"){v({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}Bu(t,"When CLI is installed via bundles, the install path must be set");let s=qu(t);if(ro(s)){v({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}await this.symlinkToLocalBin(t),await this.promptAddToShell(),await Yn(s,o),I("[install] install marker written to",s),_({message:""}),$({message:"To get started, run:"}),_({message:He.white.bold(` apify --help
95
+ actor --help`)})}async symlinkToLocalBin(e){let t=process.env.HOME;if(I("[install] user home directory",t),!t){I("[install] user home directory not found"),x({message:He.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=de(t,".local","bin");ro(o)||await Gu(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=de(e,i);if(!ro(n)){I("[install] file not found for symlinking",i,n),x({message:He.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=de(o,i);await Ju(a).catch(()=>{}),await Hu(n,a),I("[install] symlink created for item",i,a)}v({message:He.gray(`Symlinked apify, actor, and apify-cli to ${o}`)})}async promptAddToShell(){let e=process.env.PROVIDED_INSTALL_DIR;if(!e){x({message:He.gray("Install directory not found, cannot add to shell")});return}let t=process.env.FINAL_BIN_DIR;_({message:""});let o=await z({message:"Should the CLI handle adding itself to your shell automatically? (If you say no, you will receive the lines to add to your shell config file)",providedConfirmFromStdin:!1}),s=Ku(process.env.SHELL??"sh"),i=`"${e.replaceAll('"','\\"')}"`,n=[],a="";switch(s){case"bash":{n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');let l=[de(process.env.HOME,".bashrc"),de(process.env.HOME,".bash_profile")];process.env.XDG_CONFIG_HOME&&l.push(de(process.env.XDG_CONFIG_HOME,".bashrc"),de(process.env.XDG_CONFIG_HOME,".bash_profile"),de(process.env.XDG_CONFIG_HOME,"bashrc"),de(process.env.XDG_CONFIG_HOME,"bash_profile"));for(let m of l)if(ro(m)){a=m;break}break}case"zsh":n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a=de(process.env.HOME,".zshrc");break;case"fish":{n.push(`set --export APIFY_CLI_INSTALL ${i}`),n.push(`set --export PATH ${t} $PATH`),a=de(process.env.HOME,".config","fish","config.fish");break}default:n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a="~/.bashrc";break}if(_({message:""}),o&&a){let m=`${await Yu(a,"utf-8")}
96
96
 
97
97
  # apify cli
98
98
  ${n.join(`
99
- `)}`;await Hn(a,m),b({message:He.gray(`Added "${js(t)}" to $PATH in ${js(a)}`)})}else b({message:[He.gray(`Manually add the following lines to your shell config file (${js(a)} or similar):`),...n.map(l=>He.white.bold(` ${l}`))].join(`
100
- `)})}};import{spawn as rm}from"child_process";import{existsSync as om}from"fs";import{lstat as sm,readdir as im,writeFile as qn}from"fs/promises";import{dirname as nm,join as Vs}from"path";import Bs from"chalk";import{gte as Wn}from"semver";import{Result as Wu}from"@sapphire/result";import{execa as zu}from"execa";var Xu=c(async(r,e,t)=>{let o=ke(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=zu(o,e,{shell:!0,windowsHide:!0,env:t.env,cwd:t.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return Wu.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function pe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){he({message:`${o||r} ${e.join(" ")}`});let s=await Xu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(p({message:i.message}),i.cause)throw i.cause}}c(pe,"execWithLog");import{execSync as Jn}from"child_process";import{existsSync as Zu,readFileSync as Qu}from"fs";var Pe=K();function em(){return Pe.platform==="linux"?Zu("/etc/alpine-release"):!1}c(em,"isInstalledOnMusl");function tm(){return Pe.platform==="darwin"&&Pe.arch==="x64"?!Jn("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Pe.platform==="linux"&&Pe.arch==="x64"?!Qu("/proc/cpuinfo","utf-8").includes("avx2"):Pe.platform==="windows"?Pe.arch==="arm64"?!0:Jn(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:"utf-8",windowsHide:!0}).trim().toLowerCase()==="true":!1}c(tm,"isInstalledOnBaseline");async function Kn(r){let e=r.replace(/^v(\d+)/,"$1"),t=e==="latest"?"latest":`tags/v${e}`,o=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${t}`,{headers:{"User-Agent":tt}});if(!o.ok)return T("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:r,tag:t}),null;let s=await o.json(),i=em(),n=tm(),a=s.assets.filter(l=>{let[m,u,f,d,g,h]=l.name.replace(e,"version").replace(".exe","").split("-");return f!==Pe.platform||d!==Pe.arch?!1:i?g==="musl":n?h==="baseline"||g==="baseline":!g&&!h});return T("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}c(Kn,"useCLIVersionAssets");var zn={bundle:c((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:c(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:c(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:c(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:c(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:c(r=>["volta","install",`apify-cli@${r}`],"volta")},ro="0.21.8",Xn="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",qt=class extends y{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static hidden=!0;static aliases=["cv","check-version"];static flags={force:A.boolean({description:"Whether to skip checking the locally cached latest version of the CLI and fetch it from the internet instead.",required:!1,char:"f"}),version:A.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":A.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 dn(this.flags.force),{installMethod:t}=K();if(!e.shouldUpdate||e.currentVersion===si){T("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||b({message:`${this.cliName} is up to date \u{1F44D}
101
- `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=zn[t]("latest",this.entrypoint).join(" ");R({message:""});let s=[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` \u21AA Run ${Bs.bgWhite(Bs.black(o))} to update! \u{1F44D}
99
+ `)}`;await Yn(a,m),v({message:He.gray(`Added "${js(t)}" to $PATH in ${js(a)}`)})}else v({message:[He.gray(`Manually add the following lines to your shell config file (${js(a)} or similar):`),...n.map(l=>He.white.bold(` ${l}`))].join(`
100
+ `)})}};import{spawn as rm}from"child_process";import{existsSync as om}from"fs";import{lstat as sm,readdir as im,writeFile as Kn}from"fs/promises";import{dirname as nm,join as Vs}from"path";import Bs from"chalk";import{gte as qn}from"semver";import{Result as Wu}from"@sapphire/result";import{execa as zu}from"execa";var Xu=c(async(r,e,t)=>{let o=ke(r);I("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=zu(o,e,{shell:!0,windowsHide:!0,env:t.env,cwd:t.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return Wu.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function pe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){ye({message:`${o||r} ${e.join(" ")}`});let s=await Xu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(p({message:i.message}),i.cause)throw i.cause}}c(pe,"execWithLog");import{execSync as Hn}from"child_process";import{existsSync as Zu,readFileSync as Qu}from"fs";var Le=K();function em(){return Le.platform==="linux"?Zu("/etc/alpine-release"):!1}c(em,"isInstalledOnMusl");function tm(){return Le.platform==="darwin"&&Le.arch==="x64"?!Hn("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Le.platform==="linux"&&Le.arch==="x64"?!Qu("/proc/cpuinfo","utf-8").includes("avx2"):Le.platform==="windows"?Le.arch==="arm64"?!0:Hn(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:"utf-8",windowsHide:!0}).trim().toLowerCase()==="true":!1}c(tm,"isInstalledOnBaseline");async function Jn(r){let e=r.replace(/^v(\d+)/,"$1"),t=e==="latest"?"latest":`tags/v${e}`,o=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${t}`,{headers:{"User-Agent":tt}});if(!o.ok)return I("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:r,tag:t}),null;let s=await o.json(),i=em(),n=tm(),a=s.assets.filter(l=>{let[m,u,f,d,g,h]=l.name.replace(e,"version").replace(".exe","").split("-");return f!==Le.platform||d!==Le.arch?!1:i?g==="musl":n?h==="baseline"||g==="baseline":!g&&!h});return I("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}c(Jn,"useCLIVersionAssets");var Wn={bundle:c((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:c(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:c(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:c(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:c(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:c(r=>["volta","install",`apify-cli@${r}`],"volta")},oo="0.21.8",zn="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",Wt=class extends y{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static hidden=!0;static aliases=["cv","check-version"];static flags={force:A.boolean({description:"Whether to skip checking the locally cached latest version of the CLI and fetch it from the internet instead.",required:!1,char:"f"}),version:A.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":A.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 dn(this.flags.force),{installMethod:t}=K();if(!e.shouldUpdate||e.currentVersion===si){I("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||v({message:`${this.cliName} is up to date \u{1F44D}
101
+ `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=Wn[t]("latest",this.entrypoint).join(" ");_({message:""});let s=[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` \u21AA Run ${Bs.bgWhite(Bs.black(o))} to update! \u{1F44D}
102
102
  `].join(`
103
- `);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!Wn(e,ro)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${ro}.`});return}let t=await Kn(e);if(!t){p({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!Wn(s,ro)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${ro}.`});return}let i=K();if(i.installMethod==="bundle"){if(!o.length){p({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
104
- `)});return}let a=nm(process.execPath);T("[upgrade] bundleDirectory",a);let l=await im(a);if(!l.some(m=>m.startsWith("apify")||m.startsWith("actor"))){T("[upgrade] directoryEntries",l),p({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
105
- `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=zn[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){b({message:`Would run command: ${n.join(" ")}`});return}try{await pe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{p({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){$({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Vs(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${t}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),T("[upgrade] starting upgrade process with args",s),b({message:"Starting upgrade process..."});let n=rm("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{T("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{p({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=Vs(e,"upgrade.ps1");if(om(t))return;let o=K(),s=await fetch(Xn,{headers:{"User-Agent":tt}});s.ok||(p({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: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${Xn}`,`- The status code of the response: ${s.status}`].join(`
106
- `)}),process.exit(1));let i=await s.arrayBuffer();await qn(t,Buffer.from(i)),T("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=K();for(let i of o){let n=i.name.split("-")[0],a=Vs(e,n);b({message:`Downloading ${n}...`});let l=await fetch(i.browser_download_url,{headers:{"User-Agent":tt}});if(!l.ok){let u=await l.text();T("[upgrade] failed to fetch asset",{asset:i,status:l.status,body:u}),p({message:[`Failed to fetch the ${n} 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: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${l.status}`,`- The body of the response: ${u}`].join(`
107
- `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){b({message:`Would write asset ${n} to ${a}`});continue}b({message:Bs.gray(`Writing ${n} to ${a}...`)});let m=await l.arrayBuffer();try{let u=await sm(a).then(f=>f.mode).catch(()=>493);await qn(a,Buffer.from(m),{mode:u|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(u){T("[upgrade] failed to write asset",{error:u}),p({message:[`Failed to write the ${n} 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: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${u.message}`].join(`
108
- `)})}}}};import{mkdir as Sm,readdir as bm,stat as vm}from"fs/promises";import{join as Ct}from"path";import aa from"process";import{gte as Tm,minVersion as Im}from"semver";import{fetchManifest as Cm,manifestUrl as Em}from"@apify/actor-templates";import{createWriteStream as lm}from"fs";import{pipeline as cm}from"stream/promises";import{Separator as ea}from"@inquirer/core";import Zn from"chalk";import am from"@inquirer/select";var Je=$e(async({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i})=>await am({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i}));var Qn=["JavaScript","TypeScript","Python"];async function Gs(r){return r?(Lt(r),r):um()}c(Gs,"ensureValidActorName");async function ta(r,e){let t=await e;if(t instanceof Error)throw t;if(r){let o=t.templates.find(s=>s.name===r);if(!o)throw new Error(`Could not find the selected template: ${r} in the list of templates.`);return o}return oa(t)}c(ta,"getTemplateDefinition");async function ra(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await lr(t.localReadmeSuffixUrl),s=lm(r,{flags:"a"});s.write(`
109
-
110
- `),await cm(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}c(ra,"enhanceReadmeWithLocalSuffix");async function oa(r){let e=await mm();for(;;){let t=await dm(r,e);if(t){if(await pm(t))return t}else return oa(r)}}c(oa,"executePrompts");async function um(){return await rt({message:"Name of your new Actor:",validate:c(e=>{try{Lt(e)}catch(t){return t.message}return!0},"validate")})}c(um,"promptActorName");async function mm(){return await Je({message:"Choose the programming language of your new Actor:",choices:Qn,loop:!1,default:Qn[0]})}c(mm,"promptProgrammingLanguage");async function dm(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new ea,{name:"Go back",value:!1}];return await Je({message:"Choose a template for your new Actor. Detailed information about the template will be shown in the next step.",default:t[0],choices:t,loop:!1,pageSize:8})}c(dm,"promptTemplateDefinition");async function pm(r){let e=[{name:"Install template",value:!0},new ea,{name:"Go back",value:!1}],t=Zn.underline(r.label),o=Zn.dim(r.description),i=`Do you want to install the following template?${`
103
+ `);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!qn(e,oo)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${oo}.`});return}let t=await Jn(e);if(!t){p({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!qn(s,oo)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${oo}.`});return}let i=K();if(i.installMethod==="bundle"){if(!o.length){p({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
104
+ `)});return}let a=nm(process.execPath);I("[upgrade] bundleDirectory",a);let l=await im(a);if(!l.some(m=>m.startsWith("apify")||m.startsWith("actor"))){I("[upgrade] directoryEntries",l),p({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
105
+ `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=Wn[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){v({message:`Would run command: ${n.join(" ")}`});return}try{await pe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{p({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){$({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Vs(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${t}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),I("[upgrade] starting upgrade process with args",s),v({message:"Starting upgrade process..."});let n=rm("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{I("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{p({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=Vs(e,"upgrade.ps1");if(om(t))return;let o=K(),s=await fetch(zn,{headers:{"User-Agent":tt}});s.ok||(p({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: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${zn}`,`- The status code of the response: ${s.status}`].join(`
106
+ `)}),process.exit(1));let i=await s.arrayBuffer();await Kn(t,Buffer.from(i)),I("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=K();for(let i of o){let n=i.name.split("-")[0],a=Vs(e,n);v({message:`Downloading ${n}...`});let l=await fetch(i.browser_download_url,{headers:{"User-Agent":tt}});if(!l.ok){let u=await l.text();I("[upgrade] failed to fetch asset",{asset:i,status:l.status,body:u}),p({message:[`Failed to fetch the ${n} 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: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${l.status}`,`- The body of the response: ${u}`].join(`
107
+ `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){v({message:`Would write asset ${n} to ${a}`});continue}v({message:Bs.gray(`Writing ${n} to ${a}...`)});let m=await l.arrayBuffer();try{let u=await sm(a).then(f=>f.mode).catch(()=>493);await Kn(a,Buffer.from(m),{mode:u|448}),I(`[upgrade ${n}] wrote asset to`,a)}catch(u){I("[upgrade] failed to write asset",{error:u}),p({message:[`Failed to write the ${n} 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: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${u.message}`].join(`
108
+ `)})}}}};import{mkdir as Sm,readdir as bm,stat as vm}from"fs/promises";import{join as Ct}from"path";import na from"process";import{gte as Tm,minVersion as Im}from"semver";import{fetchManifest as Cm,manifestUrl as Em}from"@apify/actor-templates";import{createWriteStream as lm}from"fs";import{pipeline as cm}from"stream/promises";import{Separator as Qn}from"@inquirer/core";import Xn from"chalk";import am from"@inquirer/select";var Je=Re(async({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i})=>await am({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i}));var Zn=["JavaScript","TypeScript","Python"];async function Gs(r){return r?(Dt(r),r):um()}c(Gs,"ensureValidActorName");async function ea(r,e){let t=await e;if(t instanceof Error)throw t;if(r){let o=t.templates.find(s=>s.name===r);if(!o)throw new Error(`Could not find the selected template: ${r} in the list of templates.`);return o}return ra(t)}c(ea,"getTemplateDefinition");async function ta(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await cr(t.localReadmeSuffixUrl),s=lm(r,{flags:"a"});s.write(`
109
+
110
+ `),await cm(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}c(ta,"enhanceReadmeWithLocalSuffix");async function ra(r){let e=await mm();for(;;){let t=await dm(r,e);if(t){if(await pm(t))return t}else return ra(r)}}c(ra,"executePrompts");async function um(){return await rt({message:"Name of your new Actor:",validate:c(e=>{try{Dt(e)}catch(t){return t.message}return!0},"validate")})}c(um,"promptActorName");async function mm(){return await Je({message:"Choose the programming language of your new Actor:",choices:Zn,loop:!1,default:Zn[0]})}c(mm,"promptProgrammingLanguage");async function dm(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new Qn,{name:"Go back",value:!1}];return await Je({message:"Choose a template for your new Actor. Detailed information about the template will be shown in the next step.",default:t[0],choices:t,loop:!1,pageSize:8})}c(dm,"promptTemplateDefinition");async function pm(r){let e=[{name:"Install template",value:!0},new Qn,{name:"Go back",value:!1}],t=Xn.underline(r.label),o=Xn.dim(r.description),i=`Do you want to install the following template?${`
111
111
  ${t}:
112
- ${o}`}`;return await Je({message:i,default:e[0],choices:e,loop:!1})}c(pm,"promptTemplateInstallation");import{existsSync as fm,writeFileSync as gm}from"fs";import{join as oo}from"path";import hm from"process";import ym from"lodash.clonedeep";import{KEY_VALUE_STORE_KEYS as wm}from"@apify/consts";import{validateInputSchema as Am}from"@apify/input_schema";var sa=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],lt=c(async({forcePath:r,cwd:e}={cwd:hm.cwd()})=>{if(r)return{inputSchema:Ce(r),inputSchemaPath:r};let t=Fe(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=oo(e,ds,t.input);return{inputSchema:Ce(o),inputSchemaPath:o}}for(let o of sa){let s=oo(e,o);if(fm(s))return{inputSchema:Ce(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:oo(e,sa[0])}},"readInputSchema"),so=c(async r=>{let e={};try{let{inputSchema:t}=await lt({cwd:r});if(t){let o=new mt({strict:!1});Am(o,t),e=Object.entries(t.properties).reduce((s,[i,n])=>(s[i]=n.type==="boolean"||n.editor==="hidden"?n.default:n.prefill,s),{})}}catch(t){x({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=Ie(),o=oo(r,t,`${wm.INPUT}.json`);gm(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),ia=c(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),na=c((r,e)=>{let t=ym(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");var io=class extends y{static name="create";static description="Creates an Actor project from a template in a new directory.";static flags={template:A.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it.
113
- Visit ${Em} to find available template names.`,required:!1}),"skip-dependency-install":A.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":A.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":A.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1})};static args={actorName:w.string({required:!1,description:"Name of the Actor and its directory"})};async run(){let{actorName:e}=this.args,{template:t,skipDependencyInstall:o}=this.flags,{templateArchiveUrl:s}=this.flags,i=!1,n=Cm().catch(h=>new Error(`Could not fetch template list from server. Cause: ${h?.message}`));e=await Gs(e);let a=aa.cwd(),l=Ct(a,e);for(;;){let h=await vm(l).catch(()=>null),S=h&&await bm(l).then(I=>I.length>0).catch(()=>!1);if(h?.isDirectory()&&S){p({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Gs(),l=Ct(a,e);continue}h||await Sm(l,{recursive:!0});break}let m=null;if(this.telemetryData.fromArchiveUrl=!!s,!s){let h=await ta(t,n);({archiveUrl:s,messages:m}=h),this.telemetryData.templateId=h.id,this.telemetryData.templateName=h.name,this.telemetryData.templateLanguage=h.category,"skipOptionalDeps"in h&&(i=h.skipOptionalDeps)}this.flags.omitOptionalDeps&&(i=!0),await pr({url:s,pathTo:l});let u=Ce(Ct(l,j));await cr(Object.assign(u||tr,{name:e}),l),await ur(l),await so(l);let f=Ct(l,"package.json"),d=Ct(l,"README.md");await ra(d,n);let g=!1;o||await(await Me({cwd:l})).inspectAsync(async S=>{let I=Im(ye);if(!S.runtime){switch(S.type){case 0:{x({message:`No Node.js detected! Please install Node.js ${I} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{x({message:`No Python detected! Please install Python ${Qe} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:v}=S;switch(S.type){case 0:{dr(v.version)||x({message:`You are running Node.js version ${v.version}, which is no longer supported. Please upgrade to Node.js version ${I} or later.`}),await mi(f,{name:e});let E=["install"];if(i)switch(v.pmName){case"npm":{Tm(v.pmVersion,"7.0.0")?E.push("--omit=optional"):E.push("--no-optional");break}case"bun":{E.push("--omit=optional");break}case"deno":{E.push("--node-modules-dir");break}default:}await pe({cmd:v.pmPath,args:E,opts:{cwd:l},overrideCommand:v.pmName}),g=!0;break}case 1:case 2:{if(!mr(v.version)){x({message:`Python Actors require Python 3.9 or higher, but you have Python ${v.version}!`}),x({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let E=Ct(l,".venv");b({message:`Python version ${v.version} detected.`}),b({message:`Creating a virtual environment in "${E}" and installing dependencies from "requirements.txt"...`}),aa.env.VIRTUAL_ENV||(await pe({cmd:v.executablePath,args:["-m","venv","--prompt",".",li],opts:{cwd:l}}),v=(await Ut({cwd:l,force:!0})).unwrap(),S.runtime=v),await pe({cmd:v.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:l}}),await pe({cmd:v.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:l}}),g=!0;break}default:}}),g?($({message:`Actor '${e}' was created. To run it, run "cd ${e}" and "apify run".`}),b({message:'To run your code in the cloud, run "apify push" and deploy your code to Apify Console.'}),m?.postCreate&&b({message:m?.postCreate})):$({message:`Actor '${e}' was created. Please install its dependencies to be able to run it using "apify run".`})}};import ca from"chalk";async function la(r,e,t){let o=await r[t](e).get().catch(()=>{});if(o)return{[t]:o,[`${t}Client`]:r[t](o.id)};let s=await D(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}c(la,"tryToGetStorage");async function xe(r,e){return la(r,e,"dataset")}c(xe,"tryToGetDataset");async function ee(r,e){return la(r,e,"keyValueStore")}c(ee,"tryToGetKeyValueStore");var no=class extends y{static name="create";static description="Creates a new dataset for storing structured data on your account.";static args={datasetName:w.string({description:"Optional name for the Dataset",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await C();if(e&&await xe(t,e)){p({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){N(o);return}$({message:`Dataset with ID ${ca.yellow(o.id)}${e?` (called ${ca.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as Ke}from"apify-client";var ua={[Ke.JSON]:"application/json",[Ke.JSONL]:"application/jsonl",[Ke.CSV]:"text/csv",[Ke.HTML]:"text/html",[Ke.RSS]:"application/rss+xml",[Ke.XML]:"application/xml",[Ke.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},ao=class extends y{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static flags={limit:A.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:A.integer({description:"The offset in the dataset where to start getting items."}),format:A.string({description:"The format of the returned output. By default, it is set to 'json'",choices:Object.keys(ua),default:Ke.JSON})};static args={datasetId:w.string({description:"The ID of the Dataset to export the items for",required:!0})};async run(){let{limit:e,offset:t,format:o}=this.flags,{datasetId:s}=this.args,i=await C(),n=await this.tryToGetDataset(i,s);if(!n){p({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let l=await a.downloadItems(o,{limit:e,offset:t}),m=ua[o]??"application/octet-stream";R({message:m}),process.stdout.write(l),process.stdout.write(`
114
- `)}async tryToGetDataset(e,t){let o=await e.dataset(t).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await D(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import U from"chalk";function lo(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}c(lo,"getUserPlanPricing");var ma=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),co=class extends y{static name="info";static description="Prints information about a specific dataset.";static args={storeId:w.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await xe(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),l;if(a?.actorTaskId&&(l=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){N({...s,user:i,actor:n||null,run:a||null,task:l||null});return}let m=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,d=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),h=[`${U.bold(u.toLocaleString("en-US"))} ${U.gray(this.pluralString(u,"read","reads"))}`,`${U.bold(f.toLocaleString("en-US"))} ${U.gray(this.pluralString(f,"write","writes"))}`],S=`Items: ${U.bold(d)} ${U.gray("clean")} / ${U.bold(g)} ${U.gray("total")}
115
- Operations: ${h.join(" / ")}`;if(i.plan){let F=lo(i.plan);if(F){let te=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(m/1e9),ge=te*24*30,De=ge>1?`$${ge.toFixed(2)}`:`$${te.toFixed(3)}`;S+=`
116
- Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${U.gray(`${De} per month`)}`}}else S+=`
117
- Storage size: ${X({bytes:m,shortBytes:!0,precision:1})}`;let I=[`Dataset ID: ${U.bgGray(s.id)}`,`Name: ${s.name?U.bgGray(s.name):U.bold(U.italic("Unnamed"))}`,`Created: ${U.bold(V.display(s.createdAt))}`,`Modified: ${U.bold(V.display(s.modifiedAt))}`].join(`
118
- `),v=U.bold("\u2014");s.actRunId&&(a?v=U.bgBlue(a.id):v=U.italic(U.gray("Run removed")));let E=U.bold("\u2014");n&&(E=U.blue(n.title||n.name));let P=U.bold("\u2014");l&&(P=U.blue(l.title||l.name));let L=[`Run: ${v}`,`Actor: ${E}`,`Task: ${P}`].join(`
119
- `);ma.pushRow({Row1:I,Row2:L});let Y=ma.render(2).split(`
120
- `).map(F=>F.trim());Y.shift();let J=[`${U.bold(s.name||U.italic("Unnamed"))}`,`${U.gray(s.name?`${i.username}/${s.name}`:s.id)} ${U.gray("Owned by")} ${U.blue(i.username)}`,"",Y.join(`
112
+ ${o}`}`;return await Je({message:i,default:e[0],choices:e,loop:!1})}c(pm,"promptTemplateInstallation");import{existsSync as fm,writeFileSync as gm}from"fs";import{join as so}from"path";import hm from"process";import ym from"lodash.clonedeep";import{KEY_VALUE_STORE_KEYS as wm}from"@apify/consts";import{validateInputSchema as Am}from"@apify/input_schema";var oa=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],lt=c(async({forcePath:r,cwd:e}={cwd:hm.cwd()})=>{if(r)return{inputSchema:Ee(r),inputSchemaPath:r};let t=Fe(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=so(e,ds,t.input);return{inputSchema:Ee(o),inputSchemaPath:o}}for(let o of oa){let s=so(e,o);if(fm(s))return{inputSchema:Ee(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:so(e,oa[0])}},"readInputSchema"),io=c(async r=>{let e={};try{let{inputSchema:t}=await lt({cwd:r});if(t){let o=new mt({strict:!1});Am(o,t),e=Object.entries(t.properties).reduce((s,[i,n])=>(s[i]=n.type==="boolean"||n.editor==="hidden"?n.default:n.prefill,s),{})}}catch(t){x({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=Ce(),o=so(r,t,`${wm.INPUT}.json`);gm(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),sa=c(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),ia=c((r,e)=>{let t=ym(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");var no=class extends y{static name="create";static description="Creates an Actor project from a template in a new directory.";static flags={template:A.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it.
113
+ Visit ${Em} to find available template names.`,required:!1}),"skip-dependency-install":A.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":A.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":A.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1})};static args={actorName:w.string({required:!1,description:"Name of the Actor and its directory"})};async run(){let{actorName:e}=this.args,{template:t,skipDependencyInstall:o}=this.flags,{templateArchiveUrl:s}=this.flags,i=!1,n=Cm().catch(h=>new Error(`Could not fetch template list from server. Cause: ${h?.message}`));e=await Gs(e);let a=na.cwd(),l=Ct(a,e);for(;;){let h=await vm(l).catch(()=>null),S=h&&await bm(l).then(b=>b.length>0).catch(()=>!1);if(h?.isDirectory()&&S){p({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Gs(),l=Ct(a,e);continue}h||await Sm(l,{recursive:!0});break}let m=null;if(this.telemetryData.fromArchiveUrl=!!s,!s){let h=await ea(t,n);({archiveUrl:s,messages:m}=h),this.telemetryData.templateId=h.id,this.telemetryData.templateName=h.name,this.telemetryData.templateLanguage=h.category,"skipOptionalDeps"in h&&(i=h.skipOptionalDeps)}this.flags.omitOptionalDeps&&(i=!0),await fr({url:s,pathTo:l});let u=Ee(Ct(l,j));await ur(Object.assign(u||rr,{name:e}),l),await mr(l),await io(l);let f=Ct(l,"package.json"),d=Ct(l,"README.md");await ta(d,n);let g=!1;o||await(await Me({cwd:l})).inspectAsync(async S=>{let b=Im(we);if(!S.runtime){switch(S.type){case 0:{x({message:`No Node.js detected! Please install Node.js ${b} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{x({message:`No Python detected! Please install Python ${Qe} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:T}=S;switch(S.type){case 0:{pr(T.version)||x({message:`You are running Node.js version ${T.version}, which is no longer supported. Please upgrade to Node.js version ${b} or later.`}),await mi(f,{name:e});let E=["install"];if(i)switch(T.pmName){case"npm":{Tm(T.pmVersion,"7.0.0")?E.push("--omit=optional"):E.push("--no-optional");break}case"bun":{E.push("--omit=optional");break}case"deno":{E.push("--node-modules-dir");break}default:}await pe({cmd:T.pmPath,args:E,opts:{cwd:l},overrideCommand:T.pmName}),g=!0;break}case 1:case 2:{if(!dr(T.version)){x({message:`Python Actors require Python 3.9 or higher, but you have Python ${T.version}!`}),x({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let E=Ct(l,".venv");v({message:`Python version ${T.version} detected.`}),v({message:`Creating a virtual environment in "${E}" and installing dependencies from "requirements.txt"...`}),na.env.VIRTUAL_ENV||(await pe({cmd:T.executablePath,args:["-m","venv","--prompt",".",li],opts:{cwd:l}}),T=(await Mt({cwd:l,force:!0})).unwrap(),S.runtime=T),await pe({cmd:T.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:l}}),await pe({cmd:T.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:l}}),g=!0;break}default:}}),g?($({message:`Actor '${e}' was created. To run it, run "cd ${e}" and "apify run".`}),v({message:'To run your code in the cloud, run "apify push" and deploy your code to Apify Console.'}),m?.postCreate&&v({message:m?.postCreate})):$({message:`Actor '${e}' was created. Please install its dependencies to be able to run it using "apify run".`})}};import la from"chalk";async function aa(r,e,t){let o=await r[t](e).get().catch(()=>{});if(o)return{[t]:o,[`${t}Client`]:r[t](o.id)};let s=await F(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}c(aa,"tryToGetStorage");async function Oe(r,e){return aa(r,e,"dataset")}c(Oe,"tryToGetDataset");async function te(r,e){return aa(r,e,"keyValueStore")}c(te,"tryToGetKeyValueStore");var ao=class extends y{static name="create";static description="Creates a new dataset for storing structured data on your account.";static args={datasetName:w.string({description:"Optional name for the Dataset",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await C();if(e&&await Oe(t,e)){p({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){L(o);return}$({message:`Dataset with ID ${la.yellow(o.id)}${e?` (called ${la.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as Ke}from"apify-client";var ca={[Ke.JSON]:"application/json",[Ke.JSONL]:"application/jsonl",[Ke.CSV]:"text/csv",[Ke.HTML]:"text/html",[Ke.RSS]:"application/rss+xml",[Ke.XML]:"application/xml",[Ke.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},lo=class extends y{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static flags={limit:A.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:A.integer({description:"The offset in the dataset where to start getting items."}),format:A.string({description:"The format of the returned output. By default, it is set to 'json'",choices:Object.keys(ca),default:Ke.JSON})};static args={datasetId:w.string({description:"The ID of the Dataset to export the items for",required:!0})};async run(){let{limit:e,offset:t,format:o}=this.flags,{datasetId:s}=this.args,i=await C(),n=await this.tryToGetDataset(i,s);if(!n){p({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let l=await a.downloadItems(o,{limit:e,offset:t}),m=ca[o]??"application/octet-stream";_({message:m}),process.stdout.write(l),process.stdout.write(`
114
+ `)}async tryToGetDataset(e,t){let o=await e.dataset(t).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await F(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import U from"chalk";function co(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}c(co,"getUserPlanPricing");var ua=new G({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),uo=class extends y{static name="info";static description="Prints information about a specific dataset.";static args={storeId:w.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await Oe(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(D=>D),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),l;if(a?.actorTaskId&&(l=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:l||null});return}let m=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,d=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),h=[`${U.bold(u.toLocaleString("en-US"))} ${U.gray(this.pluralString(u,"read","reads"))}`,`${U.bold(f.toLocaleString("en-US"))} ${U.gray(this.pluralString(f,"write","writes"))}`],S=`Items: ${U.bold(d)} ${U.gray("clean")} / ${U.bold(g)} ${U.gray("total")}
115
+ Operations: ${h.join(" / ")}`;if(i.plan){let D=co(i.plan);if(D){let Q=D.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(m/1e9),ge=Q*24*30,he=ge>1?`$${ge.toFixed(2)}`:`$${Q.toFixed(3)}`;S+=`
116
+ Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${U.gray(`${he} per month`)}`}}else S+=`
117
+ Storage size: ${X({bytes:m,shortBytes:!0,precision:1})}`;let b=[`Dataset ID: ${U.bgGray(s.id)}`,`Name: ${s.name?U.bgGray(s.name):U.bold(U.italic("Unnamed"))}`,`Created: ${U.bold(V.display(s.createdAt))}`,`Modified: ${U.bold(V.display(s.modifiedAt))}`].join(`
118
+ `),T=U.bold("\u2014");s.actRunId&&(a?T=U.bgBlue(a.id):T=U.italic(U.gray("Run removed")));let E=U.bold("\u2014");n&&(E=U.blue(n.title||n.name));let N=U.bold("\u2014");l&&(N=U.blue(l.title||l.name));let P=[`Run: ${T}`,`Actor: ${E}`,`Task: ${N}`].join(`
119
+ `);ua.pushRow({Row1:b,Row2:P});let B=ua.render(2).split(`
120
+ `).map(D=>D.trim());B.shift();let J=[`${U.bold(s.name||U.italic("Unnamed"))}`,`${U.gray(s.name?`${i.username}/${s.name}`:s.id)} ${U.gray("Owned by")} ${U.blue(i.username)}`,"",B.join(`
121
121
  `),"",S].join(`
122
- `);R({message:J,stdout:!0})}};import da from"chalk";var pa=new B({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),uo=class extends y{static name="ls";static description="Prints all datasets on your account.";static flags={offset:A.integer({description:"Number of datasets that will be skipped.",default:0}),limit:A.integer({description:"Number of datasets that will be listed.",default:20}),desc:A.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:A.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await D(),l=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){N(l);return}if(l.count===0){b({message:"You don't have any Datasets on your account",stdout:!0});return}for(let m of l.items){let u=Reflect.get(m.stats,"s3StorageBytes");pa.pushRow({"Dataset ID":m.id,Created:V.display(m.createdAt),Items:`${m.itemCount}`,Modified:V.display(m.modifiedAt),Name:m.name?`${a.username}/${m.name}`:"",Size:typeof u=="number"?X({bytes:u,shortBytes:!0,colorFunc:da.gray,precision:0}):da.gray("N/A")})}R({message:pa.render(1),stdout:!0})}};import mo from"chalk";var po=class extends y{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static args={nameOrId:w.string({required:!0,description:"The dataset ID or name to push the objects to",ignoreStdin:!0}),item:w.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await C(),s=await xe(o,e);if(!s){p({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,l=t||be;if(!l){p({message:"No items were provided."});return}try{a=JSON.parse(l.toString("utf8"))}catch(u){p({message:`Failed to parse data as JSON string: ${u.message}`});return}if(Array.isArray(a)&&a.length===0){p({message:"No items were provided."});return}let m=n.name?`Dataset named ${mo.yellow(n.name)} (${mo.gray("ID:")} ${mo.yellow(n.id)})`:`Dataset with ID ${mo.yellow(n.id)}`;try{await i.pushItems(a),$({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${m} successfully.`})}catch(u){let f=u;p({message:`Failed to push items into ${m}
123
- ${f.message||f}`})}}};import qe from"chalk";var fo=class extends y{static name="rename";static description="Change dataset name or removes name with --unname flag.";static flags={unname:A.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:w.string({description:"The dataset ID or name to delete.",required:!0}),newName:w.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await xe(s,o);if(!i){p({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,l=a?e?`The name of the dataset with ID ${qe.yellow(n)} has been removed (was ${qe.yellow(a)} previously).`:`The name of the dataset with ID ${qe.yellow(n)} was changed from ${qe.yellow(a)} to ${qe.yellow(t)}.`:`The name of the dataset with ID ${qe.yellow(n)} has been set to: ${qe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),$({message:l,stdout:!0})}catch(m){let u=m;p({message:`Failed to rename dataset with ID ${qe.yellow(n)}
124
- ${u.message||u}`})}}};import Ys from"chalk";var go=class extends y{static name="rm";static description="Permanently removes a dataset.";static args={datasetNameOrId:w.string({description:"The dataset ID or name to delete",required:!0})};async run(){let{datasetNameOrId:e}=this.args,t=await C(),o=await xe(t,e);if(!o){p({message:`Dataset with ID or name "${e}" not found.`});return}if(!await z({message:"Are you sure you want to delete this Dataset?"})){b({message:"Dataset deletion has been aborted."});return}let{id:i,name:n}=o.dataset;try{await o.datasetClient.delete(),$({message:`Dataset with ID ${Ys.yellow(i)}${n?` (called ${Ys.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete dataset with ID ${Ys.yellow(i)}
125
- ${l.message||l}`})}}};var ho=class extends y{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[no,ao,uo,co,go,fo,po];async run(){this.printHelp()}};import{existsSync as Hs,mkdirSync as $m,readFileSync as _m,writeFileSync as Rm}from"fs";import{dirname as xm}from"path";import Om from"cors";import Nm from"detect-indent";import Js from"express";import Pm from"open";import{cryptoRandomObjectId as Lm}from"@apify/utilities";var ga="https://apify.github.io/input-schema-editor-react/",Dm=new URL(ga).origin,fa="v1",yo=class extends y{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 args={path:w.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 lt({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${j}' is not yet supported.`);x({message:`This command is still experimental and might break at any time. Use at your own risk.
126
- `}),b({message:`Editing input schema at "${t}"...`});let o,s=Js();s.use(Om({origin:Dm,allowedHeaders:["Content-Type","Authorization"]})),s.use((f,d,g)=>{d.set("Connection","close"),g()}),s.use(Js.json());let i=Lm();s.use((f,d,g)=>{let{token:h}=f.query;if(!h){let S=f.get("Authorization");if(S){let[I,v,...E]=S.trim().split(/\s+/);I.toLowerCase()==="bearer"&&v&&E.length===0&&(h=v)}}h!==i?(d.status(401),d.send("Authorization failed")):g()});let n=Js.Router();s.use(`/api/${fa}`,n);let a=" ",l=!0;n.get("/input-schema",(f,d)=>{let g;try{g=Hs(t)?_m(t,{encoding:"utf-8"}):`{}
122
+ `);_({message:J,stdout:!0})}};import ma from"chalk";var da=new G({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),mo=class extends y{static name="ls";static description="Prints all datasets on your account.";static flags={offset:A.integer({description:"Number of datasets that will be skipped.",default:0}),limit:A.integer({description:"Number of datasets that will be listed.",default:20}),desc:A.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:A.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await F(),l=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(l);return}if(l.count===0){v({message:"You don't have any Datasets on your account",stdout:!0});return}for(let m of l.items){let u=Reflect.get(m.stats,"s3StorageBytes");da.pushRow({"Dataset ID":m.id,Created:V.display(m.createdAt),Items:`${m.itemCount}`,Modified:V.display(m.modifiedAt),Name:m.name?`${a.username}/${m.name}`:"",Size:typeof u=="number"?X({bytes:u,shortBytes:!0,colorFunc:ma.gray,precision:0}):ma.gray("N/A")})}_({message:da.render(1),stdout:!0})}};import po from"chalk";var fo=class extends y{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static args={nameOrId:w.string({required:!0,description:"The dataset ID or name to push the objects to",ignoreStdin:!0}),item:w.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await C(),s=await Oe(o,e);if(!s){p({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,l=t||ve;if(!l){p({message:"No items were provided."});return}try{a=JSON.parse(l.toString("utf8"))}catch(u){p({message:`Failed to parse data as JSON string: ${u.message}`});return}if(Array.isArray(a)&&a.length===0){p({message:"No items were provided."});return}let m=n.name?`Dataset named ${po.yellow(n.name)} (${po.gray("ID:")} ${po.yellow(n.id)})`:`Dataset with ID ${po.yellow(n.id)}`;try{await i.pushItems(a),$({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${m} successfully.`})}catch(u){let f=u;p({message:`Failed to push items into ${m}
123
+ ${f.message||f}`})}}};import qe from"chalk";var go=class extends y{static name="rename";static description="Change dataset name or removes name with --unname flag.";static flags={unname:A.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:w.string({description:"The dataset ID or name to delete.",required:!0}),newName:w.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await Oe(s,o);if(!i){p({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,l=a?e?`The name of the dataset with ID ${qe.yellow(n)} has been removed (was ${qe.yellow(a)} previously).`:`The name of the dataset with ID ${qe.yellow(n)} was changed from ${qe.yellow(a)} to ${qe.yellow(t)}.`:`The name of the dataset with ID ${qe.yellow(n)} has been set to: ${qe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),$({message:l,stdout:!0})}catch(m){let u=m;p({message:`Failed to rename dataset with ID ${qe.yellow(n)}
124
+ ${u.message||u}`})}}};import Ys from"chalk";var ho=class extends y{static name="rm";static description="Permanently removes a dataset.";static args={datasetNameOrId:w.string({description:"The dataset ID or name to delete",required:!0})};async run(){let{datasetNameOrId:e}=this.args,t=await C(),o=await Oe(t,e);if(!o){p({message:`Dataset with ID or name "${e}" not found.`});return}if(!await z({message:"Are you sure you want to delete this Dataset?"})){v({message:"Dataset deletion has been aborted."});return}let{id:i,name:n}=o.dataset;try{await o.datasetClient.delete(),$({message:`Dataset with ID ${Ys.yellow(i)}${n?` (called ${Ys.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete dataset with ID ${Ys.yellow(i)}
125
+ ${l.message||l}`})}}};var yo=class extends y{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[ao,lo,mo,uo,ho,go,fo];async run(){this.printHelp()}};import{existsSync as Hs,mkdirSync as $m,readFileSync as Rm,writeFileSync as _m}from"fs";import{dirname as xm}from"path";import Om from"cors";import Nm from"detect-indent";import Js from"express";import Pm from"open";import{cryptoRandomObjectId as Lm}from"@apify/utilities";var fa="https://apify.github.io/input-schema-editor-react/",Dm=new URL(fa).origin,pa="v1",wo=class extends y{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 args={path:w.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 lt({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${j}' is not yet supported.`);x({message:`This command is still experimental and might break at any time. Use at your own risk.
126
+ `}),v({message:`Editing input schema at "${t}"...`});let o,s=Js();s.use(Om({origin:Dm,allowedHeaders:["Content-Type","Authorization"]})),s.use((f,d,g)=>{d.set("Connection","close"),g()}),s.use(Js.json());let i=Lm();s.use((f,d,g)=>{let{token:h}=f.query;if(!h){let S=f.get("Authorization");if(S){let[b,T,...E]=S.trim().split(/\s+/);b.toLowerCase()==="bearer"&&T&&E.length===0&&(h=T)}}h!==i?(d.status(401),d.send("Authorization failed")):g()});let n=Js.Router();s.use(`/api/${pa}`,n);let a=" ",l=!0;n.get("/input-schema",(f,d)=>{let g;try{g=Hs(t)?Rm(t,{encoding:"utf-8"}):`{}
127
127
  `,g.length>3&&(a=Nm(g).indent||a),g&&(l=g[g.length-1]===`
128
- `),Hs(t)?b({message:`Input schema loaded from "${t}"`}):b({message:"Empty input schema initialized."})}catch(S){let I=`Reading input schema from disk failed with: ${S.message}`;p({message:I}),d.status(500),d.send(I);return}let h;try{h=JSON.parse(g||"{}")}catch(S){let I=`Parsing input schema failed with error: ${S.message}`;p({message:I}),d.status(500),d.send(I);return}d.send(h),b({message:"Input schema sent to editor."})}),n.post("/input-schema",(f,d)=>{try{b({message:"Got input schema from editor..."});let g=f.body,h=JSON.stringify(g,null,a);l&&(h+=`
129
- `);let S=xm(t);Hs(S)||$m(S,{recursive:!0}),Rm(t,h,{encoding:"utf-8",flag:"w+"}),d.end(),b({message:"Input schema saved to disk."})}catch(g){let h=`Saving input schema failed with error: ${g.message}`;p({message:h}),d.status(500),d.send(h)}}),n.post("/exit",(f,d)=>{f.body.isWindowClosed?b({message:"Editor closed, finishing..."}):b({message:"Editing finished, you can close the editor."}),d.end(),o.close(()=>$({message:"Done."}))}),o=s.listen(0);let{port:m}=o.address();b({message:`Listening for messages from input schema editor on port ${m}...`});let u=`${ga}?localCliPort=${m}&localCliToken=${i}&localCliApiVersion=${fa}`;b({message:`Opening input schema editor at "${u}"...`}),await Pm(u)}};import wo from"chalk";var Wt=class extends y{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:w.string({required:!1,description:"The command to get help for.",catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith("help")){let i=_r(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=q.get(t);if(!o){let i=Nr(t),n=wo.gray(`Command ${wo.whiteBright(e)} not found`);i.length&&(n+=`
130
- `,n+=wo.gray(`Did you mean: ${i.map(a=>wo.whiteBright(a)).join(", ")}?`)),p({message:n});return}let s=Er(o);console.log(s)}};import ha from"chalk";var Ao=class extends y{static name="info";static description="Prints details about your currently authenticated Apify account.";async run(){await C();let e=await D();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${ha.gray(o)}: ${ha.bold(t[o])}`)}}};import{basename as zm}from"path";import zs from"process";import{appendFileSync as Fm,copyFileSync as km,createWriteStream as Um,existsSync as Ks,mkdirSync as Mm,readFileSync as ya,rmSync as jm,writeFileSync as Vm}from"fs";import{basename as Bm,join as qs,relative as wa,sep as Ws}from"path";import{fileURLToPath as Gm}from"url";import Ym from"@root/walk";import Hm from"configparser";import Jm from"handlebars";import{fetchManifest as Km,wrapperManifestUrl as qm}from"@apify/actor-templates";var Wm=[".dockerignore",".gitignore"],So=Gm(new URL("./templates/python-scrapy",import.meta.url));async function Aa(r,e,t={bindings:{}}){await Ym.walk(r,async(o,s,i)=>{if(s===r)return;let n=wa(r,s),a=n.split(Ws).map(m=>{if(m.startsWith("{")&&m.endsWith("}")){m=m.replace("{","").replace("}","");let u=t.bindings[m];if(!u)throw new Error(`Binding for ${m} not found.`);return u}return m}).join(Ws),l=qs(e,a);if(i.isDirectory())return Ks(l)||Mm(l),Aa(s,l);n.includes(".template")?Vm(qs(e,a.replace(".template","")),Jm.compile(ya(s,"utf8"))(t.bindings)):Ks(l)&&Wm.includes(Bm(a))?Fm(l,ya(s)):km(s,l)})}c(Aa,"merge");async function bo({projectPath:r}){r||(r=".");let e=new ot(r);if(e.configuration.hasSection("apify"))throw new Error("The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?");await e.init();let t=await Je({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((m,u)=>({name:`${m.class_name} (${m.pathname})`,value:u}))});function o(m){return`.${wa(r,m).split(Ws).slice(1).join(".").replace(".py","")}`}c(o,"translatePathToRelativeModuleName");let s={botName:xi(e.settings.BOT_NAME),scrapy_settings_module:e.configuration.get("settings","default"),apify_module_path:`${e.settings.BOT_NAME}.apify`,spider_class_name:e.getAvailableSpiders()[t].class_name,spider_module_name:`${o(e.getAvailableSpiders()[t].pathname)}`,projectFolder:e.settings.BOT_NAME},i=await Km(qm);b({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:m})=>m==="python-scrapy");Ks(So)&&jm(So,{recursive:!0}),await pr({url:n,pathTo:So}),b({message:"Wrapping the Scrapy project..."}),await Aa(So,r,{bindings:s});let a=new Hm;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let l=Um(qs(r,"scrapy.cfg"),{flags:"a"});await new Promise(m=>{l.on("open",u=>{l.write(`
131
- `,()=>{a.write(u),m()})})}),$({message:"The Scrapy project has been wrapped successfully."})}c(bo,"wrapScrapyProject");var vo=class extends y{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
128
+ `),Hs(t)?v({message:`Input schema loaded from "${t}"`}):v({message:"Empty input schema initialized."})}catch(S){let b=`Reading input schema from disk failed with: ${S.message}`;p({message:b}),d.status(500),d.send(b);return}let h;try{h=JSON.parse(g||"{}")}catch(S){let b=`Parsing input schema failed with error: ${S.message}`;p({message:b}),d.status(500),d.send(b);return}d.send(h),v({message:"Input schema sent to editor."})}),n.post("/input-schema",(f,d)=>{try{v({message:"Got input schema from editor..."});let g=f.body,h=JSON.stringify(g,null,a);l&&(h+=`
129
+ `);let S=xm(t);Hs(S)||$m(S,{recursive:!0}),_m(t,h,{encoding:"utf-8",flag:"w+"}),d.end(),v({message:"Input schema saved to disk."})}catch(g){let h=`Saving input schema failed with error: ${g.message}`;p({message:h}),d.status(500),d.send(h)}}),n.post("/exit",(f,d)=>{f.body.isWindowClosed?v({message:"Editor closed, finishing..."}):v({message:"Editing finished, you can close the editor."}),d.end(),o.close(()=>$({message:"Done."}))}),o=s.listen(0);let{port:m}=o.address();v({message:`Listening for messages from input schema editor on port ${m}...`});let u=`${fa}?localCliPort=${m}&localCliToken=${i}&localCliApiVersion=${pa}`;v({message:`Opening input schema editor at "${u}"...`}),await Pm(u)}};import Ao from"chalk";var zt=class extends y{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:w.string({required:!1,description:"The command to get help for.",catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith("help")){let i=_r(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=q.get(t);if(!o){let i=Pr(t),n=Ao.gray(`Command ${Ao.whiteBright(e)} not found`);i.length&&(n+=`
130
+ `,n+=Ao.gray(`Did you mean: ${i.map(a=>Ao.whiteBright(a)).join(", ")}?`)),p({message:n});return}let s=$r(o);console.log(s)}};import ga from"chalk";var So=class extends y{static name="info";static description="Prints details about your currently authenticated Apify account.";async run(){await C();let e=await F();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${ga.gray(o)}: ${ga.bold(t[o])}`)}}};import{basename as zm}from"path";import zs from"process";import{appendFileSync as Fm,copyFileSync as km,createWriteStream as Um,existsSync as Ks,mkdirSync as Mm,readFileSync as ha,rmSync as jm,writeFileSync as Vm}from"fs";import{basename as Bm,join as qs,relative as ya,sep as Ws}from"path";import{fileURLToPath as Gm}from"url";import Ym from"@root/walk";import Hm from"configparser";import Jm from"handlebars";import{fetchManifest as Km,wrapperManifestUrl as qm}from"@apify/actor-templates";var Wm=[".dockerignore",".gitignore"],bo=Gm(new URL("./templates/python-scrapy",import.meta.url));async function wa(r,e,t={bindings:{}}){await Ym.walk(r,async(o,s,i)=>{if(s===r)return;let n=ya(r,s),a=n.split(Ws).map(m=>{if(m.startsWith("{")&&m.endsWith("}")){m=m.replace("{","").replace("}","");let u=t.bindings[m];if(!u)throw new Error(`Binding for ${m} not found.`);return u}return m}).join(Ws),l=qs(e,a);if(i.isDirectory())return Ks(l)||Mm(l),wa(s,l);n.includes(".template")?Vm(qs(e,a.replace(".template","")),Jm.compile(ha(s,"utf8"))(t.bindings)):Ks(l)&&Wm.includes(Bm(a))?Fm(l,ha(s)):km(s,l)})}c(wa,"merge");async function vo({projectPath:r}){r||(r=".");let e=new ot(r);if(e.configuration.hasSection("apify"))throw new Error("The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?");await e.init();let t=await Je({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((m,u)=>({name:`${m.class_name} (${m.pathname})`,value:u}))});function o(m){return`.${ya(r,m).split(Ws).slice(1).join(".").replace(".py","")}`}c(o,"translatePathToRelativeModuleName");let s={botName:xi(e.settings.BOT_NAME),scrapy_settings_module:e.configuration.get("settings","default"),apify_module_path:`${e.settings.BOT_NAME}.apify`,spider_class_name:e.getAvailableSpiders()[t].class_name,spider_module_name:`${o(e.getAvailableSpiders()[t].pathname)}`,projectFolder:e.settings.BOT_NAME},i=await Km(qm);v({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:m})=>m==="python-scrapy");Ks(bo)&&jm(bo,{recursive:!0}),await fr({url:n,pathTo:bo}),v({message:"Wrapping the Scrapy project..."}),await wa(bo,r,{bindings:s});let a=new Hm;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let l=Um(qs(r,"scrapy.cfg"),{flags:"a"});await new Promise(m=>{l.on("open",u=>{l.write(`
131
+ `,()=>{a.write(u),m()})})}),$({message:"The Scrapy project has been wrapped successfully."})}c(vo,"wrapScrapyProject");var To=class extends y{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
132
132
  If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
133
133
  Creates the '${j}' file and the '${Ze}' directory in the current directory, but does not touch any other existing files or directories.
134
134
 
135
- WARNING: Overwrites existing '${Ze}' directory.`;static args={actorName:w.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:A.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts. Note that in some cases, the command may still ask for confirmation.',required:!1})};async run(){let{actorName:e}=this.args,t=zs.cwd(),o=await Me();o.isErr()&&(p({message:o.unwrapErr().message}),zs.exit(1));let s=o.unwrap();if(s.type===2)return b({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",bo({projectPath:t});if(!this.flags.yes&&s.type===3&&(x({message:"The current directory does not look like a Node.js or Python project."}),!await z({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let i=await Ye({cwd:t});if(i.isOkAnd(n=>n.exists&&!n.migrated))x({message:`Skipping creation of '${j}', the file already exists in the current directory.`});else{if(i.isErr()){p({message:i.unwrapErr().message}),zs.exitCode=5;return}if(!e){let a=i.isOkAnd(l=>l.exists)?i.unwrap().config.name:null;for(;!a;)try{let l=await rt({message:"Actor name:",default:zm(t)});Lt(l),a=l}catch(l){p({message:l.message})}e=a}let n={...tr,...i.unwrap().config};await cr(Object.assign(n,{name:e}),t)}await ur(t),await so(t),$({message:"The Actor has been initialized in the current directory."})}};var To=class extends y{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
135
+ WARNING: Overwrites existing '${Ze}' directory.`;static args={actorName:w.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:A.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts. Note that in some cases, the command may still ask for confirmation.',required:!1})};async run(){let{actorName:e}=this.args,t=zs.cwd(),o=await Me();o.isErr()&&(p({message:o.unwrapErr().message}),zs.exit(1));let s=o.unwrap();if(s.type===2)return v({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",vo({projectPath:t});if(!this.flags.yes&&s.type===3&&(x({message:"The current directory does not look like a Node.js or Python project."}),!await z({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let i=await Ye({cwd:t});if(i.isOkAnd(n=>n.exists&&!n.migrated))x({message:`Skipping creation of '${j}', the file already exists in the current directory.`});else{if(i.isErr()){p({message:i.unwrapErr().message}),zs.exitCode=5;return}if(!e){let a=i.isOkAnd(l=>l.exists)?i.unwrap().config.name:null;for(;!a;)try{let l=await rt({message:"Actor name:",default:zm(t)});Dt(l),a=l}catch(l){p({message:l.message})}e=a}let n={...rr,...i.unwrap().config};await ur(Object.assign(n,{name:e}),t)}await mr(t),await io(t),$({message:"The Actor has been initialized in the current directory."})}};var Io=class extends y{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
136
136
 
137
137
  It adds the following features:
138
138
  - Automatic retry of failed requests
139
139
  - Automatic proxy rotation
140
140
  - Automatic user agent rotation
141
141
  ...
142
- `;static args={path:w.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await bo({projectPath:this.args.path}),b({message:"Scrapy project wrapped successfully."})}};import Sa from"chalk";var Io=class extends y{static name="create";static description="Creates a new key-value store on your account.";static args={"key-value store name":w.string({description:"Optional name for the key-value store",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await C();if(e&&await ee(t,e)){p({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){N(o);return}$({message:`Key-value store with ID ${Sa.yellow(o.id)}${e?` (called ${Sa.yellow(e)})`:""} was created.`,stdout:!0})}};import Xm from"chalk";var Co=class extends y{static name="delete-value";static description="Delete a value from a key-value store.";static args={"store id":w.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{storeId:e,itemKey:t}=this.args,o=await C(),s=await ee(o,e);if(!s){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(t)){p({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await z({message:"Are you sure you want to delete this record?"})){b({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await i.deleteRecord(t),b({message:`Record with key "${Xm.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(l){let m=l;p({message:`Failed to delete record with key "${t}" from the key-value store.
143
- ${m.message||m}`})}}};var Eo=class extends y{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static flags={"only-content-type":A.boolean({description:"Only return the content type of the specified key",default:!1})};static args={keyValueStoreId:w.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:o}=this.args,s=await C(),i=await ee(s,t);if(!i){p({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){p({message:`Item with key "${o}" not found in the key-value store.`});return}if(R({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:l}=a,m=[];for await(let f of l)m.push(f);let u=Buffer.concat(m).toString();try{let f=JSON.parse(u);R({message:JSON.stringify(f,null,2),stdout:!0})}catch{R({message:u,stdout:!0})}return}a.value.pipe(process.stdout)}};import k from"chalk";var ba=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),$o=class extends y{static name="info";static description="Shows information about a key-value store.";static args={storeId:w.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await ee(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(F=>F),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),l;if(a?.actorTaskId&&(l=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){N({...s,user:i,actor:n||null,run:a||null,task:l||null});return}let m=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,d=s.stats?.deleteCount||0,g=s.stats?.listCount||0,S=`Operations: ${[`${k.bold(u.toLocaleString("en-US"))} ${k.gray(this.pluralString(u,"read","reads"))}`,`${k.bold(f.toLocaleString("en-US"))} ${k.gray(this.pluralString(f,"write","writes"))}`,`${k.bold(d.toLocaleString("en-US"))} ${k.gray(this.pluralString(d,"delete","deletes"))}`,`${k.bold(g.toLocaleString("en-US"))} ${k.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let F=lo(i.plan);if(F){let te=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(m/1e9),ge=te*24*30,De=ge>1?`$${ge.toFixed(2)}`:`$${te.toFixed(3)}`;S+=`
144
- Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${k.gray(`${De} per month`)}`}}else S+=`
145
- Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${k.gray("$unknown per month")}`;let I=[`Store ID: ${k.bgGray(s.id)}`,`Name: ${s.name?k.bgGray(s.name):k.bold(k.italic("Unnamed"))}`,`Created: ${k.bold(V.display(s.createdAt))}`,`Modified: ${k.bold(V.display(s.modifiedAt))}`].join(`
146
- `),v=k.bold("\u2014");s.actRunId&&(a?v=k.bgBlue(a.id):v=k.italic(k.gray("Run removed")));let E=k.bold("\u2014");n&&(E=k.blue(n.title||n.name));let P=k.bold("\u2014");l&&(P=k.blue(l.title||l.name));let L=[`Run: ${v}`,`Actor: ${E}`,`Task: ${P}`].join(`
147
- `);ba.pushRow({Row1:I,Row2:L});let Y=ba.render(2).split(`
148
- `).map(F=>F.trim());Y.shift();let J=[`${k.bold(s.name||k.italic("Unnamed"))}`,`${k.gray(s.name?`${i.username}/${s.name}`:s.id)} ${k.gray("Owned by")} ${k.blue(i.username)}`,"",Y.join(`
142
+ `;static args={path:w.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await vo({projectPath:this.args.path}),v({message:"Scrapy project wrapped successfully."})}};import Aa from"chalk";var Co=class extends y{static name="create";static description="Creates a new key-value store on your account.";static args={"key-value store name":w.string({description:"Optional name for the key-value store",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await C();if(e&&await te(t,e)){p({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){L(o);return}$({message:`Key-value store with ID ${Aa.yellow(o.id)}${e?` (called ${Aa.yellow(e)})`:""} was created.`,stdout:!0})}};import Xm from"chalk";var Eo=class extends y{static name="delete-value";static description="Delete a value from a key-value store.";static args={"store id":w.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{storeId:e,itemKey:t}=this.args,o=await C(),s=await te(o,e);if(!s){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(t)){p({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await z({message:"Are you sure you want to delete this record?"})){v({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await i.deleteRecord(t),v({message:`Record with key "${Xm.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(l){let m=l;p({message:`Failed to delete record with key "${t}" from the key-value store.
143
+ ${m.message||m}`})}}};var $o=class extends y{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static flags={"only-content-type":A.boolean({description:"Only return the content type of the specified key",default:!1})};static args={keyValueStoreId:w.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:o}=this.args,s=await C(),i=await te(s,t);if(!i){p({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){p({message:`Item with key "${o}" not found in the key-value store.`});return}if(_({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:l}=a,m=[];for await(let f of l)m.push(f);let u=Buffer.concat(m).toString();try{let f=JSON.parse(u);_({message:JSON.stringify(f,null,2),stdout:!0})}catch{_({message:u,stdout:!0})}return}a.value.pipe(process.stdout)}};import k from"chalk";var Sa=new G({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),Ro=class extends y{static name="info";static description="Shows information about a key-value store.";static args={storeId:w.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await te(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(D=>D),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),l;if(a?.actorTaskId&&(l=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){L({...s,user:i,actor:n||null,run:a||null,task:l||null});return}let m=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,d=s.stats?.deleteCount||0,g=s.stats?.listCount||0,S=`Operations: ${[`${k.bold(u.toLocaleString("en-US"))} ${k.gray(this.pluralString(u,"read","reads"))}`,`${k.bold(f.toLocaleString("en-US"))} ${k.gray(this.pluralString(f,"write","writes"))}`,`${k.bold(d.toLocaleString("en-US"))} ${k.gray(this.pluralString(d,"delete","deletes"))}`,`${k.bold(g.toLocaleString("en-US"))} ${k.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let D=co(i.plan);if(D){let Q=D.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(m/1e9),ge=Q*24*30,he=ge>1?`$${ge.toFixed(2)}`:`$${Q.toFixed(3)}`;S+=`
144
+ Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${k.gray(`${he} per month`)}`}}else S+=`
145
+ Storage size: ${X({bytes:m,shortBytes:!0,precision:1})} / ${k.gray("$unknown per month")}`;let b=[`Store ID: ${k.bgGray(s.id)}`,`Name: ${s.name?k.bgGray(s.name):k.bold(k.italic("Unnamed"))}`,`Created: ${k.bold(V.display(s.createdAt))}`,`Modified: ${k.bold(V.display(s.modifiedAt))}`].join(`
146
+ `),T=k.bold("\u2014");s.actRunId&&(a?T=k.bgBlue(a.id):T=k.italic(k.gray("Run removed")));let E=k.bold("\u2014");n&&(E=k.blue(n.title||n.name));let N=k.bold("\u2014");l&&(N=k.blue(l.title||l.name));let P=[`Run: ${T}`,`Actor: ${E}`,`Task: ${N}`].join(`
147
+ `);Sa.pushRow({Row1:b,Row2:P});let B=Sa.render(2).split(`
148
+ `).map(D=>D.trim());B.shift();let J=[`${k.bold(s.name||k.italic("Unnamed"))}`,`${k.gray(s.name?`${i.username}/${s.name}`:s.id)} ${k.gray("Owned by")} ${k.blue(i.username)}`,"",B.join(`
149
149
  `),"",S].join(`
150
- `);R({message:J,stdout:!0})}};var va=new B({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),_o=class extends y{static name="keys";static description="Lists all keys in a key-value store.";static flags={limit:A.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":A.string({description:"The key to start the list from."})};static args={storeId:w.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:o}=this.flags,s=await C(),i=await ee(s,e);if(!i){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:t,exclusiveStartKey:o});if(this.flags.json){N(a);return}for(let l of a.items)va.pushRow({Key:l.key,Size:X({bytes:l.size,shortBytes:!0,precision:0})});R({message:va.render(1),stdout:!0})}};import Ta from"chalk";var Ia=new B({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),Ro=class extends y{static name="ls";static description="Lists all key-value stores on your account.";static flags={offset:A.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:A.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:A.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:A.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await D(),l=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){N(l);return}if(l.count===0){b({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let m of l.items){let f=Reflect.get(m,"stats").s3StorageBytes;Ia.pushRow({"Store ID":m.id,Created:V.display(m.createdAt),Modified:V.display(m.modifiedAt),Name:m.name?`${a.username}/${m.name}`:"",Size:typeof f=="number"?X({bytes:f,shortBytes:!0,colorFunc:Ta.gray,precision:0}):Ta.gray("N/A")})}R({message:Ia.render(1),stdout:!0})}};import We from"chalk";var xo=class extends y{static name="rename";static description="Renames a key-value store, or removes its unique name.";static flags={unname:A.boolean({description:"Removes the unique name of the key-value store"})};static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0}),newName:w.string({description:"The new name for the key-value store"})};async run(){let{unname:e}=this.flags,{newName:t,keyValueStoreNameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await ee(s,o);if(!i){p({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,l=a?e?`The name of the key-value store with ID ${We.yellow(n)} has been removed (was ${We.yellow(a)} previously).`:`The name of the key-value store with ID ${We.yellow(n)} was changed from ${We.yellow(a)} to ${We.yellow(t)}.`:`The name of the key-value store with ID ${We.yellow(n)} has been set to: ${We.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),$({message:l,stdout:!0})}catch(m){let u=m;p({message:`Failed to rename key-value store with ID ${We.yellow(n)}
151
- ${u.message||u}`})}}};import Xs from"chalk";var Oo=class extends y{static name="rm";static description="Permanently removes a key-value store.";static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0})};async run(){let{keyValueStoreNameOrId:e}=this.args,t=await C(),o=await ee(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await z({message:"Are you sure you want to delete this Key-value store?"})){b({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),$({message:`Key-value store with ID ${Xs.yellow(i)}${n?` (called ${Xs.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete key-value store with ID ${Xs.yellow(i)}
152
- ${l.message||l}`})}}};var No=class extends y{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static flags={"content-type":A.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:w.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0}),value:w.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await C(),n=await ee(i,e);if(!n){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:t,value:o||process.stdin,contentType:s}),$({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(l){let m=l;p({message:`Failed to set value with key "${t}" in the key-value store.
153
- ${m.message||m}`})}}};var Po=class extends y{static name="key-value-stores";static description=`Manages persistent key-value storage.
150
+ `);_({message:J,stdout:!0})}};var ba=new G({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),_o=class extends y{static name="keys";static description="Lists all keys in a key-value store.";static flags={limit:A.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":A.string({description:"The key to start the list from."})};static args={storeId:w.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:o}=this.flags,s=await C(),i=await te(s,e);if(!i){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:t,exclusiveStartKey:o});if(this.flags.json){L(a);return}for(let l of a.items)ba.pushRow({Key:l.key,Size:X({bytes:l.size,shortBytes:!0,precision:0})});_({message:ba.render(1),stdout:!0})}};import va from"chalk";var Ta=new G({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),xo=class extends y{static name="ls";static description="Lists all key-value stores on your account.";static flags={offset:A.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:A.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:A.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:A.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await F(),l=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){L(l);return}if(l.count===0){v({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let m of l.items){let f=Reflect.get(m,"stats").s3StorageBytes;Ta.pushRow({"Store ID":m.id,Created:V.display(m.createdAt),Modified:V.display(m.modifiedAt),Name:m.name?`${a.username}/${m.name}`:"",Size:typeof f=="number"?X({bytes:f,shortBytes:!0,colorFunc:va.gray,precision:0}):va.gray("N/A")})}_({message:Ta.render(1),stdout:!0})}};import We from"chalk";var Oo=class extends y{static name="rename";static description="Renames a key-value store, or removes its unique name.";static flags={unname:A.boolean({description:"Removes the unique name of the key-value store"})};static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0}),newName:w.string({description:"The new name for the key-value store"})};async run(){let{unname:e}=this.flags,{newName:t,keyValueStoreNameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await te(s,o);if(!i){p({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,l=a?e?`The name of the key-value store with ID ${We.yellow(n)} has been removed (was ${We.yellow(a)} previously).`:`The name of the key-value store with ID ${We.yellow(n)} was changed from ${We.yellow(a)} to ${We.yellow(t)}.`:`The name of the key-value store with ID ${We.yellow(n)} has been set to: ${We.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),$({message:l,stdout:!0})}catch(m){let u=m;p({message:`Failed to rename key-value store with ID ${We.yellow(n)}
151
+ ${u.message||u}`})}}};import Xs from"chalk";var No=class extends y{static name="rm";static description="Permanently removes a key-value store.";static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0})};async run(){let{keyValueStoreNameOrId:e}=this.args,t=await C(),o=await te(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await z({message:"Are you sure you want to delete this Key-value store?"})){v({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),$({message:`Key-value store with ID ${Xs.yellow(i)}${n?` (called ${Xs.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let l=a;p({message:`Failed to delete key-value store with ID ${Xs.yellow(i)}
152
+ ${l.message||l}`})}}};var Po=class extends y{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static flags={"content-type":A.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:w.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0}),value:w.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await C(),n=await te(i,e);if(!n){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:t,value:o||process.stdin,contentType:s}),$({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(l){let m=l;p({message:`Failed to set value with key "${t}" in the key-value store.
153
+ ${m.message||m}`})}}};var Lo=class extends y{static name="key-value-stores";static description=`Manages persistent key-value storage.
154
154
 
155
- Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[Io,Co,Eo,$o,_o,Ro,xo,Oo,No];async run(){this.printHelp()}};import Qm from"chalk";import ed from"computer-name";import td from"cors";import Zs from"express";import rd from"open";import{cryptoRandomObjectId as od}from"@apify/utilities";import Zm from"@inquirer/password";var Ca=$e(async({message:r,mask:e})=>await Zm({message:r,mask:e??"*"}));var ei="https://console.apify.com/settings/integrations",sd=new URL(ei).origin,id=ei.includes("localhost")?"http://localhost:3333":void 0,Ea="v1",Qs=c(async r=>{let e=await Nt(r,id),t=await D();return e?(await hr(t.id),$({message:`You are logged in to Apify as ${t.username||t.id}. ${Qm.gray(`Your token is stored at ${ne()}.`)}`})):p({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Lo=class extends y{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ne()}'.
155
+ Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[Co,Eo,$o,Ro,_o,xo,Oo,No,Po];async run(){this.printHelp()}};import Qm from"chalk";import ed from"computer-name";import td from"cors";import Zs from"express";import rd from"open";import{cryptoRandomObjectId as od}from"@apify/utilities";import Zm from"@inquirer/password";var Ia=Re(async({message:r,mask:e})=>await Zm({message:r,mask:e??"*"}));var ei="https://console.apify.com/settings/integrations",sd=new URL(ei).origin,id=ei.includes("localhost")?"http://localhost:3333":void 0,Ca="v1",Qs=c(async r=>{let e=await Pt(r,id),t=await F();return e?(await yr(t.id),$({message:`You are logged in to Apify as ${t.username||t.id}. ${Qm.gray(`Your token is stored at ${ne()}.`)}`})):p({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Do=class extends y{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ne()}'.
156
156
  All other commands use these stored credentials.
157
157
 
158
- Run 'apify logout' to remove authentication.`;static flags={token:A.string({char:"t",description:"[Optional] Apify API token",required:!1}),method:A.string({char:"m",description:"[Optional] Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await Qs(e);return}let o=t;if(t||(o=await Je({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})),o==="console"){let s,i=Zs();i.use(td({origin:sd,allowedHeaders:["Content-Type","Authorization"]})),i.use((u,f,d)=>{f.set("Connection","close"),d()}),i.use(Zs.json());let n=od();i.use((u,f,d)=>{let{token:g}=u.query;if(!g){let h=u.get("Authorization");if(h){let[S,I,...v]=h.trim().split(/\s+/);S.toLowerCase()==="bearer"&&I&&v.length===0&&(g=I)}}g!==n?(f.status(401),f.send("Authorization failed")):d()});let a=Zs.Router();i.use(`/api/${Ea}`,a),a.post("/login-token",async(u,f)=>{try{if(u.body.apiToken)await Qs(u.body.apiToken);else throw new Error("Request did not contain API token");f.end()}catch(d){let g=`Login to Apify failed with error: ${d.message}`;p({message:g}),f.status(500),f.send(g)}s.close()}),a.post("/exit",(u,f)=>{u.body.isWindowClosed?p({message:"Login to Apify failed, the console window was closed."}):u.body.actionCanceled?p({message:"Login to Apify failed, the action was canceled in the Apify Console."}):p({message:"Login to Apify failed."}),f.end(),s.close()}),s=i.listen(0);let{port:l}=s.address(),m=new URL(ei);m.searchParams.set("localCliCommand","login"),m.searchParams.set("localCliPort",`${l}`),m.searchParams.set("localCliToken",n),m.searchParams.set("localCliApiVersion",Ea);try{m.searchParams.set("localCliComputerName",encodeURIComponent(ed()))}catch{}b({message:`Opening Apify Console at "${m.href}"...`}),await rd(m.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await Ca({message:"token:"});await Qs(s)}}};var Do=class extends y{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ne()}'.
159
- Run 'apify login' to authenticate again.`;async run(){await $t(ne()),await hr(null),$({message:"You are logged out from your Apify account."})}};var Fo=class extends Tt{static name="pull"};var ko=class extends It{static name="push"};var Uo=class extends y{static name="request-queues";static description="Manages URL queues for web scraping and automation tasks.";async run(){this.printHelp()}};import{existsSync as _a,renameSync as ud}from"fs";import{mkdir as Mo,readFile as md,stat as Ra,writeFile as Xt}from"fs/promises";import{dirname as jo,join as Vo}from"path";import Le from"process";import dd from"mime";import{minVersion as pd}from"semver";import{APIFY_ENV_VARS as Bo}from"@apify/consts";import{validateInputSchema as fd,validateInputUsingValidator as xa}from"@apify/input_schema";import{none as zt,some as nd}from"@sapphire/result";import{execa as ad}from"execa";var ti=c(r=>`
158
+ Run 'apify logout' to remove authentication.`;static flags={token:A.string({char:"t",description:"[Optional] Apify API token",required:!1}),method:A.string({char:"m",description:"[Optional] Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await Qs(e);return}let o=t;if(t||(o=await Je({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})),o==="console"){let s,i=Zs();i.use(td({origin:sd,allowedHeaders:["Content-Type","Authorization"]})),i.use((u,f,d)=>{f.set("Connection","close"),d()}),i.use(Zs.json());let n=od();i.use((u,f,d)=>{let{token:g}=u.query;if(!g){let h=u.get("Authorization");if(h){let[S,b,...T]=h.trim().split(/\s+/);S.toLowerCase()==="bearer"&&b&&T.length===0&&(g=b)}}g!==n?(f.status(401),f.send("Authorization failed")):d()});let a=Zs.Router();i.use(`/api/${Ca}`,a),a.post("/login-token",async(u,f)=>{try{if(u.body.apiToken)await Qs(u.body.apiToken);else throw new Error("Request did not contain API token");f.end()}catch(d){let g=`Login to Apify failed with error: ${d.message}`;p({message:g}),f.status(500),f.send(g)}s.close()}),a.post("/exit",(u,f)=>{u.body.isWindowClosed?p({message:"Login to Apify failed, the console window was closed."}):u.body.actionCanceled?p({message:"Login to Apify failed, the action was canceled in the Apify Console."}):p({message:"Login to Apify failed."}),f.end(),s.close()}),s=i.listen(0);let{port:l}=s.address(),m=new URL(ei);m.searchParams.set("localCliCommand","login"),m.searchParams.set("localCliPort",`${l}`),m.searchParams.set("localCliToken",n),m.searchParams.set("localCliApiVersion",Ca);try{m.searchParams.set("localCliComputerName",encodeURIComponent(ed()))}catch{}v({message:`Opening Apify Console at "${m.href}"...`}),await rd(m.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await Ia({message:"token:"});await Qs(s)}}};var Fo=class extends y{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ne()}'.
159
+ Run 'apify login' to authenticate again.`;async run(){await Rt(ne()),await yr(null),$({message:"You are logged out from your Apify account."})}};var ko=class extends Tt{static name="pull"};var Uo=class extends It{static name="push"};var Mo=class extends y{static name="request-queues";static description="Manages URL queues for web scraping and automation tasks.";async run(){this.printHelp()}};import{existsSync as $a,renameSync as ud}from"fs";import{mkdir as jo,readFile as md,stat as Ra,writeFile as Zt}from"fs/promises";import{dirname as Vo,join as Bo}from"path";import De from"process";import dd from"mime";import{minVersion as pd}from"semver";import{APIFY_ENV_VARS as Go}from"@apify/consts";import{validateInputSchema as fd,validateInputUsingValidator as _a}from"@apify/input_schema";import{none as Xt,some as nd}from"@sapphire/result";import{execa as ad}from"execa";var ti=c(r=>`
160
160
  (async () => {
161
161
  const [nodeModule, process, path, fs] = await Promise.all([
162
162
  import('node:module'),
@@ -194,25 +194,25 @@ try:
194
194
  print(${r}.__version__)
195
195
  except:
196
196
  print('n/a')
197
- `,"pyScript"),cd={node(r){return["-e",`"${ti(r)}"`]},deno(r){return["eval",`"${ti(r)}"`]},bun(r){return["--eval",`"${ti(r)}"`]},python(r){return["-c",`"${ld(r)}"`]}};async function $a({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),zt;let t;if(e.type===0)t=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)t="python";else return T("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:r}),zt;let o=cd[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),zt;try{let s=await ad(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?(T("useModuleVersion",{status:"no_version_found",project:e,moduleName:r}),zt):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),nd(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),zt}}c($a,"useModuleVersion");var Go=class extends y{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
197
+ `,"pyScript"),cd={node(r){return["-e",`"${ti(r)}"`]},deno(r){return["eval",`"${ti(r)}"`]},bun(r){return["--eval",`"${ti(r)}"`]},python(r){return["-c",`"${ld(r)}"`]}};async function Ea({moduleName:r,project:e}){if(!e.runtime)return I("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),Xt;let t;if(e.type===0)t=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)t="python";else return I("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:r}),Xt;let o=cd[t]?.(r);if(!o)return I("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),Xt;try{let s=await ad(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?(I("useModuleVersion",{status:"no_version_found",project:e,moduleName:r}),Xt):(I("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),nd(s.stdout.trim()))}catch(s){return I("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),Xt}}c(Ea,"useModuleVersion");var Yo=class extends y{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
198
198
  Stores data in local '${Ze}' directory.
199
199
 
200
200
  NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static flags={purge:A.boolean({char:"p",description:"Whether to purge the default request queue, dataset and key-value store before the run starts.\nFor crawlee projects, this is the default behavior, and the flag is optional.\nUse `--no-purge` to keep the storage folder intact.",required:!1,default:!0,exclusive:["resurrect"]}),resurrect:A.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:A.string({description:["Optional entrypoint for running with injected environment variables.",`
201
201
  `,"For Python, it is the module name, or a path to a file.",`
202
- `,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};async run(){let e=Le.cwd(),{proxy:t,id:o,token:s}=await D(),i=await Ye({cwd:e});if(i.isErr()){let{message:M,cause:Y}=i.unwrapErr();p({message:`${M}${Y?`
203
- ${Y.message}`:""}`}),Le.exitCode=5;return}let{config:n}=i.unwrap(),a=ce(),l=await Me({cwd:e});if(l.isErr()){p({message:l.unwrapErr().message}),Le.exitCode=5;return}let m=l.unwrap(),{type:u,entrypoint:f,runtime:d}=m;if(u===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!d){switch(u){case 0:p({message:`No Node.js detected! Please install Node.js ${ye} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:p({message:`No Python detected! Please install Python ${Qe} (or higher) to be able to run Python Actors locally.`});break;default:p({message:`No runtime detected! Make sure you have Python ${Qe} (or higher) or Node.js ${ye} (or higher) installed.`})}return}let g,h;if(this.flags.entrypoint){h=this.flags.entrypoint;let M=Vo(e,this.flags.entrypoint),Y=await Ra(M).catch(()=>null);Y?.isDirectory()?g=1:Y?.isFile()?g=0:g=2}else if(f?.script)g=2,h=f.script;else if(f?.path)g=u!==0?1:0,h=f.path;else{p({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}_a(us)&&!_a(a)&&(ud(us,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let S=await $a({moduleName:"crawlee",project:m}),I="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(I="1",S.isNone()&&(await Promise.all([Ei(),_i(),$i()]),b({message:"All default local stores were purged."}))),this.flags.purge||!await Ri()&&!this.flags.resurrect&&x({message:"The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory."});let v=await St(e,this.flags.input,this.flags.inputFile);if(v===!1)return;let E=await this.validateAndStoreInput(v),P={[Bo.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:I};if(t&&t.password&&(P[Bo.PROXY_PASSWORD]=t.password),o&&(P[Bo.USER_ID]=o),s&&(P[Bo.TOKEN]=s),n.environmentVariables){let M=jn(n.environmentVariables);Object.assign(P,M)}let L=Object.assign(P,Le.env);o||x({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(u){case 0:{let M=pd(ye);if(dr(d.version)?L.NODE_OPTIONS=L.NODE_OPTIONS?`${L.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":x({message:`You are running Node.js version ${d.version}, which is no longer supported. Please upgrade to Node.js version ${M} or later.`}),g===0||g===1)await pe({cmd:d.executablePath,args:[h],opts:{env:L,cwd:e}});else{let Y=await md(Vo(e,"package.json"),"utf8").catch(()=>"{}"),J=JSON.parse(Y);if(!J.scripts)throw new Error('No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".');if(!J.scripts[h])throw new Error(`The script "${h}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!d.pmPath)throw new Error("No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.");await pe({cmd:d.pmPath,args:["run",h],opts:{env:L,cwd:e},overrideCommand:d.pmName})}break}case 1:case 2:{if(!mr(d.version)){p({message:`Python Actors require Python 3.9 or higher, but you have Python ${d.version}!`}),p({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await pe({cmd:d.executablePath,args:["-m",h],opts:{env:L,cwd:e}}):await pe({cmd:d.executablePath,args:[h],opts:{env:L,cwd:e}});break}default:p({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(M){let{stderr:Y}=M}finally{if(E)if(E.existingInput){let M=await Ra(E.inputFilePath);if(Math.trunc(M.mtimeMs)-E.writtenAt>=5){x({message:`The "${E.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await Xt(E.inputFilePath,E.existingInput.body)}else await _t(E.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await lt({cwd:Le.cwd()});if(!t){if(!e)return null;let m=Pt(Le.cwd()),u=Vo(Le.cwd(),Ie(),m?.fileName??"INPUT.json");return await Mo(jo(u),{recursive:!0}),await Xt(u,JSON.stringify(e.input,null,2)),{existingInput:m,inputFilePath:u,writtenAt:Date.now()}}let o=new mt({strict:!1,unicodeRegExp:!1});fd(o,t);let s=ia(t),i=na(t,o),n=Pt(Le.cwd()),a=Vo(Le.cwd(),Ie(),n?.fileName??"INPUT.json"),l;switch(e?.source){case"stdin":l=`The input provided through standard input is invalid. Please fix the following errors:
202
+ `,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};async run(){let e=De.cwd(),{proxy:t,id:o,token:s}=await F(),i=await Ye({cwd:e});if(i.isErr()){let{message:M,cause:B}=i.unwrapErr();p({message:`${M}${B?`
203
+ ${B.message}`:""}`}),De.exitCode=5;return}let{config:n}=i.unwrap(),a=ce(),l=await Me({cwd:e});if(l.isErr()){p({message:l.unwrapErr().message}),De.exitCode=5;return}let m=l.unwrap(),{type:u,entrypoint:f,runtime:d}=m;if(u===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!d){switch(u){case 0:p({message:`No Node.js detected! Please install Node.js ${we} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:p({message:`No Python detected! Please install Python ${Qe} (or higher) to be able to run Python Actors locally.`});break;default:p({message:`No runtime detected! Make sure you have Python ${Qe} (or higher) or Node.js ${we} (or higher) installed.`})}return}let g,h;if(this.flags.entrypoint){h=this.flags.entrypoint;let M=Bo(e,this.flags.entrypoint),B=await Ra(M).catch(()=>null);B?.isDirectory()?g=1:B?.isFile()?g=0:g=2}else if(f?.script)g=2,h=f.script;else if(f?.path)g=u!==0?1:0,h=f.path;else{p({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}$a(us)&&!$a(a)&&(ud(us,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let S=await Ea({moduleName:"crawlee",project:m}),b="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(b="1",S.isNone()&&(await Promise.all([Ei(),Ri(),$i()]),v({message:"All default local stores were purged."}))),this.flags.purge||!await _i()&&!this.flags.resurrect&&x({message:"The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory."});let T=await St(e,this.flags.input,this.flags.inputFile);if(T===!1)return;let E=await this.validateAndStoreInput(T),N={[Go.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:b};if(t&&t.password&&(N[Go.PROXY_PASSWORD]=t.password),o&&(N[Go.USER_ID]=o),s&&(N[Go.TOKEN]=s),n.environmentVariables){let M=Mn(n.environmentVariables);Object.assign(N,M)}let P=Object.assign(N,De.env);o||x({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(u){case 0:{let M=pd(we);if(pr(d.version)?P.NODE_OPTIONS=P.NODE_OPTIONS?`${P.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":x({message:`You are running Node.js version ${d.version}, which is no longer supported. Please upgrade to Node.js version ${M} or later.`}),g===0||g===1)await pe({cmd:d.executablePath,args:[h],opts:{env:P,cwd:e}});else{let B=await md(Bo(e,"package.json"),"utf8").catch(()=>"{}"),J=JSON.parse(B);if(!J.scripts)throw new Error('No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".');if(!J.scripts[h])throw new Error(`The script "${h}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!d.pmPath)throw new Error("No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.");await pe({cmd:d.pmPath,args:["run",h],opts:{env:P,cwd:e},overrideCommand:d.pmName})}break}case 1:case 2:{if(!dr(d.version)){p({message:`Python Actors require Python 3.9 or higher, but you have Python ${d.version}!`}),p({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await pe({cmd:d.executablePath,args:["-m",h],opts:{env:P,cwd:e}}):await pe({cmd:d.executablePath,args:[h],opts:{env:P,cwd:e}});break}default:p({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(M){let{stderr:B}=M}finally{if(E)if(E.existingInput){let M=await Ra(E.inputFilePath);if(Math.trunc(M.mtimeMs)-E.writtenAt>=5){x({message:`The "${E.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await Zt(E.inputFilePath,E.existingInput.body)}else await _t(E.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await lt({cwd:De.cwd()});if(!t){if(!e)return null;let m=Lt(De.cwd()),u=Bo(De.cwd(),Ce(),m?.fileName??"INPUT.json");return await jo(Vo(u),{recursive:!0}),await Zt(u,JSON.stringify(e.input,null,2)),{existingInput:m,inputFilePath:u,writtenAt:Date.now()}}let o=new mt({strict:!1,unicodeRegExp:!1});fd(o,t);let s=sa(t),i=ia(t,o),n=Lt(De.cwd()),a=Bo(De.cwd(),Ce(),n?.fileName??"INPUT.json"),l;switch(e?.source){case"stdin":l=`The input provided through standard input is invalid. Please fix the following errors:
204
204
  `;break;case"input":l=`The input provided through the --input flag is invalid. Please fix the following errors:
205
205
  `;break;default:e?l=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
206
206
  `:l=`The input in your storage is invalid. Please fix the following errors:
207
- `;break}if(e){let m={...s,...e.input},u=xa(i,t,m);if(u.length>0)throw new Error(`${l}${u.map(f=>` - ${f.message.replace("Field input.","Field ")}`).join(`
208
- `)}`);return await Mo(jo(a),{recursive:!0}),await Xt(a,JSON.stringify(m,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await Mo(jo(a),{recursive:!0}),await Xt(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(dd.getExtension(n.contentType)==="json"){let m=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(m))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let u={...s,...m},f=xa(i,t,u);if(f.length>0)throw new Error(`${l}${f.map(d=>` - ${d.message.replace("Field input.","Field ")}`).join(`
209
- `)}`);return await Mo(jo(a),{recursive:!0}),await Xt(a,JSON.stringify(u,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as Yo}from"@apify/consts";var gd=[Yo.READY,Yo.RUNNING],hd=[Yo.ABORTING,Yo.TIMING_OUT],Ho=class extends y{static name="abort";static description="Aborts an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to abort."})};static flags={force:A.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 C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!gd.includes(o.status)){hd.includes(o.status)?p({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):p({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){N(s);return}this.flags.force?$({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):$({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to abort run "${e}".
210
- ${i.message||i}`,stdout:!0})}}};import _ from"chalk";var Zt=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Oa={"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"},Jo=class extends y{static name="info";static description="Prints information about an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:A.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,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,l]=await Promise.all([t.actor(o.actId).get(),t.build(o.buildId).get(),o.actorTaskId?t.task(o.actorTaskId).get():Promise.resolve(void 0),t.dataset(o.defaultDatasetId).get(),t.requestQueue(o.defaultRequestQueueId).get()]);if(this.flags.json){N({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:l});return}this.addDetailedUsage(o);let m=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",u=[`${_.yellow("Actor")}: ${m} (${_.grey(o.actId)})`];n?u.push(`\u2514\u2500 ${_.yellow("Task")}: ${n.title??n.name} (${_.gray(o.actorTaskId)})`,""):o.actorTaskId?u.push(`\u2514\u2500 ${_.yellow("Task")}: unknown-task (${_.gray(o.actorTaskId)})`,""):u.push("");let f=` (exit code: ${_.gray(o.exitCode!==null?o.exitCode:"N/A")})`;u.push(`${_.yellow("Status")}: ${Te(o.status)}${f}`),o.statusMessage&&u.push(`\u2514\u2500 ${_.yellow("Status Message:")} ${o.statusMessage}`);let d=a?.itemCount??0;u.push(`${_.yellow("Results")}: ${_.cyan(d.toLocaleString("en-US"))}`),l?u.push(`${_.yellow("Requests")}: ${_.cyan(l.handledRequestCount.toLocaleString("en-US"))} out of ${_.cyan(l.totalRequestCount.toLocaleString("en-US"))} handled`):u.push(`${_.yellow("Requests")}: ${_.gray("unknown handled")}`);let g=this.flags.verbose?"":_.gray(` (run with ${_.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?u.push(`${_.yellow("Usage")}: ${_.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):u.push(`${_.yellow("Usage")}: $${_.gray("0.000")}${g}`),this.flags.verbose&&u.push(Zt.render(0)),u.push(""),u.push(`${_.yellow("Started")}: ${V.display(o.startedAt)}`),o.finishedAt)u.push(`${_.yellow("Finished")}: ${V.display(o.finishedAt)} (took ${_.gray(se.format(o.stats.durationMillis))})`);else{let v=Date.now()-o.startedAt.getTime();u.push(`${_.yellow("Finished")}: ${_.gray(`Running for ${se.format(v)}`)}`)}if(u.push(""),o.stats.resurrectCount?u.push(`${_.yellow("Resurrected")}: Yes, ${_.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):u.push(`${_.yellow("Resurrected")}: No`),o.containerUrl&&u.push(`${_.yellow("Container URL")}: ${_.blue(o.containerUrl)}`),u.push(`${_.yellow("Origin")}: ${o.meta.origin}`),s){let v=o.buildNumber.split(".").slice(0,2).join("."),E=s.versions.find(M=>M.versionNumber===v),P=Object.entries(s.taggedBuilds??{}).find(([,M])=>M.buildNumber===o.buildNumber)?.[0],L=[`${_.yellow("Build")}:`,_.cyan(o.buildNumber)];P?L.push(`(${_.yellow(P)})`):L.push(`(${_.gray("N/A")})`),E&&L.push(`| ${_.gray("Actor version:")} ${_.cyan(E.versionNumber)} (${_.yellow(E.buildTag)})`),u.push(L.join(" "))}else u.push(`${_.yellow("Build")}: ${_.cyan(o.buildNumber)}`);u.push(`${_.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),u.push(`${_.yellow("Memory")}: ${o.options.memoryMbytes} MB`),u.push(""),u.push(`${_.yellow("CPU")}: ${_.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${_.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),u.push(`${_.yellow("Memory")}: ${_.gray("Average:")} ${X({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${_.gray("Maximum:")} ${X({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),u.push("");let h=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,S=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,I=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;u.push(`${_.blue("Export results")}: ${S}`),u.push(`${_.blue("View saved items")}: ${I}`),u.push(`${_.blue("View in Apify Console")}: ${h}`),R({message:u.join(`
211
- `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(Oa))Zt.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Oa)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{Zt.pushRow({"":s,Unit:n.toFixed(4),"USD Amount":this.formatUsd(a)});break}case"DATA_TRANSFER_INTERNAL_GBYTES":case"DATA_TRANSFER_EXTERNAL_GBYTES":case"PROXY_RESIDENTIAL_TRANSFER_GBYTES":{Zt.pushRow({"":s,Unit:X({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:Zt.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var Ko=class extends y{static name="log";static description="Prints the log of a specific run.";static args={runId:w.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for run with ID "${e}":
212
- `,stdout:!0});try{await Ee({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import fe from"chalk";var Na=new B({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"}}),qo=class extends y{static name="ls";static description="Lists all runs of the Actor.";static flags={offset:A.integer({description:"Number of runs that will be skipped.",default:0}),limit:A.integer({description:"Number of runs that will be listed.",default:10}),desc:A.boolean({description:"Sort runs in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),l=await Ve({providedActorNameOrId:n,client:a});if(!l.valid){p({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let m=await a.actor(l.id).runs().list({desc:e,limit:t,offset:o});if(i){N(m);return}if(!m.items.length){R({message:"There are no recent runs found for this Actor."});return}let u=[`${fe.reset("Showing")} ${fe.yellow(m.items.length)} out of ${fe.yellow(m.total)} runs for Actor ${fe.yellow(l.userFriendlyId)} (${fe.gray(l.id)})`],f=new Map(await Promise.all(m.items.map(async d=>a.dataset(d.defaultDatasetId).get().then(g=>[d.id,fe.yellow(g?.itemCount??0)],()=>[d.id,fe.gray("N/A")]))));for(let d of m.items){let g;if(d.finishedAt){let h=d.finishedAt.getTime()-d.startedAt.getTime();g=fe.gray(`${se.format(h,void 0,{left:""})}`)}else{let h=Date.now()-d.startedAt.getTime();g=fe.gray(`Running for ${se.format(h,void 0,{left:""})}`)}Na.pushRow({ID:fe.gray(d.id),Status:Te(d.status),Results:f.get(d.id)||fe.gray("N/A"),Usage:fe.cyan(`$${(d.usageTotalUsd??0).toFixed(3)}`),"Started At":Dt.display(d.startedAt),Took:g,"Build No.":d.buildNumber,Origin:d.meta.origin??"UNKNOWN"})}u.push(Na.render(s?0:1)),R({message:u.join(`
213
- `),stdout:!0})}};import{ACTOR_JOB_STATUSES as Wo}from"@apify/consts";var yd=[Wo.SUCCEEDED,Wo.FAILED,Wo.ABORTED,Wo.TIMED_OUT],zo=class extends y{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static args={runId:w.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!yd.includes(o.status)){p({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await t.run(e).resurrect();if(this.flags.json){N(s);return}$({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to resurrect run "${e}".
214
- ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Xo}from"@apify/consts";var wd=[Xo.SUCCEEDED,Xo.FAILED,Xo.ABORTED,Xo.TIMED_OUT],Zo=class extends y{static name="rm";static description="Deletes an Actor Run.";static args={runId:w.string({description:"The run ID to delete.",required:!0})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}if(!wd.includes(o.status)){p({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await z({message:"Are you sure you want to delete this Actor Run?"})){b({message:`Deletion of run "${e}" was canceled.`});return}try{await t.run(e).delete(),$({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete run "${e}".
215
- ${n.message||n}`})}}};var Qo=class extends y{static name="runs";static description="Manages Actor run operations ";static subcommands=[Ho,Jo,Ko,qo,zo,Zo];async run(){this.printHelp()}};var es=class extends y{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static args={name:w.string({required:!0,description:"Name of the secret"}),value:w.string({required:!0,description:"Value of the secret"})};async run(){let{name:e,value:t}=this.args;kn(e,t)}};var ts=class extends y{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static args={name:w.string({required:!0,description:"Name of the secret"})};async run(){let{name:e}=this.args;Un(e)}};var rs=class extends y{static name="secrets";static description=`Manages secure environment variables for Actors.
207
+ `;break}if(e){let m={...s,...e.input},u=_a(i,t,m);if(u.length>0)throw new Error(`${l}${u.map(f=>` - ${f.message.replace("Field input.","Field ")}`).join(`
208
+ `)}`);return await jo(Vo(a),{recursive:!0}),await Zt(a,JSON.stringify(m,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await jo(Vo(a),{recursive:!0}),await Zt(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(dd.getExtension(n.contentType)==="json"){let m=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(m))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let u={...s,...m},f=_a(i,t,u);if(f.length>0)throw new Error(`${l}${f.map(d=>` - ${d.message.replace("Field input.","Field ")}`).join(`
209
+ `)}`);return await jo(Vo(a),{recursive:!0}),await Zt(a,JSON.stringify(u,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as Ho}from"@apify/consts";var gd=[Ho.READY,Ho.RUNNING],hd=[Ho.ABORTING,Ho.TIMING_OUT],Jo=class extends y{static name="abort";static description="Aborts an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to abort."})};static flags={force:A.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 C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!gd.includes(o.status)){hd.includes(o.status)?p({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):p({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){L(s);return}this.flags.force?$({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):$({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to abort run "${e}".
210
+ ${i.message||i}`,stdout:!0})}}};import R from"chalk";var Qt=new G({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),xa={"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"},Ko=class extends y{static name="info";static description="Prints information about an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:A.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,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,l]=await Promise.all([t.actor(o.actId).get(),t.build(o.buildId).get(),o.actorTaskId?t.task(o.actorTaskId).get():Promise.resolve(void 0),t.dataset(o.defaultDatasetId).get(),t.requestQueue(o.defaultRequestQueueId).get()]);if(this.flags.json){L({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:l});return}this.addDetailedUsage(o);let m=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",u=[`${R.yellow("Actor")}: ${m} (${R.grey(o.actId)})`];n?u.push(`\u2514\u2500 ${R.yellow("Task")}: ${n.title??n.name} (${R.gray(o.actorTaskId)})`,""):o.actorTaskId?u.push(`\u2514\u2500 ${R.yellow("Task")}: unknown-task (${R.gray(o.actorTaskId)})`,""):u.push("");let f=` (exit code: ${R.gray(o.exitCode!==null?o.exitCode:"N/A")})`;u.push(`${R.yellow("Status")}: ${Ie(o.status)}${f}`),o.statusMessage&&u.push(`\u2514\u2500 ${R.yellow("Status Message:")} ${o.statusMessage}`);let d=a?.itemCount??0;u.push(`${R.yellow("Results")}: ${R.cyan(d.toLocaleString("en-US"))}`),l?u.push(`${R.yellow("Requests")}: ${R.cyan(l.handledRequestCount.toLocaleString("en-US"))} out of ${R.cyan(l.totalRequestCount.toLocaleString("en-US"))} handled`):u.push(`${R.yellow("Requests")}: ${R.gray("unknown handled")}`);let g=this.flags.verbose?"":R.gray(` (run with ${R.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?u.push(`${R.yellow("Usage")}: ${R.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):u.push(`${R.yellow("Usage")}: $${R.gray("0.000")}${g}`),this.flags.verbose&&u.push(Qt.render(0)),u.push(""),u.push(`${R.yellow("Started")}: ${V.display(o.startedAt)}`),o.finishedAt)u.push(`${R.yellow("Finished")}: ${V.display(o.finishedAt)} (took ${R.gray(se.format(o.stats.durationMillis))})`);else{let T=Date.now()-o.startedAt.getTime();u.push(`${R.yellow("Finished")}: ${R.gray(`Running for ${se.format(T)}`)}`)}if(u.push(""),o.stats.resurrectCount?u.push(`${R.yellow("Resurrected")}: Yes, ${R.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):u.push(`${R.yellow("Resurrected")}: No`),o.containerUrl&&u.push(`${R.yellow("Container URL")}: ${R.blue(o.containerUrl)}`),u.push(`${R.yellow("Origin")}: ${o.meta.origin}`),s){let T=o.buildNumber.split(".").slice(0,2).join("."),E=s.versions.find(M=>M.versionNumber===T),N=Object.entries(s.taggedBuilds??{}).find(([,M])=>M.buildNumber===o.buildNumber)?.[0],P=[`${R.yellow("Build")}:`,R.cyan(o.buildNumber)];N?P.push(`(${R.yellow(N)})`):P.push(`(${R.gray("N/A")})`),E&&P.push(`| ${R.gray("Actor version:")} ${R.cyan(E.versionNumber)} (${R.yellow(E.buildTag)})`),u.push(P.join(" "))}else u.push(`${R.yellow("Build")}: ${R.cyan(o.buildNumber)}`);u.push(`${R.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),u.push(`${R.yellow("Memory")}: ${o.options.memoryMbytes} MB`),u.push(""),u.push(`${R.yellow("CPU")}: ${R.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${R.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),u.push(`${R.yellow("Memory")}: ${R.gray("Average:")} ${X({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${R.gray("Maximum:")} ${X({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),u.push("");let h=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,S=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,b=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;u.push(`${R.blue("Export results")}: ${S}`),u.push(`${R.blue("View saved items")}: ${b}`),u.push(`${R.blue("View in Apify Console")}: ${h}`),_({message:u.join(`
211
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(xa))Qt.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(xa)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{Qt.pushRow({"":s,Unit:n.toFixed(4),"USD Amount":this.formatUsd(a)});break}case"DATA_TRANSFER_INTERNAL_GBYTES":case"DATA_TRANSFER_EXTERNAL_GBYTES":case"PROXY_RESIDENTIAL_TRANSFER_GBYTES":{Qt.pushRow({"":s,Unit:X({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:Qt.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var qo=class extends y{static name="log";static description="Prints the log of a specific run.";static args={runId:w.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for run with ID "${e}":
212
+ `,stdout:!0});try{await $e({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import fe from"chalk";var Oa=new G({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"}}),Wo=class extends y{static name="ls";static description="Lists all runs of the Actor.";static flags={offset:A.integer({description:"Number of runs that will be skipped.",default:0}),limit:A.integer({description:"Number of runs that will be listed.",default:10}),desc:A.boolean({description:"Sort runs in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),l=await Ve({providedActorNameOrId:n,client:a});if(!l.valid){p({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let m=await a.actor(l.id).runs().list({desc:e,limit:t,offset:o});if(i){L(m);return}if(!m.items.length){_({message:"There are no recent runs found for this Actor."});return}let u=[`${fe.reset("Showing")} ${fe.yellow(m.items.length)} out of ${fe.yellow(m.total)} runs for Actor ${fe.yellow(l.userFriendlyId)} (${fe.gray(l.id)})`],f=new Map(await Promise.all(m.items.map(async d=>a.dataset(d.defaultDatasetId).get().then(g=>[d.id,fe.yellow(g?.itemCount??0)],()=>[d.id,fe.gray("N/A")]))));for(let d of m.items){let g;if(d.finishedAt){let h=d.finishedAt.getTime()-d.startedAt.getTime();g=fe.gray(`${se.format(h,void 0,{left:""})}`)}else{let h=Date.now()-d.startedAt.getTime();g=fe.gray(`Running for ${se.format(h,void 0,{left:""})}`)}Oa.pushRow({ID:fe.gray(d.id),Status:Ie(d.status),Results:f.get(d.id)||fe.gray("N/A"),Usage:fe.cyan(`$${(d.usageTotalUsd??0).toFixed(3)}`),"Started At":Ft.display(d.startedAt),Took:g,"Build No.":d.buildNumber,Origin:d.meta.origin??"UNKNOWN"})}u.push(Oa.render(s?0:1)),_({message:u.join(`
213
+ `),stdout:!0})}};import{ACTOR_JOB_STATUSES as zo}from"@apify/consts";var yd=[zo.SUCCEEDED,zo.FAILED,zo.ABORTED,zo.TIMED_OUT],Xo=class extends y{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static args={runId:w.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!yd.includes(o.status)){p({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await t.run(e).resurrect();if(this.flags.json){L(s);return}$({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to resurrect run "${e}".
214
+ ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Zo}from"@apify/consts";var wd=[Zo.SUCCEEDED,Zo.FAILED,Zo.ABORTED,Zo.TIMED_OUT],Qo=class extends y{static name="rm";static description="Deletes an Actor Run.";static args={runId:w.string({description:"The run ID to delete.",required:!0})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}if(!wd.includes(o.status)){p({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await z({message:"Are you sure you want to delete this Actor Run?"})){v({message:`Deletion of run "${e}" was canceled.`});return}try{await t.run(e).delete(),$({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete run "${e}".
215
+ ${n.message||n}`})}}};var es=class extends y{static name="runs";static description="Manages Actor run operations ";static subcommands=[Jo,Ko,qo,Wo,Xo,Qo];async run(){this.printHelp()}};var ts=class extends y{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static args={name:w.string({required:!0,description:"Name of the secret"}),value:w.string({required:!0,description:"Value of the secret"})};async run(){let{name:e,value:t}=this.args;Fn(e,t)}};var rs=class extends y{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static args={name:w.string({required:!0,description:"Name of the secret"})};async run(){let{name:e}=this.args;kn(e)}};var os=class extends y{static name="secrets";static description=`Manages secure environment variables for Actors.
216
216
 
217
217
  Example:
218
218
  $ apify secrets add mySecret TopSecretValue123
@@ -228,15 +228,15 @@ prefix:
228
228
  }
229
229
 
230
230
  When the Actor is pushed to Apify cloud, the "SECRET_ENV_VAR" and its value is stored as a secret environment variable
231
- of the Actor.`;static subcommands=[es,ts];async run(){this.printHelp()}};import Pa from"chalk";var os=class extends y{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
231
+ of the Actor.`;static subcommands=[ts,rs];async run(){this.printHelp()}};import Na from"chalk";var ss=class extends y{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
232
232
  Customize with --memory and --timeout flags.
233
- `;static flags=vt("Task");static args={taskId:w.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await C(),t=await D(),o=t.username||t.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let l,m,u=bt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let f of u)l=`https://console.apify.com/actors/${f.actId}/runs/${f.id}`,m=`https://console.apify.com/storage/datasets/${f.defaultDatasetId}`;R({message:["",`${Pa.blue("Export results")}: ${m}`,`${Pa.blue("View on Apify Console")}: ${l}`].join(`
234
- `),stdout:!0})}async resolveTaskId(e,t){let{taskId:o}=this.args;if(o?.includes("/")){let s=await e.task(o).get();if(!s)throw new Error(`Cannot find Task with ID '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}if(o){let s=await e.task(`${t}/${o.toLowerCase()}`).get();if(!s)throw new Error(`Cannot find Task with name '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}throw new Error("Please provide a valid Task ID or name.")}};var ss=class extends y{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[os];async run(){this.printHelp()}};var is=class extends y{static name="disable";static description="Disables telemetry.";async run(){(await ue()).enabled?(await yr(!1),$({message:"Telemetry disabled."})):b({message:"Telemetry is already disabled."})}};var ns=class extends y{static name="enable";static description="Enables telemetry.";async run(){(await ue()).enabled?b({message:"Telemetry is already enabled."}):(await yr(!0),$({message:"Telemetry enabled."}))}};var Qt=class extends y{static name="telemetry";static description=`Manages telemetry settings. We use this data to improve the CLI and the Apify platform.
235
- Read more: https://docs.apify.com/cli/docs/telemetry`;static subcommands=[ns,is];async run(){this.printHelp()}};import Ad from"process";import{validateInputSchema as Sd}from"@apify/input_schema";var as=class extends y{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
233
+ `;static flags=vt("Task");static args={taskId:w.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await C(),t=await F(),o=t.username||t.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let l,m,u=bt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let f of u)l=`https://console.apify.com/actors/${f.actId}/runs/${f.id}`,m=`https://console.apify.com/storage/datasets/${f.defaultDatasetId}`;_({message:["",`${Na.blue("Export results")}: ${m}`,`${Na.blue("View on Apify Console")}: ${l}`].join(`
234
+ `),stdout:!0})}async resolveTaskId(e,t){let{taskId:o}=this.args;if(o?.includes("/")){let s=await e.task(o).get();if(!s)throw new Error(`Cannot find Task with ID '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}if(o){let s=await e.task(`${t}/${o.toLowerCase()}`).get();if(!s)throw new Error(`Cannot find Task with name '${o}' in your account.`);return{id:s.id,userFriendlyId:`${t}/${s.name}`,title:s.title,task:s}}throw new Error("Please provide a valid Task ID or name.")}};var is=class extends y{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[ss];async run(){this.printHelp()}};var ns=class extends y{static name="disable";static description="Disables telemetry.";async run(){(await ue()).enabled?(await wr(!1),$({message:"Telemetry disabled."})):v({message:"Telemetry is already disabled."})}};var as=class extends y{static name="enable";static description="Enables telemetry.";async run(){(await ue()).enabled?v({message:"Telemetry is already enabled."}):(await wr(!0),$({message:"Telemetry enabled."}))}};var er=class extends y{static name="telemetry";static description=`Manages telemetry settings. We use this data to improve the CLI and the Apify platform.
235
+ Read more: https://docs.apify.com/cli/docs/telemetry`;static subcommands=[as,ns];async run(){this.printHelp()}};import Ad from"process";import{validateInputSchema as Sd}from"@apify/input_schema";var ls=class extends y{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
236
236
  1. Object in '${j}' under "input" key
237
237
  2. JSON file path in '${j}' "input" key
238
238
  3. .actor/INPUT_SCHEMA.json
239
239
  4. INPUT_SCHEMA.json
240
240
 
241
- Optionally specify custom schema path to validate.`;static args={path:w.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await lt({forcePath:this.args.path,cwd:Ad.cwd()});if(!e)throw new Error(`Input schema has not been found at ${t}.`);t?b({message:`Validating input schema stored at ${t}`}):b({message:`Validating input schema embedded in '${j}'`});let o=new mt({strict:!1});Sd(o,e),$({message:"Input schema is valid."})}};var vx=[Dr,qr,Qr,ho,Po,Uo,Qo,rs,ss,Qt,eo,qt,Kt,io,yo,Ao,To,vo,Lo,Do,Fo,ko,Go,as,Wt],Tx=[wt,yt,ht,gt,ft,pt,Wt,qt,Kt,Qt];export{Ph as a,Lh as b,vx as c,Tx as d};
242
- //# sourceMappingURL=chunk-ATQHWRBX.js.map
241
+ Optionally specify custom schema path to validate.`;static args={path:w.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await lt({forcePath:this.args.path,cwd:Ad.cwd()});if(!e)throw new Error(`Input schema has not been found at ${t}.`);t?v({message:`Validating input schema stored at ${t}`}):v({message:`Validating input schema embedded in '${j}'`});let o=new mt({strict:!1});Sd(o,e),$({message:"Input schema is valid."})}};var vx=[Fr,Wr,eo,yo,Lo,Mo,es,os,is,er,to,Wt,qt,no,wo,So,Io,To,Do,Fo,ko,Uo,Yo,ls,zt],Tx=[wt,yt,ht,gt,ft,pt,zt,Wt,qt,er];export{Ph as a,Lh as b,vx as c,Tx as d};
242
+ //# sourceMappingURL=chunk-T5ULSWTR.js.map