apify-cli 1.3.1-beta.12 → 1.3.1-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/actor.js +1 -1
- package/dist/apify.js +1 -1
- package/dist/{chunk-FGWT777S.js → chunk-SWHV5KL3.js} +153 -150
- package/dist/chunk-SWHV5KL3.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-FGWT777S.js.map +0 -1
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var $c=Object.defineProperty;var m=(r,e)=>$c(r,"name",{value:e,configurable:!0});import Ee from"process";import{parseArgs as qi}from"util";import to from"chalk";import{satisfies as Eu}from"semver";import nn from"chalk";import au from"indent-string";import cu from"widest-line";import lu from"wrap-ansi";import Ec from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Ec.gray(`[${r}]`),...e)}m(T,"cliDebugPrint");import{realpathSync as Rc}from"fs";import{dirname as _c}from"path";import dt from"chalk";function Qe(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}m(Qe,"internalLog");function R(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}m(R,"simpleLog");function f(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.red("Error:"),r.message]})}m(f,"error");function _(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.yellow.bold("Warning:"),r.message]})}m(_,"warning");function E(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.green("Success:"),r.message]})}m(E,"success");function ve(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.gray("Run:"),r.message]})}m(ve,"run");function b(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.white("Info:"),r.message]})}m(b,"info");function Ls(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.blue(r.message),r.url]})}m(Ls,"link");var Ms="0.0.0";var xc="1.3.1-beta.12",Oc="0e5e3a974f5f7df4de40ab102a064367a1a2f53f";function Pc(){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 _({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Rc(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"}m(Pc,"detectInstallMethod");function kc(){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}}m(kc,"getRuntimeInfo");var Mt=null;function W(){if(Mt)return Mt;let r=Pc(),e=kc();return Mt={version:xc,hash:Oc,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===Ms}},r==="bundle"&&(Mt.installPath=_c(process.execPath)),Mt}m(W,"useCLIMetadata");import{existsSync as wl,mkdirSync as Al,readFileSync as bl,writeFileSync as Sl}from"fs";import{dirname as vl}from"path";import{cryptoRandomObjectId as Tl}from"@apify/utilities";import{homedir as Fc}from"os";import{join as et}from"path";import{KEY_VALUE_STORE_KEYS as Dc,META_ORIGINS as Lc}from"@apify/consts";var Dn={name:"apify-cli",version:"1.3.1-beta.12",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.');"`,prepare:"husky"},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-memory-expression":"^0.1.3","@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":"^11.0.0","@inquirer/input":"^5.0.0","@inquirer/password":"^5.0.0","@inquirer/select":"^5.0.0","@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.18.0","apify-client":"^2.22.0",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.6.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","es-toolkit":"^1.45.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.2.0",handlebars:"~4.7.8",ignore:"^7.0.0","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","json-schema-to-typescript":"^15.0.4",mime:"~4.1.0",open:"~11.0.0",rimraf:"~6.1.0",semver:"~7.7.0","string-width":"^8.0.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",tinyglobby:"^0.2.15",which:"^6.0.0","widest-line":"^6.0.0","wrap-ansi":"^10.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":"^7.0.0","@types/bun":"^1.2.5","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/mime":"^4.0.0","@types/node":"^24.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2",husky:"^9","lint-staged":"^16.0.0","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^6.0.0","typescript-eslint":"^8.31.0",vitest:"^4.0.0"},volta:{node:"24.14.1",yarn:"4.13.0"},packageManager:"yarn@4.13.0",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"},resolutions:{tar:"7.5.13"}};var tt="storage",Us="apify_storage",js=1,Ar={actorSpecification:js,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Ln=1440*60*1e3,pt=m(()=>{let r=et(Fc(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?et(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),pe=m(()=>et(pt(),"auth.json"),"AUTH_FILE_PATH"),br=m(()=>et(pt(),"secrets.json"),"SECRETS_FILE_PATH"),Sr=m(()=>et(pt(),"state.json"),"STATE_FILE_PATH"),vr=m(()=>et(pt(),"telemetry.json"),"TELEMETRY_FILE_PATH"),Tr="apify.json",Cr=".actor",Mc="actor.json",D=et(Cr,Mc),Bs=new RegExp(`(^${Dc.INPUT}(?:\\.[^.]+)?$)`),Te=Dn.engines.node,Mn={"X-Apify-Request-Origin":Lc.CLI},rt="3.9.0",Un=".venv";import{execSync as Jc}from"child_process";import{createWriteStream as qc,existsSync as oe,mkdirSync as Kc,readdirSync as Hn,readFileSync as Yt,writeFileSync as $r}from"fs";import{mkdir as Wc,readFile as Er}from"fs/promises";import{get as zc}from"https";import{homedir as Vs}from"os";import{dirname as ft,join as q,relative as Xc}from"path";import z from"process";import{finished as Zc}from"stream/promises";import{DurationFormatter as Jn,TimeTypes as ot}from"@sapphire/duration";import{Timestamp as Gs}from"@sapphire/timestamp";import Qc from"adm-zip";import el from"ajv/dist/2019.js";import{ApifyClient as qn}from"apify-client";import tl from"archiver";import{AxiosHeaders as rl}from"axios";import ol from"escape-string-regexp";import sl from"ignore";import{getEncoding as nl}from"istextorbinary";import{Mime as il}from"mime";import al from"mime/types/other.js";import cl from"mime/types/standard.js";import{gte as ll,minVersion as ul,satisfies as ml}from"semver";import{glob as Ys}from"tinyglobby";import{ACTOR_ENV_VARS as Hs,ACTOR_JOB_TERMINAL_STATUSES as dl,ACTOR_NAME as Vt,APIFY_ENV_VARS as pl,KEY_VALUE_STORE_KEYS as Yn,LOCAL_ACTOR_ENV_VARS as Js,LOCAL_STORAGE_SUBDIRS as qs,SOURCE_FILE_FORMATS as Bt}from"@apify/consts";import{existsSync as Uc,mkdirSync as jc}from"fs";import{readFile as Bc,stat as jn,unlink as Vc,writeFile as Gc}from"fs/promises";import{join as Bn,sep as Yc}from"path";import{rimraf as Hc}from"rimraf";var Vn=m(async(r,e={},t=null)=>{let o=await Bc(r,"utf-8"),s=JSON.parse(o),n;t?(n=s,n[t]={...s[t],...e}):n={...s,...e},await Gc(r,JSON.stringify(n,null," "))},"updateLocalJson"),Ir=m((r,e)=>{e||(e=r,r="."),e.split(Yc).reduce((o,s)=>(o=Bn(o,s),Uc(o)||jc(o),o),r)},"ensureFolderExistsSync"),Ut=m(async r=>{await Hc(r)},"rimrafPromised"),jt=m(async r=>{(await jn(r)).isFile()&&await Vc(r)},"deleteFile"),Gn=m(async(r,e)=>(await Promise.all(r.map(async s=>jn(Bn(e,s))))).map(s=>s.size).reduce((s,n)=>s+n,0),"sumFilesSizeInBytes");var Gt=sl,Ht=el,Rr=m(async r=>new Promise((e,t)=>{zc(r,o=>{o.statusCode===301||o.statusCode===302?(e(Rr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),ge=m(()=>{let r=pl.LOCAL_STORAGE_DIR;return z.env[r]||z.env.CRAWLEE_STORAGE_DIR||tt},"getLocalStorageDir"),fe=m(r=>{let e=Hs.DEFAULT_KEY_VALUE_STORE_ID,t=r||z.env[e]||Js[e];return q(ge(),qs.keyValueStores,t)},"getLocalKeyValueStorePath"),Kn=m(r=>{let e=Hs.DEFAULT_DATASET_ID,t=r||z.env[e]||Js[e];return q(ge(),qs.datasets,t)},"getLocalDatasetPath"),Wn=m(r=>{let e=Hs.DEFAULT_REQUEST_QUEUE_ID,t=r||z.env[e]||Js[e];return q(ge(),qs.requestQueues,t)},"getLocalRequestQueuePath"),U=m(async()=>{let r={};try{let e=await Er(pe(),"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 I(){let r=await Jt();if(!r)throw z.exitCode=1,new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}m(I,"getLoggedClientOrThrow");var zn=m(r=>{if(!r&&oe(pt())&&oe(pe())){let e=Yt(pe(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),Ks=m((r,e)=>(r=zn(r),{token:r,baseUrl:e||z.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new rl;for(let[o,s]of Object.entries(Mn))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Jt(r,e){r=zn(r);let t=new qn(Ks(r,e)),o;try{o=await t.user("me").get()}catch(s){return T("[getLoggedClient] error getting user info",{error:s,apiBaseUrl:e}),null}return zs(pe()),$r(pe(),JSON.stringify({token:t.token,...o},null," ")),t}m(Jt,"getLoggedClient");var Ws=m(r=>q(r,D),"getLocalConfigPath"),le=m(r=>{if(oe(r))return JSON.parse(Yt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Me=m(r=>le(Ws(r)),"getLocalConfig"),_r=m(async(r,e)=>{let t=q(e||z.cwd(),D);await Wc(ft(t),{recursive:!0}),$r(t,JSON.stringify(r,null," "))},"setLocalConfig"),fl=[ge(),"node_modules",".venv"],xr=m(async r=>{let e=fe();Ir(r,Kn()),Ir(r,Wn()),Ir(r,e);let t=q(r,".gitignore"),o="";oe(t)&&(o=Yt(t,{encoding:"utf-8"}));let s=[];for(let n of fl)RegExp(`^${ol(n)}$`,"mg").test(o)||s.push(n);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),$r(t,`
|
|
1
|
+
var Rc=Object.defineProperty;var m=(r,e)=>Rc(r,"name",{value:e,configurable:!0});import Re from"process";import{parseArgs as Wn}from"util";import ro from"chalk";import{satisfies as _u}from"semver";import ni from"chalk";import lu from"indent-string";import uu from"widest-line";import mu from"wrap-ansi";import _c from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(_c.gray(`[${r}]`),...e)}m(T,"cliDebugPrint");import{realpathSync as xc}from"fs";import{dirname as Pc}from"path";import dt from"chalk";function Qe(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}m(Qe,"internalLog");function R(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}m(R,"simpleLog");function f(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.red("Error:"),r.message]})}m(f,"error");function _(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.yellow.bold("Warning:"),r.message]})}m(_,"warning");function E(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.green("Success:"),r.message]})}m(E,"success");function ve(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.gray("Run:"),r.message]})}m(ve,"run");function b(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.white("Info:"),r.message]})}m(b,"info");function Us(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.blue(r.message),r.url]})}m(Us,"link");var js="0.0.0";var Oc="1.3.1-beta.13",kc="b416d75406e4913a78b5804403efaed6807c0a6b";function Nc(){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 _({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=xc(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"}m(Nc,"detectInstallMethod");function Fc(){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}}m(Fc,"getRuntimeInfo");var Mt=null;function W(){if(Mt)return Mt;let r=Nc(),e=Fc();return Mt={version:Oc,hash:kc,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===js}},r==="bundle"&&(Mt.installPath=Pc(process.execPath)),Mt}m(W,"useCLIMetadata");import{existsSync as bl,mkdirSync as Sl,readFileSync as vl,writeFileSync as Tl}from"fs";import{dirname as Cl}from"path";import{cryptoRandomObjectId as Il}from"@apify/utilities";import{homedir as Lc}from"os";import{join as et}from"path";import{KEY_VALUE_STORE_KEYS as Mc,META_ORIGINS as Uc}from"@apify/consts";var Li={name:"apify-cli",version:"1.3.1-beta.13",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.');"`,prepare:"husky"},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-memory-expression":"^0.1.3","@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":"^11.0.0","@inquirer/input":"^5.0.0","@inquirer/password":"^5.0.0","@inquirer/select":"^5.0.0","@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.18.0","apify-client":"^2.22.0",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.6.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","es-toolkit":"^1.45.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.2.0",handlebars:"~4.7.8",ignore:"^7.0.0","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","json-schema-to-typescript":"^15.0.4",mime:"~4.1.0",open:"~11.0.0",rimraf:"~6.1.0",semver:"~7.7.0","string-width":"^8.0.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",tinyglobby:"^0.2.15",which:"^6.0.0","widest-line":"^6.0.0","wrap-ansi":"^10.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":"^7.0.0","@types/bun":"^1.2.5","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/mime":"^4.0.0","@types/node":"^24.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2",husky:"^9","lint-staged":"^16.0.0","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^6.0.0","typescript-eslint":"^8.31.0",vitest:"^4.0.0"},volta:{node:"24.14.1",yarn:"4.13.0"},packageManager:"yarn@4.13.0",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"},resolutions:{tar:"7.5.13"}};var tt="storage",Bs="apify_storage",Vs=1,br={actorSpecification:Vs,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Mi=1440*60*1e3,pt=m(()=>{let r=et(Lc(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?et(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),pe=m(()=>et(pt(),"auth.json"),"AUTH_FILE_PATH"),Sr=m(()=>et(pt(),"secrets.json"),"SECRETS_FILE_PATH"),vr=m(()=>et(pt(),"state.json"),"STATE_FILE_PATH"),Tr=m(()=>et(pt(),"telemetry.json"),"TELEMETRY_FILE_PATH"),Cr="apify.json",Ir=".actor",jc="actor.json",D=et(Ir,jc),Gs=new RegExp(`(^${Mc.INPUT}(?:\\.[^.]+)?$)`),Te=Li.engines.node,Ui={"X-Apify-Request-Origin":Uc.CLI},rt="3.9.0",ji=".venv";import{execSync as Kc}from"child_process";import{createWriteStream as Wc,existsSync as oe,mkdirSync as zc,readdirSync as qi,readFileSync as Yt,writeFileSync as Er}from"fs";import{mkdir as Xc,readFile as Rr}from"fs/promises";import{get as Zc}from"https";import{homedir as Ys}from"os";import{dirname as ft,join as J,relative as Qc}from"path";import z from"process";import{finished as el}from"stream/promises";import{DurationFormatter as Ji,TimeTypes as ot}from"@sapphire/duration";import{Timestamp as Hs}from"@sapphire/timestamp";import tl from"adm-zip";import rl from"ajv/dist/2019.js";import{ApifyClient as Ki}from"apify-client";import ol from"archiver";import{AxiosHeaders as sl}from"axios";import il from"escape-string-regexp";import nl from"ignore";import{getEncoding as al}from"istextorbinary";import{Mime as cl}from"mime";import ll from"mime/types/other.js";import ul from"mime/types/standard.js";import{gte as ml,minVersion as dl,satisfies as pl}from"semver";import{glob as qs}from"tinyglobby";import{ACTOR_ENV_VARS as Js,ACTOR_JOB_TERMINAL_STATUSES as fl,ACTOR_NAME as Vt,APIFY_ENV_VARS as gl,KEY_VALUE_STORE_KEYS as Hi,LOCAL_ACTOR_ENV_VARS as Ks,LOCAL_STORAGE_SUBDIRS as Ws,SOURCE_FILE_FORMATS as Bt}from"@apify/consts";import{existsSync as Bc,mkdirSync as Vc}from"fs";import{readFile as Gc,stat as Bi,unlink as Yc,writeFile as Hc}from"fs/promises";import{join as Vi,sep as qc}from"path";import{rimraf as Jc}from"rimraf";var Gi=m(async(r,e={},t=null)=>{let o=await Gc(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await Hc(r,JSON.stringify(i,null," "))},"updateLocalJson"),$r=m((r,e)=>{e||(e=r,r="."),e.split(qc).reduce((o,s)=>(o=Vi(o,s),Bc(o)||Vc(o),o),r)},"ensureFolderExistsSync"),Ut=m(async r=>{await Jc(r)},"rimrafPromised"),jt=m(async r=>{(await Bi(r)).isFile()&&await Yc(r)},"deleteFile"),Yi=m(async(r,e)=>(await Promise.all(r.map(async s=>Bi(Vi(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var Gt=nl,Ht=rl,_r=m(async r=>new Promise((e,t)=>{Zc(r,o=>{o.statusCode===301||o.statusCode===302?(e(_r(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),ge=m(()=>{let r=gl.LOCAL_STORAGE_DIR;return z.env[r]||z.env.CRAWLEE_STORAGE_DIR||tt},"getLocalStorageDir"),fe=m(r=>{let e=Js.DEFAULT_KEY_VALUE_STORE_ID,t=r||z.env[e]||Ks[e];return J(ge(),Ws.keyValueStores,t)},"getLocalKeyValueStorePath"),Wi=m(r=>{let e=Js.DEFAULT_DATASET_ID,t=r||z.env[e]||Ks[e];return J(ge(),Ws.datasets,t)},"getLocalDatasetPath"),zi=m(r=>{let e=Js.DEFAULT_REQUEST_QUEUE_ID,t=r||z.env[e]||Ks[e];return J(ge(),Ws.requestQueues,t)},"getLocalRequestQueuePath"),U=m(async()=>{let r={};try{let e=await Rr(pe(),"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 I(){let r=await Jt();if(!r)throw z.exitCode=1,new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}m(I,"getLoggedClientOrThrow");var Xi=m(r=>{if(!r&&oe(pt())&&oe(pe())){let e=Yt(pe(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),qt=m((r,e)=>(r=Xi(r),{token:r,baseUrl:e||z.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new sl;for(let[o,s]of Object.entries(Ui))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Jt(r,e){r=Xi(r);let t=new Ki(qt(r,e)),o;try{o=await t.user("me").get()}catch(s){return T("[getLoggedClient] error getting user info",{error:s,apiBaseUrl:e}),null}return Xs(pe()),Er(pe(),JSON.stringify({token:t.token,...o},null," ")),t}m(Jt,"getLoggedClient");var zs=m(r=>J(r,D),"getLocalConfigPath"),le=m(r=>{if(oe(r))return JSON.parse(Yt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Me=m(r=>le(zs(r)),"getLocalConfig"),xr=m(async(r,e)=>{let t=J(e||z.cwd(),D);await Xc(ft(t),{recursive:!0}),Er(t,JSON.stringify(r,null," "))},"setLocalConfig"),hl=[ge(),"node_modules",".venv"],Pr=m(async r=>{let e=fe();$r(r,Wi()),$r(r,zi()),$r(r,e);let t=J(r,".gitignore"),o="";oe(t)&&(o=Yt(t,{encoding:"utf-8"}));let s=[];for(let i of hl)RegExp(`^${il(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),Er(t,`
|
|
2
2
|
${s.join(`
|
|
3
3
|
`)}
|
|
4
|
-
`,{flag:"a"}))
|
|
4
|
+
`,{flag:"a"})):Er(t,`${s.join(`
|
|
5
5
|
`)}
|
|
6
|
-
`,{flag:"w"}))},"setLocalEnv"),
|
|
7
|
-
`),s=[],
|
|
8
|
-
`).filter(Boolean);if(u.length>0){let l=Gt().add(u);
|
|
9
|
-
]HH:mm:ss`),
|
|
10
|
-
`);function
|
|
11
|
-
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
|
|
6
|
+
`,{flag:"w"}))},"setLocalEnv"),Zi=new cl(ul,ll).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),yl=m((r,e)=>{let t=Zi.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")?Bt.TEXT:Bt.BASE64:al(e)==="binary"?Bt.BASE64:Bt.TEXT},"getSourceFileFormat"),Qi=m(async(r,e)=>r.map(t=>{let o=Yt(J(e,t)),s=yl(t,o);return{name:t,format:s,content:s===Bt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),wl=m(async r=>{let e=await qs("**/.gitignore",{dot:!0,cwd:r,ignore:[".git/**"],expandDirectories:!1}),t=[];for(let s of e){let i=ft(s),n=await Rr(J(r,s),"utf-8");t.push({dir:i==="."?"":i,ig:Gt().add(n)})}let o=ft(r);for(;o!==ft(o)&&!oe(J(o,".git"));){let s=J(o,".gitignore");if(oe(s))try{let i=await Rr(s,"utf-8"),n=Qc(o,r);t.push({dir:"",ig:Gt().add(i),ancestorPrefix:n})}catch{}o=ft(o)}return t.length===0?s=>s:s=>s.filter(i=>{for(let{dir:n,ig:a,ancestorPrefix:c}of t){let u;if(n?i.startsWith(`${n}/`)?u=i.slice(n.length+1):u=null:u=c?`${c}/${i}`:i,u!==null&&a.ignores(u))return!1}return!0})},"getGitignoreFallbackFilter"),Al=m(async r=>{let e=J(r,".actorignore");if(!oe(e))return{excludeFilter:null,forceIncludePatterns:[]};let o=(await Rr(e,"utf-8")).split(`
|
|
7
|
+
`),s=[],i=[];for(let a of o){let c=a.trim();!c||c.startsWith("#")||(c.startsWith("!")?i.push(c.slice(1)):s.push(c))}return{excludeFilter:s.length>0?a=>{let c=Gt().add(s);return a.filter(u=>!c.ignores(u))}:null,forceIncludePatterns:i}},"parseActorIgnore"),en=m(async r=>{let e=r??z.cwd(),t=[".git/**","apify_storage","node_modules","storage","crawlee_storage"],{excludeFilter:o,forceIncludePatterns:s}=await Al(e),i=null;try{let u=Kc("git ls-files --others --ignored --exclude-standard --directory",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
8
|
+
`).filter(Boolean);if(u.length>0){let l=Gt().add(u);i=m(d=>d.filter(p=>!l.ignores(p)),"gitIgnoreFilter")}}catch{i=await wl(e)}let n=await qs(["*","**/**"],{ignore:t,dot:!0,expandDirectories:!1,cwd:e}),a=i?i(n):n;if(o&&(a=o(a)),s.length>0){let u=Gt().add(s),l=n.filter(p=>u.ignores(p)),d=new Set(a);for(let p of l)d.add(p);a=[...d]}let c=n.filter(u=>u===".actor"||u.startsWith(".actor/"));if(c.length>0){let u=new Set(a);for(let l of c)u.add(l);a=[...u]}return a},"getActorLocalFilePaths"),tn=m(async(r,e,t)=>{oe(r)&&await jt(r);let o=Wc(r),s=ol("zip",{zlib:{level:6}});s.pipe(o),e.forEach(i=>s.file(J(t,i),{name:i})),await s.finalize()},"createActZip"),Kt=m(r=>{let e=fe();if(!oe(J(r,e)))return;let s=qi(J(r,e)).find(a=>!!a.match(Gs));if(!s)return;let i=Yt(J(r,e,s)),n=Zi.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),rn=m(async()=>{let r=zi();oe(ge())&&oe(r)&&await Ut(r)},"purgeDefaultQueue"),on=m(async()=>{let r=Wi();oe(ge())&&oe(r)&&await Ut(r)},"purgeDefaultDataset"),sn=m(async()=>{let r=fe();if(!oe(ge())||!oe(r))return;let e=qi(r),t=[];e.forEach(o=>{o.match(Gs)||t.push(jt(J(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),Pe=m(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new Ki({baseUrl:z.env.APIFY_CLIENT_BASE_URL});if(fl.includes(s)){if(z.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();z.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let c=null;a.on("data",u=>{z.env.APIFY_NO_LOGS_IN_TESTS||z.stderr.write(u.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var nn=m(async()=>(await qs([`${ge()}/**`,`!${fe()}/${Hi.INPUT}.*`,`!${fe()}/${Hi.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Wt=m(r=>{if(!Vt.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<Vt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>Vt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),Or=m(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<Vt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,Vt.MAX_LENGTH)},"sanitizeActorName"),kr=m(r=>pl(r,`^${rt}`),"isPythonVersionSupported"),Nr=m(r=>{let e=dl(Te);return ml(r,e)},"isNodeVersionSupported"),Fr=m(async({url:r,pathTo:e})=>{let t=await _r(r),o=[];t.on("data",i=>o.push(i)),await el(t),new tl(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Xs(r){let e=ft(r);zc(e,{recursive:!0})}m(Xs,"ensureApifyDirectory");var Y=new Hs("YYYY-MM-DD [at] HH:mm:ss"),zt=new Hs(`YYYY-MM-DD[
|
|
9
|
+
]HH:mm:ss`),an=new Hs("YYYY-MM-DD"),Xt=new Ji,ue=new Ji({[ot.Day]:{DEFAULT:"d"},[ot.Hour]:{DEFAULT:"h"},[ot.Minute]:{DEFAULT:"m"},[ot.Month]:{DEFAULT:"M"},[ot.Second]:{DEFAULT:"s"},[ot.Week]:{DEFAULT:"w"},[ot.Year]:{DEFAULT:"y"}});function Dr(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}m(Dr,"objectGroupBy");function cn(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}m(cn,"mapGroupBy");function F(r){console.log(JSON.stringify(r,null,2))}m(F,"printJsonToStdout");var ae=m(r=>r.startsWith(Ys())?r.replace(Ys(),"~"):r,"tildify");function ln(){let r=z.env.SHELL??"";return r.includes("zsh")?"zsh":r.includes("bash")?"bash":r.includes("fish")?"fish":"unknown"}m(ln,"detectShell");function un(r,e){switch(e){case"bash":{let t=[J(r,".bashrc"),J(r,".bash_profile")];z.env.XDG_CONFIG_HOME&&t.push(J(z.env.XDG_CONFIG_HOME,".bashrc"),J(z.env.XDG_CONFIG_HOME,".bash_profile"),J(z.env.XDG_CONFIG_HOME,"bashrc"),J(z.env.XDG_CONFIG_HOME,"bash_profile"));for(let o of t)if(oe(o))return o;return null}case"zsh":{let t=z.env.ZDOTDIR||Ys();return J(t,".zshrc")}case"fish":return J(r,".config","fish","config.fish");case"unknown":return null}}m(un,"shellConfigFile");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(`
|
|
10
|
+
`);function mn(){return`CLI:${Il()}`}m(mn,"createAnonymousId");async function El(r){if(r.version&&r.version>=1)return!1;let e=r,t=await U().catch(()=>({}));return Lr({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=mn(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}m(El,"migrateStateV0ToV1");async function he(){let r=Tr();if(!bl(r)){let s=await U().catch(()=>({}));return Lr({version:1,enabled:!0,anonymousId:mn(),userId:s.id}),b({message:$l}),he()}let t=JSON.parse(vl(r,"utf-8"));return await El(t)?he():t}m(he,"useTelemetryState");function Lr(r,e){let t={...r};e?.(t);let o=Tr(),s=Cl(o);Sl(s,{recursive:!0}),Tl(Tr(),JSON.stringify(t,null," "))}m(Lr,"updateTelemetryState");async function Mr(r){let e=await he();Lr(e,t=>{t.userId=r})}m(Mr,"updateUserId");async function Ur(r){let e=await he();Lr(e,t=>{t.enabled=r})}m(Ur,"updateTelemetryEnabled");async function dn(){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 he();return T("telemetry state",{telemetryState:r}),r.enabled}m(dn,"useTelemetryEnabled");async function pn(){let r=await he();return{anonymousId:r.anonymousId,userId:r.userId}}m(pn,"useTelemetryIdentifiers");var Zt=W(),Rl="https://api.segment.io/v1/track",_l=Zt.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function fn(r,e){let t=await pn(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:Zt.version,build:Zt.hash},library:{name:"apify-cli",version:Zt.version},os:{name:Zt.platform},userAgent:st,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:_l};if(T("trackEvent",o),!await dn()){T("trackEvent","telemetry disabled");return}try{let i=await fetch(Rl,{method:"POST",body:JSON.stringify(o)});if(!i.ok){T("trackEvent","failed to send event",await i.text());return}T("trackEvent","event sent")}catch(i){T("trackEvent","failed to send event",i)}}m(fn,"trackEvent");import{access as ri,readdir as gt,readFile as ql,stat as Jl}from"fs/promises";import{join as j,resolve as _n}from"path";import Kl from"process";import{err as Wl,ok as ti}from"@sapphire/result";import{existsSync as wn,readdirSync as Dl}from"fs";import{join as Gr,resolve as Ll}from"path";import Ml from"configparser";import Nl from"@inquirer/input";import kl from"is-ci";import{constants as gn,fstat as xl}from"fs";import hn from"process";import{promisify as Pl}from"util";var Ol=Pl(xl),Zs;async function jr(){if(Zs)return Zs;let r=hn.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Ol(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()}),hn.platform==="win32"){if((o.mode&gn.S_IFIFO)===gn.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),Zs=e,e}m(jr,"useStdin");var Qs="confirm",yn=`no-${Qs}`;function Oe(r,{errorMessageForStdin:e=`Please use the --${Qs}/--${yn} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await jr(),n=t;if(kl||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${Qs}/--${yn} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}m(Oe,"stdinCheckWrapper");var it=Oe(async({message:r,validate:e,default:t})=>await Nl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as Fl}from"fs";var Br=class{static{m(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 Vr=class{static{m(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 Br({class_name:s[1],pathname:this.pathname})),s=t.exec(e);return o}};var nt=class{static{m(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return wn(Gr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Ml,t=Ll(Gr(this.pathname,"scrapy.cfg"));if(!wn(t))throw new Error(`scrapy.cfg not found in "${t}".
|
|
11
|
+
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 it({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await it({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=Gr(this.pathname,o.replaceAll(".","/")),i=Dl(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new Vr(Gr(s,n.name)).getSpiders())}return t}};import ei from"process";import{none as bn,some as Sn}from"@sapphire/result";import{execa as Tn}from"execa";import vn from"which";import{stat as Yr}from"fs/promises";import{isAbsolute as Ul,join as Hr}from"path";function Ve(r){return r?r.startsWith('"')?r:Ul(r)&&r.includes(" ")?`"${r}"`:r:null}m(Ve,"normalizeExecutablePath");async function An(r){let e=null;return await(await ke({cwd:r})).inspectAsync(async o=>{if(o.type===0){let[s,i,n,a]=await Promise.all([Yr(Hr(r,"yarn.lock")).then(()=>!0).catch(()=>!1),Yr(Hr(r,"pnpm-lock.yaml")).then(()=>!0).catch(()=>!1),Yr(Hr(r,"bun.lockb")).then(()=>!0).catch(()=>!1),Yr(Hr(r,"bun.lock")).then(()=>!0).catch(()=>!1)]);s?e="yarn install":i?e="pnpm install":n||a||o.runtime?.pmName==="bun"?e="bun install":o.runtime?.pmName==="deno"?e="deno install --node-modules-dir":e="npm install"}else(o.type===1||o.type===2)&&(e="python -m pip install -r requirements.txt")}),e}m(An,"getInstallCommandSuggestion");var qr=new Map,jl={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 Tn(r,e,{shell:!0,windowsHide:!0,verbose:ei.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}m(Bl,"getRuntimeVersion");async function Vl(r){let e=await Tn(r,["--version"],{shell:!0,windowsHide:!0,verbose:ei.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}m(Vl,"getNpmVersion");async function Cn(r=ei.cwd()){let e=qr.get(r);if(e)return T("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(jl))try{let s=Ve(await vn(t)),i=await Bl(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ve(await vn("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Vl(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return qr.set(r,Sn(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:qr.get(r)?.unwrap()}),Sn(n)}}catch{}return qr.set(r,bn),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),bn}m(Cn,"useJavaScriptRuntime");import{platform as Gl}from"os";import{join as In}from"path";import Jr from"process";import{none as $n,some as En}from"@sapphire/result";import{execa as Yl}from"execa";import Hl from"which";var Ge=new Map;async function Rn(r){try{let e=await Yl(r,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Jr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}m(Rn,"getPythonVersion");async function er({cwd:r=Jr.cwd(),force:e=!1}={}){let t=Ge.get(r);if(t&&!e)return T("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=Gl()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Jr.env.VIRTUAL_ENV?i=In(Jr.env.VIRTUAL_ENV,...s):i=In(r,".venv",...s),i=Ve(i);try{let a=await Rn(i);if(a)return Ge.set(r,En({executablePath:i,version:a})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ge.get(r)?.unwrap()}),Ge.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ve(await Hl(a)),u=await Rn(c);if(u)return Ge.set(r,En({executablePath:c,version:u})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ge.get(r)?.unwrap()}),Ge.get(r)}catch{}return Ge.set(r,$n),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),$n}m(er,"usePythonRuntime");var xn=new Map;async function ke({cwd:r=Kl.cwd()}={}){let e=xn.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),ti(e);let t={type:3},s=await m(async()=>{if(await eu(r)){t.type=2;let a=await er({cwd:r});t.runtime=a.unwrapOr(void 0);let c=new nt(r);if(c.loadScrapyCfg(),c.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:c.configuration.get("apify","mainpy_location")};else try{let u=await kn(r);u&&(t.entrypoint={path:u})}catch{}return}let n=await zl(r);if(!n){let a=null;try{a=await kn(r)}catch(c){return Wl({message:c instanceof Error?c.message:String(c)})}if(a){t.type=1;let c=await er({cwd:r});t.entrypoint={path:a},t.runtime=c.unwrapOr(void 0);let u=j(r,a.replace(/\./g,"/"));await tr(j(u,"__main__.py"))||(t.warnings=[`The detected Python package "${a}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(n){t.type=0;let a=await Cn();t.runtime=a.unwrapOr(void 0),n.type==="file"?t.entrypoint={path:n.path}:n.type==="script"&&(t.entrypoint={script:n.script});return}return ti(t)},"check")();return s?.isErr()?(T("useCwdProject",{cacheHit:!1,error:s}),s):(T("useCwdProject",{cacheHit:!1,project:t}),xn.set(r,t),ti(t))}m(ke,"useCwdProject");async function zl(r){let e=j(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 ri(_n(r,s.main)),{path:_n(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[j(r,"index.js"),j(r,"index.mjs"),j(r,"index.cjs"),j(r,"main.js"),j(r,"main.mjs"),j(r,"main.cjs"),j(r,"src","index.js"),j(r,"src","index.mjs"),j(r,"src","index.cjs"),j(r,"src","main.js"),j(r,"src","main.mjs"),j(r,"src","main.cjs"),j(r,"dist","index.js"),j(r,"dist","index.mjs"),j(r,"dist","index.cjs"),j(r,"dist","main.js"),j(r,"dist","main.mjs"),j(r,"dist","main.cjs")];for(let o of t)try{return await ri(o),{path:o,type:"file"}}catch{}return null}m(zl,"checkNodeProject");async function tr(r){try{return await ri(r),!0}catch{return!1}}m(tr,"fileExists");async function Nn(r){try{return(await Jl(r)).isDirectory()}catch{return!1}}m(Nn,"dirExists");function Fn(r){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)}m(Fn,"isValidPythonIdentifier");async function Xl(r){try{let e=await gt(r,{withFileTypes:!0});if(e.some(t=>t.isFile()&&t.name.endsWith(".py")))return!0;for(let t of e){if(!t.isDirectory()||t.name.startsWith(".")||t.name.startsWith("_"))continue;let o=j(r,t.name);try{let s=await gt(o,{withFileTypes:!0});if(s.some(i=>i.isFile()&&i.name.endsWith(".py")))return!0;if(t.name==="src"){for(let i of s)if(i.isDirectory()&&!(i.name.startsWith(".")||i.name.startsWith("_")))try{if((await gt(j(o,i.name),{withFileTypes:!0})).some(a=>a.isFile()&&a.name.endsWith(".py")))return!0}catch{}}}catch{}}return!1}catch{return!1}}m(Xl,"hasPythonFilesInDirOrSubdirs");async function Zl(r){try{return(await gt(r,{withFileTypes:!0})).some(t=>t.isFile()&&t.name.endsWith(".py")&&t.name!=="__init__.py")}catch{return!1}}m(Zl,"dirHasPyFiles");async function Pn(r){try{let e=await gt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory()||o.name.startsWith(".")||o.name.startsWith("_"))continue;let s=Fn(o.name),i=await tr(j(r,o.name,"__init__.py")),n=i||await Zl(j(r,o.name));s&&i||n&&t.push({name:o.name,needsRename:!s,needsInit:!i})}return t}catch{return[]}}m(Pn,"findNearMissPackagesInDir");async function On(r){try{let e=await gt(r,{withFileTypes:!0}),t=[];for(let o of e){if(!o.isDirectory())continue;let{name:s}=o;if(s.startsWith(".")||s.startsWith("_")||!Fn(s))continue;let i=j(r,s,"__init__.py");await tr(i)&&t.push({name:s,path:j(r,s)})}return t}catch{return[]}}m(On,"findPackagesInDir");async function Ql(r){let e=[],t=await On(r);e.push(...t.map(i=>i.name));let o=j(r,"src"),s=await tr(j(o,"__init__.py"));if(await Nn(o)&&!s){let i=await On(o);e.push(...i.map(n=>`src.${n.name}`))}return e}m(Ql,"discoverPythonPackages");async function kn(r){let e=await Ql(r);if(e.length===1)return e[0];if(e.length>1){let c=e.map(u=>` - ${u}`).join(`
|
|
12
12
|
`);throw new Error(`Multiple Python packages found:
|
|
13
13
|
${c}
|
|
14
14
|
|
|
15
15
|
Apify CLI cannot determine which package to run.
|
|
16
16
|
Please specify the package using the --entrypoint flag, e.g.:
|
|
17
|
-
apify run --entrypoint <package_name>`)}let t=await
|
|
17
|
+
apify run --entrypoint <package_name>`)}let t=await Pn(r),o=j(r,"src"),i=!await tr(j(o,"__init__.py"))&&await Nn(o)?await Pn(o):[],n=[...t.map(c=>({...c,prefix:""})),...i.map(c=>({...c,prefix:"src/"}))];if(n.length>0){let c=n.map(({name:u,prefix:l,needsRename:d,needsInit:p})=>{let g=[];return d&&g.push(`rename to "${l}${u.replace(/[^a-zA-Z0-9_]/g,"_")}/"`),p&&g.push("add __init__.py"),` - "${l}${u}/" \u2192 ${g.join(" and ")}`}).join(`
|
|
18
18
|
`);throw new Error(`Found directories that appear to be Python packages but have issues:
|
|
19
19
|
${c}
|
|
20
20
|
|
|
21
|
-
A valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await
|
|
21
|
+
A valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await Xl(r))throw new Error(`No Python package found. Found Python files, but no valid package structure detected.
|
|
22
22
|
A Python package requires:
|
|
23
23
|
- A directory with a valid Python identifier name (letters, numbers, underscores)
|
|
24
24
|
- An __init__.py file inside the directory
|
|
@@ -31,45 +31,45 @@ Common package structures:
|
|
|
31
31
|
src/
|
|
32
32
|
my_package/
|
|
33
33
|
__init__.py
|
|
34
|
-
main.py`);return null}m(
|
|
35
|
-
`)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(
|
|
36
|
-
`).at(-1)||"")+o,
|
|
37
|
-
`),e.push(t)}kebabFlagName(e){return
|
|
34
|
+
main.py`);return null}m(kn,"checkPythonProject");async function eu(r){return nt.isApplicable(r)}m(eu,"checkScrapyProject");import K from"chalk";import or from"chalk";import Un from"indent-string";import jn from"widest-line";import Bn from"wrap-ansi";import Kr from"chalk";import oi from"indent-string";import su from"string-width";import Ln from"strip-ansi";import Mn from"widest-line";import si from"wrap-ansi";import tu from"chalk";import ru from"indent-string";import Dn from"string-width";import ou from"wrap-ansi";var Ye;function ce(){if(Ye)return Ye;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))Ye=r;else if(!process.stdout.isTTY)Ye=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?Ye=80:e<40?Ye=40:Ye=e}return Ye}m(ce,"getMaxLineWidth");var ht=class{static{m(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(`
|
|
35
|
+
`)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(tu.bold("DESCRIPTION"));let t=ou(this.command.description,ce()-2,{trim:!1}),o=ru(t,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=Dn(e.join(" ").split(`
|
|
36
|
+
`).at(-1)||"")+o,i=Dn(t);s+i>ce()&&e.push(`
|
|
37
|
+
`),e.push(t)}kebabFlagName(e){return Ie($e(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 Wr=class extends ht{static{m(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
|
|
38
38
|
`).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(`
|
|
39
|
-
`).trim()}pushUsageString(e){e.push(
|
|
40
|
-
`));for(let[s,
|
|
41
|
-
`));for(let[n
|
|
42
|
-
<options: ${
|
|
39
|
+
`).trim()}pushUsageString(e){e.push(Kr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+su(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[d,p]of i){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:p.required?`<${d}>`:`[${d}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,d])=>{if(typeof d=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!d.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((d,p)=>{if(typeof d[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof p[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return d[1].required&&!p[1].required?-1:!d[1].required&&p[1].required?1:d[0].localeCompare(p[0])})),c=new Set;if(n.length)for(let[d,p]of a){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(c.has(d))continue;let g=p.required,v=[this.makeFlagString(d,p)];if(p.exclusive?.length)for(let S of p.exclusive){c.add(S);let $=a.get(S),C=this.makeFlagString(S,$);v.push(C),$.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?v.join(" | "):`[${v.join(" | ")}]`,indentSize:o})}let u=si(s.join(" "),ce()-o),l=oi(u,o+1).trim();e.push(` ${l}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(Kr.bold("ARGUMENTS"));let o=Mn(t.map(([s])=>s).join(`
|
|
40
|
+
`));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=si(n,ce()-o-2),c=oi(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(Kr.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 c=n.choices?"<option>":"<value>";a.push(`--${this.kebabFlagName(i)}=${Kr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=Mn([...o.keys()].map(Ln).join(`
|
|
41
|
+
`));for(let[i,n]of o){let a=s-Ln(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
|
|
42
|
+
<options: ${n.choices.join("|")}>`);let u=si(c,ce()-s),l=oi(u,s).trim().split(`
|
|
43
43
|
`).map(d=>/^-[a-z]/.test(d.trim())?d:` ${d}`).join(`
|
|
44
|
-
`);e.push(` ${l}`)}e.push("")}};import
|
|
44
|
+
`);e.push(` ${l}`)}e.push("")}};import iu from"chalk";import nu from"indent-string";import au from"widest-line";import cu from"wrap-ansi";var rr=class extends ht{static{m(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
|
|
45
45
|
`).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(`
|
|
46
|
-
`).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(
|
|
46
|
+
`).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(iu.bold("SUBCOMMANDS"));let t=au(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
|
|
47
47
|
`));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
|
|
48
|
-
`)[0]||"",
|
|
48
|
+
`)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=cu(i,ce()-t-2),a=nu(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var sr=new Map;function ii(r,e){if(e.name.toLowerCase()!==e.name){f({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){sr.set(e,new rr(r,e));for(let t of e.subcommands)ii(`${r} ${e.name}`,t)}else sr.set(e,new Wr(r,e))}m(ii,"registerCommandForHelpGeneration");function zr(r){let e=sr.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}m(zr,"renderHelpForCommand");function Xr(r,e){let t=sr.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}m(Xr,"selectiveRenderHelpForCommand");function Vn(r,e){return r[0].name.localeCompare(e[0].name)}m(Vn,"sortByName");function Zr(r){let e=W(),t=[];t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(or.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(or.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=cn(sr,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof rr?"subcommand":"command"),s=o.get("subcommand")?.sort(Vn),i=o.get("command")?.sort(Vn);if(s?.length){t.push(or.bold("TOPICS"));let n=[],a=jn(s.map(([c])=>c.name).join(`
|
|
49
49
|
`));for(let[c]of s){if(c.hidden)continue;let u=c.shortDescription||c.description?.split(`
|
|
50
|
-
`)[0]||"",l=`${c.name.padEnd(a)} ${u}`,d=
|
|
51
|
-
`));for(let[c]of
|
|
52
|
-
`)[0]||"",l=`${c.name.padEnd(a)} ${u}`,d=
|
|
53
|
-
`).trim()}m(
|
|
50
|
+
`)[0]||"",l=`${c.name.padEnd(a)} ${u}`,d=Bn(l,ce()-a-2);n.push(` ${Un(d,a+2+2).trim()}`)}t.push(...n,"")}if(i?.length){t.push(or.bold("COMMANDS"));let n=[],a=jn(i.map(([c])=>c.name).join(`
|
|
51
|
+
`));for(let[c]of i){if(c.hidden)continue;let u=c.shortDescription||c.description?.split(`
|
|
52
|
+
`)[0]||"",l=`${c.name.padEnd(a)} ${u}`,d=Bn(l,ce()-a-2);n.push(` ${Un(d,a+2+2).trim()}`)}t.push(...n,"")}return t.push(or.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(`
|
|
53
|
+
`).trim()}m(Zr,"renderMainHelpMenu");var Qr=(l=>(l[l.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",l[l.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",l[l.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",l[l.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",l[l.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",l[l.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",l[l.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",l[l.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",l[l.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",l[l.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",l))(Qr||{}),me=class r extends Error{static{m(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(Qr[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}.
|
|
54
54
|
|
|
55
55
|
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 '-(?<longForm>-)?(?<optionName>.+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
|
|
56
56
|
|
|
57
|
-
Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}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=
|
|
58
|
-
`)}case 3:{let e=`--${this.metadata.flag}`;return K.gray(`Flag ${K.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=K.whiteBright(String(this.metadata.value));return K.gray(`The provided value for the '${K.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=`'${K.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${K.white.bold(`--${t}`)}')`),o?K.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):K.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[K.gray("The following errors occurred:")],o=K.red(" > ");for(let[s,
|
|
59
|
-
`)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return K.gray(`Flag ${K.white.bold(`--${e}`)} and ${K.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=W();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} (${
|
|
60
|
-
${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? ${
|
|
57
|
+
Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}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=Xr(this.command,{showUsageString:!0});return[K.gray(`Unknown flag provided: ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?K.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
|
|
58
|
+
`)}case 3:{let e=`--${this.metadata.flag}`;return K.gray(`Flag ${K.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=K.whiteBright(String(this.metadata.value));return K.gray(`The provided value for the '${K.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=`'${K.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${K.white.bold(`--${t}`)}')`),o?K.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):K.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[K.gray("The following errors occurred:")],o=K.red(" > ");for(let[s,i]of e)t.push(K.gray(`${o}${K.white.bold(s)} cannot also be provided when using ${K.white.bold(i)}`));return t.push(K.gray(`${o}See more help with ${K.white.bold("--help")}`)),t.join(`
|
|
59
|
+
`)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return K.gray(`Flag ${K.white.bold(`--${e}`)} and ${K.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=W();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} (${Qr[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
|
|
60
|
+
${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? ${Ee?"Yes":"No"}`].join(`
|
|
61
61
|
`)}}}static buildMessageFromFlagData(e){let t=[`Flag ${K.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
|
|
62
62
|
${e.ambiguousMessage.split(`
|
|
63
63
|
`).map(o=>` ${o}`).join(`
|
|
64
|
-
`)}`):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=>K.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
|
|
65
|
-
`)),s=[];for(let[
|
|
66
|
-
`)})}_handleStdin(e){return e===2?(
|
|
67
|
-
`,t+=
|
|
64
|
+
`)}`):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=>K.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 Gn(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}m(Gn,"camelCaseString");function Ie(r){return r.replace(/[\s_]+/g,"-")}m(Ie,"kebabCaseString");function $e(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}m($e,"camelCaseToKebabCase");var du={type:"boolean",multiple:!1,short:"h"},pu={type:"boolean",multiple:!1},Z=new Map,fu=["init","run","push","actors push","pull","actors pull","call","actors call","actors start"],h=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;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;constructor(e,t,o,s){this.entrypoint=e,this.commandString=t,this.aliasUsed=o,this.subcommandAliasUsed=s;let i=W();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.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(zr(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,c]of Object.entries(this.ctor.args)){if(typeof c=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let u=Gn(a),l=o[n++];if(l)switch(c.argTag){default:this.args[u]=String(l),l==="-"&&c.stdin&&(this.args[u]=this._handleStdin(c.stdin)),c.catchAll&&(this.args[u]=o.slice(n-1).join(" "));break}else c.required&&i.set(a,c)}}if(i.size){process.exitCode=1,this._printMissingRequiredArgs(i);return}this._parseFlags(t,s);try{await this.run()}catch(n){f({message:n.message}),process.exitCode||=1}finally{!this.telemetryData.actorLanguage&&fu.includes(this.commandString)&&(await ke()).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 fn(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData)}}_userFlagNameToRegisteredName(e,t){let o=Ie($e(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ie($e(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ie($e(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:c,baseFlagName:u,rawBaseFlagName:l}=this._userFlagNameToRegisteredName(n,a),d=Gn(l),p=t.some(v=>v.kind==="option"&&v.name===u);if(a.exclusive?.length){let v=o.get(u)??new Set;for(let S of a.exclusive)v.add(this._commandFlagKeyToKebabCaseRegisteredName(S));o.set(u,v);for(let S of a.exclusive){let $=this._commandFlagKeyToKebabCaseRegisteredName(S),C=o.get($)??new Set;C.add(u),o.set($,C)}}let g=c.filter(v=>e[v]);if(g.length>1)throw new me({code:3,command:this.ctor,metadata:{flag:u}});let y=e[g[0]];if(!y&&a.required)throw new me({code:6,command:this.ctor,metadata:{flag:u,matcher:g[0]}});if(Array.isArray(y)){if(y.length>1)throw new me({code:3,command:this.ctor,metadata:{flag:u}});y=y[0]}if(p&&typeof y=="string"&&y.startsWith("=")&&(y=y.slice(1)),typeof y<"u")switch(a.flagTag){case"boolean":{this.flags[d]=l.startsWith("no-")?!y:y;break}case"integer":{let v=Number(y);if(Number.isNaN(v)||!Number.isInteger(v))throw new me({code:4,command:this.ctor,metadata:{flag:u,value:String(y)}});this.flags[d]=v;break}default:{if(this.flags[d]=y,y==="-"&&a.stdin){if(s)throw new me({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:u}});s=u,this.flags[d]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[d]=a.hasDefault);if(this.flags[d]&&a.choices&&!a.choices.includes(this.flags[d]))throw new me({code:5,command:this.ctor,metadata:{flag:u,choices:a.choices.map(v=>ni.white.bold(v)).join(", ")}});if(this.flags[d]==null&&(a.required||y!=null))throw new me({code:6,command:this.ctor,metadata:{flag:u,matcher:g[0],providedButReceivedNoValue:!!y}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let c of a){if(e[c]==null)continue;let u=e[n][0],l=e[c][0],d=m((p,g)=>typeof g=="boolean"?g?`--${p}`:`--no-${p}`:`--${p}=${g}`,"flagRepresentation");i.push([d(n,u),d(c,l)]);break}if(i.length)throw new me({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t;try{t=Xr(this.ctor,{showUsageString:!0})}catch{}let o=uu([...e.keys()].join(`
|
|
65
|
+
`)),s=[];for(let[n,a]of e){let c=`${n.padEnd(o)} ${a.description}`,u=mu(c,ce()-o-2),l=lu(u,o+2+2).trim();s.push(` ${ni.red(">")} ${l}`)}let i=[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,ni.gray(" See more help with --help")];t&&i.push("",t),f({message:i.join(`
|
|
66
|
+
`)})}_handleStdin(e){return e===2?(Ee?.toString("utf8")??"").trim():Ee}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:du}};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=Ie($e(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=pu),e}static registerCommand(e){if(ii(e,this),Z.set(this.name,this),this.aliases?.length)for(let t of this.aliases)Z.set(t,this);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)Z.set(t,this);if(this.subcommands?.length)for(let t of this.subcommands){if(Z.set(`${this.name} ${t.name}`,t),this.aliases?.length)for(let o of this.aliases)Z.set(`${o} ${t.name}`,t);if(this.hiddenAliases?.length)for(let o of this.hiddenAliases)Z.set(`${o} ${t.name}`,t);if(t.aliases?.length)for(let o of t.aliases){if(Z.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)Z.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)Z.set(`${s} ${o}`,t)}if(t.hiddenAliases?.length)for(let o of t.hiddenAliases){if(Z.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)Z.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)Z.set(`${s} ${o}`,t)}}}};async function Yn(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,u]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let l=Ie($e(u)).toLowerCase();l.startsWith("no-")?o.values[l.slice(3)]=!a:o.values[l]=a}}let i=new e(r,e.name,e.name);i.skipTelemetry=!0,await i._run(o)}m(Yn,"internalRunCommand");import{once as gu}from"events";async function Hn(){let r=await jr(),{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",c=>{s.push(c),n&&(clearTimeout(n),n=null)});try{await gu(o,"end",{signal:i.signal})}catch(c){if(c.name==="AbortError")return}n&&clearTimeout(n),r.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}m(Hn,"readStdin");import{gt as Tu}from"semver";import{existsSync as hu,mkdirSync as yu,readFileSync as wu,writeFileSync as Au}from"fs";import{dirname as bu}from"path";function Su(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}}}),ci({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}m(Su,"migrateStateV0ToV1");var vu={version:1};function ai(){let r=vr();if(!hu(r))return vu;let t=JSON.parse(wu(r,"utf-8"));return Su(t)?ai():t}m(ai,"useLocalState");function ci(r,e){let t={...r};e(t);let o=vr(),s=bu(o);yu(s,{recursive:!0}),Au(vr(),JSON.stringify(t,null," "))}m(ci,"updateLocalState");var eo=W(),qn=`Apify CLI/${eo.version} (https://github.com/apify/apify-cli)`,Cu=["https://1.1.1.1","https://8.8.8.8"];async function Iu(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Cu.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":qn},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)}m(Iu,"isOnline");async function $u(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":qn}});if(!e.ok)return T("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),_({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}),ci(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}m($u,"getLatestVersion");function Jn(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}m(Jn,"shouldSkipVersionCheck");async function Kn(r=!1){let e=ai(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>Mi,o=r||t&&await Iu(),s=o?await $u(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:eo.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=Tu(s,eo.version);return{currentVersion:eo.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}m(Kn,"useCLIVersionCheck");import{jaroWinkler as Eu}from"@skyra/jaro-winkler";import Ru from"js-levenshtein";function to(r){let e=[...Z.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),c=a[a.length-1].toLowerCase(),u=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,l=Ru(t,n),d=Eu(t,n),p=l<=2||d>=.975;return p?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:p,levenshtein:l,jaroWinkler:d}),u?{string:`${n} (alias for ${i.name})`,distance:d}:{string:`${n}`,distance:d}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}m(to,"useCommandSuggestions");var Ee=await Hn(),ir=W(),st=`Apify CLI/${ir.version} (https://github.com/apify/apify-cli)`;function zy(r){ir.installMethod!=="bundle"&&(_u(Re.version,Te)||(f({message:`${r} CLI requires Node.js version ${Te}. Your current version is ${Re.version}.`}),Re.exit(1)))}m(zy,"processVersionCheck");function xu(r){r.values.version===!0&&r.positionals.length===0&&(console.log(ir.fullVersionString),Re.exit(0))}m(xu,"printCLIVersionAndExitIfFlagUsed");function Pu(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(Zr(e)),Re.exit(0))}m(Pu,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function zn(r){let e=to(String(r)),t=ro.gray(`Command ${ro.whiteBright(r)} not found`);e.length&&(t+=`
|
|
67
|
+
`,t+=ro.gray(`Did you mean: ${e.map(o=>ro.whiteBright(o)).join(", ")}?`)),f({message:t}),Re.exit(1)}m(zn,"handleCommandNotFound");async function Ou(r,e){let t=Z.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){T("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(Jn()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await Yn(r,t,{flags_internalAutomaticCall:!0})}m(Ou,"runVersionCheck");async function Xy(r){T("CLIMetadata",{...ir,fullVersionString:ir.fullVersionString,argv:Re.argv,cwd:Re.cwd(),execPath:Re.execPath});let e=Re.argv.slice(2);T("ProcessArgv",e);let t=Wn({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});xu(t),Pu(t,r),await Ou(r,t.positionals[0]),T("TopLevelOptions",t);let[o,s]=t.positionals,i=!1,n=Z.get(o);if(!n)return zn(o);let a=n;if(n.subcommands?.length){if(!s)return n.printHelp();i=!0,a=Z.get(`${o} ${s}`)}if(!a)return zn(`${o} ${s}`);let c=[...e],u=c.indexOf(o);if(T("CommandNameIndex",u),c.splice(u,1),i){let p=c.indexOf(s);T("SubcommandNameIndex",p),c.splice(p,1)}T("RebuiltArgs",c),T("CommandToRun",a);let l=new a(r,i?`${n.name} ${s}`:n.name,o,i?s:void 0),d=l._buildParseArgsOption();T("ParserOptionsForCommand",d);try{let p=Wn({...d,args:c});await l._run(p),T("CommandArgsResult",p)}catch(p){let g=me.into(p,a);f({message:g.getPrettyMessage()}),Re.exit(1)}}m(Xy,"runCLI");import{join as Xu,resolve as Zu}from"path";import ui from"process";import{calculateRunDynamicMemory as Qu}from"@apify/actor-memory-expression";var w={string:ku,boolean:Nu,integer:Fu};function ku(r){return{flagTag:"string",builder:m(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:Ie($e(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}}m(ku,"stringFlag");function Nu(r){return{flagTag:"boolean",builder:m(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:Ie($e(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}}m(Nu,"booleanFlag");function Fu(r){return{flagTag:"integer",builder:m(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:Ie($e(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}}m(Fu,"integerFlag");import{mkdir as Bu,rename as ta,writeFile as Vu}from"fs/promises";import{dirname as Gu,join as Yu}from"path";import ea from"process";import{inspect as Hu}from"util";import{err as nr,ok as io}from"@sapphire/result";import{createPrompt as Du,isEnterKey as Lu,makeTheme as Mu,useKeypress as Uu,usePrefix as ju,useState as Xn}from"@inquirer/core";function li(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}m(li,"getBooleanValue");function Zn(r){return r?"Yes":"No"}m(Zn,"boolToString");var Qn=Du((r,e)=>{let t=Zn,[o,s]=Xn("idle"),[i,n]=Xn(""),a=Mu(),c=ju({status:o,theme:a});Uu((p,g)=>{if(Lu(p)){let y=li(i,r.default);n(t(y)),s("done"),e(y);return}if(p.name==="tab"){let y=Zn(!li(i,r.default));g.clearLine(0),g.write(y),n(y);return}if(p.name==="y"||p.name==="n"){let y=li(p.name,r.default);n(t(y)),s("done"),e(y);return}g.clearLine(0),g.write(i),n(g.line)});let u=i,l="";o==="done"?u=a.style.answer(i):l=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let d=a.style.message(r.message,o);return`${c} ${d}${l} ${u}`});var X=Oe(async({message:r,default:e})=>await Qn({message:r,default:e}));var qu=m(r=>Yu(r,Cr),"getDeprecatedLocalConfigPath"),so=new Map;async function Ne({cwd:r=ea.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:ea.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=so.get(r);if(o)return T("useActorConfig",{cacheHit:!0,config:o}),io(o);let s=zs(r),i=qu(r),n,a;try{n=le(s)}catch(u){return nr({message:`Failed to read local config at path: '${s}':`,cause:u,exists:!1,config:{}})}try{a=le(i)}catch(u){return nr({message:`Failed to read local config at path: '${i}':`,cause:u,exists:!1,config:{}})}if(n&&a&&t&&await Ju(i),!n&&!a)return so.set(r,{exists:!1,migrated:!1,config:{}}),io({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let u=await Wu(a,i,s);if(u.isErr())return nr(u.unwrapErr());n=u.unwrap(),c=!0}return so.set(r,{exists:!0,migrated:c,config:n||a||{}}),T("useActorConfig",{cacheHit:!1,config:so.get(r)}),io({exists:!0,migrated:c,config:n||a||{}})}m(Ne,"useActorConfig");async function Ju(r){if(!await X({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?'})){_({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 ta(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?f({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
68
68
|
${t.message||t}`}):f({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
69
|
-
${
|
|
70
|
-
${
|
|
71
|
-
${
|
|
72
|
-
${
|
|
69
|
+
${Hu(t,{showHidden:!1})}`})}}m(Ju,"handleBothConfigVersionsFound");var Ku=["name","version","buildTag"];async function Wu(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=zu(o)),o={actorSpecification:Vs,environmentVariables:r?.env||void 0,...Ku.reduce((i,n)=>(i[n]=r[n],i),{})},!await X({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 nr({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 Bu(Gu(t),{recursive:!0}),await Vu(t,JSON.stringify(o,null," "))}catch(i){let n=i;return nr({message:`Failed to write the new "actor.json" file to path: '${t}'.
|
|
70
|
+
${n.message||n}`,exists:!0,config:o})}try{await ta(e,`${e}.deprecated`)}catch(i){let n=i;_({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
71
|
+
${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.'}),io(o)}m(Wu,"handleMigrationFlow");function zu(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}m(zu,"updateLocalConfigStructure");var em=Xu(fe("default"),"INPUT.json"),yt=class extends h{static name="calculate-memory";static description="Calculates the Actor\u2019s dynamic memory usage based on a memory expression from actor.json, input data, and run options.";static flags={input:w.string({description:"Path to the input JSON file used for the calculation.",required:!1,default:em}),defaultMemoryMbytes:w.string({description:"Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.",required:!1}),build:w.string({description:"Actor build version or build tag to evaluate the expression with.",required:!1}),timeoutSecs:w.integer({description:"Maximum run timeout, in seconds.",required:!1}),maxItems:w.integer({description:"Maximum number of items Actor can output.",required:!1}),maxTotalChargeUsd:w.integer({description:"Maximum total charge in USD.",required:!1})};async run(){let{input:e,memoryExpression:t,minMemory:o,maxMemory:s,runOptions:i}=await this.prepareMemoryArguments();if(!t)throw new Error("No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.");let n=Zu(ui.cwd(),e),a=le(n)??{};b({message:`Evaluating memory expression: ${t}`});try{let c=await Qu(t,{input:a,runOptions:i}),u=Math.min(Math.max(c,o),s);E({message:`Calculated memory: ${u} MB`,stdout:!0})}catch(c){f({message:`Memory calculation failed: ${c.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...o}=this.flags,s=t,i=0,n=1/0;return s||({defaultMemoryMbytes:s,minMemoryMbytes:i=i,maxMemoryMbytes:n=n}=await this.getExpressionFromConfig()),{memoryExpression:s,minMemory:i,maxMemory:n,input:e,runOptions:o}}async getExpressionFromConfig(){let e=ui.cwd(),t=await Ne({cwd:e});if(t.isErr()){let{message:s,cause:i}=t.unwrapErr();return f({message:`${s}${i?`
|
|
72
|
+
${i.message}`:""}`}),ui.exitCode=5,{}}let{config:o}=t.unwrap();return{defaultMemoryMbytes:o?.defaultMemoryMbytes?.toString(),minMemoryMbytes:o?.minMemoryMbytes,maxMemoryMbytes:o?.maxMemoryMbytes}}};import{APIFY_ENV_VARS as am}from"@apify/consts";import ar from"process";import{pipeline as tm}from"stream/promises";import{MemoryStorage as rm}from"@crawlee/memory-storage";import{ApifyClient as om}from"apify-client";import{ACTOR_ENV_VARS as ra,APIFY_ENV_VARS as oa,KEY_VALUE_STORE_KEYS as sm,LOCAL_ACTOR_ENV_VARS as im}from"@apify/consts";var cr={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},mi=m(async()=>{let r=ar.env[oa.TOKEN];if(r)return r;let e=await U();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"),at=m(async(r={},e=Reflect.has(ar.env,oa.IS_AT_HOME))=>{let t=ge();if(t&&!e)return new rm({localDataDirectory:t,...r});let o=await mi();return new om({...qt(o),...r})},"getApifyStorageClient"),lr=m(r=>{let e=ra[`DEFAULT_${r}_ID`];return ar.env[e]||im[e]},"getDefaultStorageId"),di=m(async r=>{let e=await at(),t=lr(cr.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await tm(o.value,ar.stdout,{end:!1})},"outputRecordFromDefaultStore"),sa=m(async()=>di(ar.env[ra.INPUT_KEY]||sm.INPUT),"outputInputFromDefaultStore");function nm(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}m(nm,"stringArg");var A={string:nm};var wt=class extends h{static name="charge";static description="Charge for a specific event in the pay-per-event Actor run.";static args={eventName:A.string({description:"Name of the event to charge for",required:!0})};static flags={count:w.integer({description:"Number of events to charge",required:!1,default:1}),"idempotency-key":w.string({description:"Idempotency key for the charge request",required:!1}),"test-pay-per-event":w.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 mi(),a=await Jt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[am.ACTOR_RUN_ID];if(!c)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(c).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: ${c}).`,stdout:!0}),await a.run(c).charge({eventName:e,count:t,idempotencyKey:s})}};import{mkdir as dm,writeFile as lo}from"fs/promises";import vt from"path";import fa from"process";import{compile as uo}from"json-schema-to-typescript";import{existsSync as cm,writeFileSync as lm}from"fs";import{join as ur}from"path";import{cloneDeep as um}from"es-toolkit";import{KEY_VALUE_STORE_KEYS as mm}from"@apify/consts";import{validateInputSchema as na}from"@apify/input_schema";var ia=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],At=m(async({forcePath:r,cwd:e})=>{if(r)return{inputSchema:le(r),inputSchemaPath:r};let t=Me(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=ur(e,Ir,t.input);return{inputSchema:le(o),inputSchemaPath:o}}for(let o of ia){let s=ur(e,o);if(cm(s))return{inputSchema:le(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:ur(e,ia[0])}},"readInputSchema"),no=m(async({forcePath:r,cwd:e,getMessage:t})=>{let{inputSchema:o,inputSchemaPath:s}=await At({forcePath:r,cwd:e});if(!o)throw new Error(`Input schema has not been found at ${s}.`);b({message:t(s)});let i=new Ht({strict:!1});return na(i,o),{inputSchema:o,inputSchemaPath:s}},"readAndValidateInputSchema"),ao=m(({cwd:r,key:e,label:t,getRef:o})=>{let s=Me(r),i=o?o(s):s?.storages?.[e];if(typeof i=="object"&&i!==null)return{schema:i,schemaPath:null};if(typeof i=="string"){let n=ur(r,Ir,i),a=le(n);return a?{schema:a,schemaPath:n}:(_({message:`${t} schema file not found at ${n} (referenced in '${D}').`}),null)}return null},"readStorageSchema"),aa=m(({cwd:r})=>{let e=ao({cwd:r,key:"dataset",label:"Dataset"});return e?{datasetSchema:e.schema,datasetSchemaPath:e.schemaPath}:null},"readDatasetSchema"),ca=m(({cwd:r})=>{let e=ao({cwd:r,key:"output",label:"Output",getRef:m(t=>t?.output,"getRef")});return e?{outputSchema:e.schema,outputSchemaPath:e.schemaPath}:null},"readOutputSchema"),co=m(async r=>{let e={};try{let{inputSchema:t}=await At({cwd:r});if(t){let o=new Ht({strict:!1});na(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){_({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=fe(),o=ur(r,t,`${mm.INPUT}.json`);lm(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),la=m(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),ua=m((r,e)=>{let t=um(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");import{cloneDeep as bt}from"es-toolkit";function pi(r){let e=bt(r);if(!e.properties||typeof e.properties!="object")return e;let t=e.properties,o=new Set(Array.isArray(e.required)?e.required:[]);for(let[s,i]of Object.entries(t))i.default!==void 0&&o.add(s),i.type==="object"&&i.properties&&(t[s]=pi(i));return e.required=Array.from(o),e}m(pi,"makePropertiesRequired");function St(r){let e=bt(r);if(delete e.required,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s.type==="object"&&s.properties&&(t[o]=St(s))}return e}m(St,"clearAllRequired");function ye(r){let e=bt(r);if(delete e.title,e.properties&&typeof e.properties=="object"){let t=e.properties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=ye(s))}e.items&&typeof e.items=="object"&&(e.items=ye(e.items));for(let t of["allOf","anyOf","oneOf"])Array.isArray(e[t])&&(e[t]=e[t].map(o=>o&&typeof o=="object"?ye(o):o));for(let t of["definitions","$defs"])if(e[t]&&typeof e[t]=="object"&&!Array.isArray(e[t])){let o=e[t];for(let[s,i]of Object.entries(o))i&&typeof i=="object"&&(o[s]=ye(i))}e.additionalProperties&&typeof e.additionalProperties=="object"&&(e.additionalProperties=ye(e.additionalProperties));for(let t of["if","then","else","not"])e[t]&&typeof e[t]=="object"&&(e[t]=ye(e[t]));if(e.patternProperties&&typeof e.patternProperties=="object"&&!Array.isArray(e.patternProperties)){let t=e.patternProperties;for(let[o,s]of Object.entries(t))s&&typeof s=="object"&&(t[o]=ye(s))}return e}m(ye,"stripTitles");function ma(r){let e=r.fields;if(!e||typeof e!="object"||!e.properties||typeof e.properties!="object")return null;let t=bt(e);return t.type||(t.type="object"),t}m(ma,"prepareFieldsSchemaForCompilation");function da(r){let e=r.properties;if(!e||typeof e!="object"||Object.keys(e).length===0)return null;let t=bt(e);for(let s of Object.values(t))s&&typeof s=="object"&&delete s.template;let o={type:r.type||"object",properties:t};return Array.isArray(r.required)&&(o.required=[...r.required]),o}m(da,"prepareOutputSchemaForCompilation");function pa(r){let e=r.collections;if(!e||typeof e!="object")return[];let t=[];for(let[o,s]of Object.entries(e)){if(!s||typeof s!="object")continue;let i=s.jsonSchema;if(!i||typeof i!="object"||Object.keys(i).length===0)continue;let n=bt(i);n.type||(n.type="object"),t.push({name:o,schema:n})}return t}m(pa,"prepareKvsCollectionsForCompilation");var pm=`
|
|
73
73
|
// biome-ignore-all lint: generated
|
|
74
74
|
// biome-ignore-all format: generated
|
|
75
75
|
/* eslint-disable */
|
|
@@ -91,14 +91,14 @@ Reads the input schema from one of these locations (in priority order):
|
|
|
91
91
|
3. .actor/INPUT_SCHEMA.json
|
|
92
92
|
4. INPUT_SCHEMA.json
|
|
93
93
|
|
|
94
|
-
Optionally specify custom schema path to use.`;static flags={output:w.string({char:"o",description:"Directory where the generated files should be outputted. Defaults to src/.generated/actor/ to stay within the typical tsconfig rootDir.",required:!1,default:vt.join("src",".generated","actor")}),strict:w.boolean({description:"Whether generated interfaces should be strict (no index signature [key: string]: unknown).",required:!1,default:!0}),"all-optional":w.boolean({description:"Mark all properties as optional in generated types.",required:!1,default:!1})};static args={path:A.string({required:!1,description:"Optional path to the input schema file. If not provided, searches default locations."})};async run(){let e=
|
|
95
|
-
`),"utf-8"),E({message:`Generated types written to ${u}`})}};var Ct=class extends h{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
|
|
94
|
+
Optionally specify custom schema path to use.`;static flags={output:w.string({char:"o",description:"Directory where the generated files should be outputted. Defaults to src/.generated/actor/ to stay within the typical tsconfig rootDir.",required:!1,default:vt.join("src",".generated","actor")}),strict:w.boolean({description:"Whether generated interfaces should be strict (no index signature [key: string]: unknown).",required:!1,default:!0}),"all-optional":w.boolean({description:"Mark all properties as optional in generated types.",required:!1,default:!1})};static args={path:A.string({required:!1,description:"Optional path to the input schema file. If not provided, searches default locations."})};async run(){let e=fa.cwd(),{inputSchema:t}=await no({forcePath:this.args.path,cwd:e,getMessage:m(u=>u?`Generating types from input schema at ${u}`:`Generating types from input schema embedded in '${D}'`,"getMessage")}),o="input",s=this.flags.allOptional?St(t):pi(t),i={bannerComment:pm,maxItems:-1,unknownAny:!0,format:!0,additionalProperties:!this.flags.strict,$refOptions:{resolve:{external:!1,file:!1,http:!1}}},n=await uo(ye(s),o,i),a=vt.resolve(e,this.flags.output);await dm(a,{recursive:!0});let c=vt.join(a,`${o}.ts`);if(await lo(c,n,"utf-8"),E({message:`Generated types written to ${c}`}),!this.args.path){let u=await Promise.allSettled([this.generateDatasetTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateOutputTypes({cwd:e,outputDir:a,compileOptions:i}),this.generateKvsTypes({cwd:e,outputDir:a,compileOptions:i})]),l=["Dataset","Output","Key-Value Store"],d=!1;for(let[p,g]of u.entries())g.status==="rejected"&&(d=!0,f({message:`Failed to generate types for ${l[p]} schema: ${g.reason instanceof Error?g.reason.message:String(g.reason)}`}));d&&(fa.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:o}){let s=aa({cwd:e});if(!s)return;let{datasetSchema:i,datasetSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Dataset schema at ${n}`}):b({message:`[experimental] Generating types from Dataset schema embedded in '${D}'`});let a=ma(i);if(!a){_({message:"Dataset schema has no fields defined, skipping type generation."});return}let c="dataset",u=this.flags.allOptional?St(a):a,l=await uo(ye(u),c,o),d=vt.join(t,`${c}.ts`);await lo(d,l,"utf-8"),E({message:`Generated types written to ${d}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:o}){let s=ca({cwd:e});if(!s)return;let{outputSchema:i,outputSchemaPath:n}=s;n?b({message:`[experimental] Generating types from Output schema at ${n}`}):b({message:`[experimental] Generating types from Output schema embedded in '${D}'`});let a=da(i);if(!a){_({message:"Output schema has no properties defined, skipping type generation."});return}let c="output",u=this.flags.allOptional?St(a):a,l=await uo(ye(u),c,o),d=vt.join(t,`${c}.ts`);await lo(d,l,"utf-8"),E({message:`Generated types written to ${d}`})}async generateKvsTypes({cwd:e,outputDir:t,compileOptions:o}){let s=ao({cwd:e,key:"keyValueStore",label:"Key-Value Store"});if(!s)return;let{schema:i,schemaPath:n}=s;n?b({message:`[experimental] Generating types from Key-Value Store schema at ${n}`}):b({message:`[experimental] Generating types from Key-Value Store schema embedded in '${D}'`});let a=pa(i);if(a.length===0){_({message:"Key-Value Store schema has no collections with JSON schemas, skipping type generation."});return}let c=[];for(let{name:l,schema:d}of a){let p=this.flags.allOptional?St(d):d,g=await uo(ye(p),l,{...o,bannerComment:c.length===0?o.bannerComment:""});c.push(g)}let u=vt.join(t,"key-value-store.ts");await lo(u,c.join(`
|
|
95
|
+
`),"utf-8"),E({message:`Generated types written to ${u}`})}};var Ct=class extends h{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 sa()}};import{ACTOR_ENV_VARS as fi,APIFY_ENV_VARS as fm}from"@apify/consts";var It=class extends h{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static args={key:A.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[fm.IS_AT_HOME])){f({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[fi.DEFAULT_KEY_VALUE_STORE_ID];if(!t){f({message:`Missing environment variable: ${fi.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let o=await at();if(!await o.keyValueStore(t).get()){f({message:`Key-Value store with ID '${t}' was not found. Ensure the store exists and that the correct ID is set in ${fi.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let i=await o.keyValueStore(t).getRecordPublicUrl(e);console.log(i)}};var $t=class extends h{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static args={key:A.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;await di(e)}};var Et=class extends h{static name="push-data";static description=`Saves data to Actor's run default dataset.
|
|
96
96
|
|
|
97
97
|
Accept input as:
|
|
98
98
|
- JSON argument:
|
|
99
99
|
$ apify actor push-data {"key": "value"}
|
|
100
100
|
- Piped stdin:
|
|
101
|
-
$ cat ./test.json | apify actor push-data`;static args={item:A.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
|
|
101
|
+
$ cat ./test.json | apify actor push-data`;static args={item:A.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||Ee;if(!t){f({message:"No item was provided."});return}let o=await at(),s=lr(cr.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 Rt=class extends h{static name="set-value";static description=`Sets or removes record into the default key-value store associated with the Actor run.
|
|
102
102
|
|
|
103
103
|
It is possible to pass data using argument or stdin.
|
|
104
104
|
|
|
@@ -109,137 +109,140 @@ Passing data using stdin with pipe:
|
|
|
109
109
|
$ cat ./my-text-file.txt | apify actor set-value KEY --contentType text/plain`;static args={key:A.string({required:!0,description:"Key of the record in key-value store."}),value:A.string({required:!1,description:`Record data, which can be one of the following values:
|
|
110
110
|
- If empty, the record in the key-value store is deleted.
|
|
111
111
|
- If no \`contentType\` flag is specified, value is expected to be any JSON string value.
|
|
112
|
-
- If options.contentType is set, value is taken as is.`})};static flags={contentType:w.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,
|
|
113
|
-
Available versions for this tag: ${l.map(C=>
|
|
114
|
-
`),stdout:!0}),s){try{await
|
|
115
|
-
${
|
|
116
|
-
${a.message}`}),
|
|
117
|
-
${
|
|
118
|
-
`}):o.title?ve({message:`Calling ${
|
|
119
|
-
`}):ve({message:`Calling ${
|
|
120
|
-
`}));let g;try{p&&
|
|
121
|
-
${
|
|
122
|
-
`):console.error()}catch(y){_({message:"Can not get log:"}),console.error(y)}if(g=await r.run(g.id).get(),u)for(;!
|
|
123
|
-
Reads input from local key-value store by default.`;static flags={...
|
|
124
|
-
`),stdout:!this.flags.json})}if(this.flags.json){F(p);return}if(this.flags.silent||R({message:["",`${
|
|
125
|
-
`),stdout:!0}),this.flags.outputDataset){let S=p.defaultDatasetId,$,C=4;do{if($=await o.dataset(S).get(),$?.itemCount)break;await new Promise(N=>{setTimeout(N,250)})}while(C--);let
|
|
112
|
+
- If options.contentType is set, value is taken as is.`})};static flags={contentType:w.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 at()).keyValueStore(lr(cr.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var mo=class extends h{static name="actor";static description="Manages runtime data operations inside of a running Actor.";static subcommands=[Rt,Et,$t,It,Ct,wt,yt,Tt];async run(){this.printHelp()}};import Fe from"chalk";import gm from"process";async function He({providedActorNameOrId:r,client:e}){let t=await U(),o=t.username||t.id,s=Me(gm.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"}}m(He,"resolveActorContext");var _t=class extends h{static name="create";static description="Creates a new build of the Actor.";static flags={tag:w.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:w.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:w.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:A.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 I(),a=await He({providedActorNameOrId:i,client:n});if(!a.valid){f({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let c=await n.actor(a.id).get(),l=Dr(c.versions,C=>C.buildTag??"latest")[e??"latest"],d=c.versions.find(C=>C.versionNumber===t),p,g=e;if(d){if(e&&(!l||!l.some(C=>C.versionNumber===t))){f({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}p=t,g=d.buildTag??"latest"}else if(l&&(p=l[0].versionNumber,g=e??"latest",l.length>1&&!t)){f({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
|
|
113
|
+
Available versions for this tag: ${l.map(C=>Fe.yellow(C.versionNumber)).join(", ")}`,stdout:!0});return}if(!p){f({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 y=await n.actor(a.id).build(p,{tag:e});if(o){F(y);return}let v=[`${Fe.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${Fe.gray(y.actId)})`,` ${Fe.yellow("Version")}: ${p} (tagged with ${Fe.yellow(g)})`,"",`${Fe.greenBright("Build Started")} (ID: ${Fe.gray(y.id)})`,` ${Fe.yellow("Build Number")}: ${y.buildNumber} (will get tagged once finished)`,` ${Fe.yellow("Started")}: ${Y.display(y.startedAt)}`,""],S=`https://console.apify.com/actors/${y.actId}/builds/${y.buildNumber}`,$=`${Fe.blue("View in Apify Console")}: ${S}`;if(R({message:v.join(`
|
|
114
|
+
`),stdout:!0}),s){try{await Pe({job:y,apifyClient:n})}catch(C){f({message:`Failed to print log for build with ID "${y.id}": ${C.message}`,stdout:!0})}R({message:"",stdout:!0})}R({message:$,stdout:!0})}};var po=class extends _t{static name="build"};import wa from"process";import{DownloadItemsFormat as bm}from"apify-client";import ne from"chalk";import{access as hm,readFile as ym}from"fs/promises";import wm,{resolve as ga}from"path";import De from"process";import Am from"mime";function ha(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Kt(r);s&&(Am.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}}m(ha,"resolveInput");async function xt(r,e,t){let o,s;if(!e&&!t){let i=Ee;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=n,s="stdin"}catch(n){return f({message:`Cannot parse JSON input from standard input.
|
|
115
|
+
${n.message}`}),De.exitCode=5,!1}}if(e)switch(e[0]){case"-":return f({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),De.exitCode=5,!1;default:{let i=await hm(ga(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||wm.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return f({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),De.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=a,s="input"}catch(a){return f({message:`Cannot parse JSON input.
|
|
116
|
+
${a.message}`}),De.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return f({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),De.exitCode=5,!1;default:{let i=ga(r,t),n;try{let a=await ym(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=c,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return f({message:"The provided input is invalid. It should be an object, not an array."}),De.exitCode=5,!1;o=a,s=t}catch{return f({message:`Cannot read input file at path "${i}".
|
|
117
|
+
${n.message}`}),De.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}m(xt,"getInputOverride");import gi from"process";import fo from"chalk";import{ACTOR_JOB_STATUSES as qe}from"@apify/consts";var ya=[qe.SUCCEEDED,qe.ABORTED,qe.FAILED,qe.TIMED_OUT];async function*Pt(r,e){let t=gi.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:u,printRunLogs:l}=e,d=i==="Actor"?"actor":"task",p=ha(t,a);c||(i==="Actor"?ve({message:`Calling ${i} ${o.userFriendlyId} (${fo.gray(o.id)})
|
|
118
|
+
`}):o.title?ve({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${fo.gray(o.id)})
|
|
119
|
+
`}):ve({message:`Calling ${i} ${o.userFriendlyId} (${fo.gray(o.id)})
|
|
120
|
+
`}));let g;try{p&&i==="Actor"?g=await r[d](o.id).start(p.inputToUse,{...s,contentType:p.contentType}):g=await r[d](o.id).start(void 0,s)}catch(y){throw y.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):y}if(yield g,!c&&l)try{await Pe({job:g,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
|
|
121
|
+
${fo.gray("Timeout for printing logs was hit, there may be future logs.")}
|
|
122
|
+
`):console.error()}catch(y){_({message:"Can not get log:"}),console.error(y)}if(g=await r.run(g.id).get(),u)for(;!ya.includes(g.status)&&(g=await r.run(g.id).get(),!ya.includes(g.status));)await new Promise(y=>{setTimeout(y,1e3)});c||(g.status===qe.SUCCEEDED?E({message:`${i} finished.`}):g.status===qe.RUNNING?_({message:`${i} is still running!`}):g.status===qe.ABORTED||g.status===qe.ABORTING?(_({message:`${i} was aborted!`}),gi.exitCode=3):(f({message:`${i} failed!`}),gi.exitCode=1)),yield g}m(Pt,"runActorOrTaskOnCloud");var Ot=m(r=>({build:w.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:w.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:w.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var Je=class r extends h{static name="call";static description=`Executes Actor remotely using your authenticated account.
|
|
123
|
+
Reads input from local key-value store by default.`;static flags={...Ot("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.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:w.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":w.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:A.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 '${D}' file.`})};async run(){let e=wa.cwd(),t=Me(e)||{},o=await I(),s=await U(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){f({message:"You cannot use both the --json and --output-dataset flags when running this command."}),wa.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),u={waitForFinish:2};this.flags.build&&(u.build=this.flags.build),this.flags.timeout&&(u.timeout=this.flags.timeout),this.flags.memory&&(u.memory=this.flags.memory);let l=await xt(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let d=!1,p,g,y,v=Pt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:u,type:"Actor",inputOverride:l?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let S of v)if(p=S,!d&&(d=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${S.id}`,y=`https://console.apify.com/storage/datasets/${S.defaultDatasetId}`;let $=[`${ne.yellow("Started")}: ${Y.display(S.startedAt)}`];S.containerUrl&&$.push(`${ne.yellow("Container URL")}: ${ne.blue(S.containerUrl)}`);let C=p.buildNumber.split(".").slice(0,2).join("."),P=c.versions.find(M=>M.versionNumber===C),N=Object.entries(c.taggedBuilds??{}).find(([,M])=>M.buildNumber===S.buildNumber)?.[0],k=[`${ne.yellow("Build")}:`,ne.cyan(p.buildNumber)];N?k.push(`(${ne.yellow(N)})`):k.push(`(${ne.gray("N/A")})`),P&&k.push(`| ${ne.gray("Actor version:")} ${ne.cyan(P.versionNumber)} (${ne.yellow(P.buildTag)})`),$.push(k.join(" ")),$.push(`${ne.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),$.push(`${ne.yellow("Memory")}: ${p.options.memoryMbytes} MB`),$.push(`${ne.blue("View on Apify Console")}: ${g}`,""),R({message:$.join(`
|
|
124
|
+
`),stdout:!this.flags.json})}if(this.flags.json){F(p);return}if(this.flags.silent||R({message:["",`${ne.blue("Export results")}: ${y}`,`${ne.blue("View on Apify Console")}: ${g}`].join(`
|
|
125
|
+
`),stdout:!0}),this.flags.outputDataset){let S=p.defaultDatasetId,$,C=4;do{if($=await o.dataset(S).get(),$?.itemCount)break;await new Promise(N=>{setTimeout(N,250)})}while(C--);let P=await o.dataset(S).downloadItems(bm.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 Sm from"cli-table3";var vm={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},Tm={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Cm={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 Im={[-1]:void 0,0:vm,1:Tm,2:Cm};function $m(r){return Array.from({length:r},()=>"cyan")}m($m,"generateHeaderColors");var Em=process.stdout.columns??100,go=Symbol.for("@apify/cli:responsive-table:skip-column"),B=class r{static{m(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=$m(t.length),s=e===0||e===2,i=Im[e],n=[],a=[],c=[];for(let l of t)this.options.hiddenColumns?.includes(l)||this.rows.some(d=>d[l]===go)||(n.push(this.options.columnAlignments?.[l]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[l]?.label??l),c.push(this.options.breakpointOverrides?.small?.[l]?.valueFrom??l)):(a.push(l),c.push(l)));let u=new Sm({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let l of this.rows){let d=c.map(p=>l[p]);u.push(d)}return u.toString()}static isSmallTerminal(){return Em<100}};var ho="\u200B",yo="\u200B\u200B",Aa=new B({allColumns:[ho,yo],mandatoryColumns:[ho,yo],columnAlignments:{[ho]:"left",[yo]:"right"}}),wo=class extends h{static name="info";static description="Get information about an Actor.";static flags={readme:w.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:w.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:A.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 I(),n=await He({providedActorNameOrId:e,client:i});if(!n.valid){f({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),c=await i.user(a.userId).get();a.actorMaker=c;for(let p of Object.values(a.taggedBuilds??{})){if(!p.buildId)continue;let g=await i.build(p.buildId).get();p.build=g}if(s){F(a);return}let u=a.taggedBuilds?.latest;if(t){if(!u){f({message:"No README found for this Actor.",stdout:!0});return}if(!u.build?.readme){f({message:"No README found for this Actor.",stdout:!0});return}R({message:u.build.readme,stdout:!0})}if(o){if(!u){f({message:"No input schema found for this Actor.",stdout:!0});return}if(!u.build?.inputSchema){f({message:"No input schema found for this Actor.",stdout:!0});return}R({message:u.build.inputSchema,stdout:!0})}let l=[`Information about Actor ${O.yellow(`${a.username}/${a.name}`)} (${O.gray(a.id)})`,""];a.title&&l.push(`${O.yellow("Title:")} ${O.bold(a.title)}`),a.description&&l.push(`${O.yellow("Description:")} ${a.description}`),l.push(`${O.yellow("Created at:")} ${O.cyan(Y.display(a.createdAt))} ${O.gray("|")} ${O.yellow("Updated at:")} ${O.cyan(Y.display(a.modifiedAt))}`),a.actorMaker&&(l.push("",`${O.yellow("Made by:")} ${O.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(l[l.length-1]+=` ${O.bgGray("Maintained by Apify")}`)),a.isPublic?l.push("",`${O.yellow("Actor is")} ${O.green("PUBLIC")}`):l.push("",`${O.yellow("Actor is")} ${O.cyan("PRIVATE")}`),a.isDeprecated&&l.push("",`${O.yellow("Actor is")} ${O.red("DEPRECATED")}`);let d=Reflect.get(a,"pricingInfos");if(d?.length){let p=d.at(-1);switch(p.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(l.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let g=p.trialMinutes*60*1e3,y=Xt.format(g);l.push(` ${O.yellow("Trial duration:")} ${O.bold(y)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=p.pricePerUnitUsd*1e3;l.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{l.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay per event")}`);let g=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let S of g)Aa.pushRow({[ho]:S.eventTitle,[yo]:O.bold(`$${S.eventPriceUsd.toFixed(2)}`)});let v=Aa.render(0).split(`
|
|
126
126
|
`);v.splice(1,1),l.push(v.join(`
|
|
127
|
-
`));break}case"FREE":{l.push(`${
|
|
128
|
-
`),stdout:!0})}};import{Time as
|
|
127
|
+
`));break}case"FREE":{l.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);break}default:l.push(`${O.yellow("Pricing information:")} ${O.bgGray(`Unknown pricing model (${O.yellow(p.pricingModel)})`)}`)}}else l.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(l.push("",O.yellow("SEO information:")),a.seoTitle&&l.push(` ${O.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&l.push(` ${O.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){l.push("",O.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&l.push(` ${O.yellow("-")} ${O.cyan(p.buildNumber)} ${O.gray("/")} ${O.yellow("latest")}`);for(let[g,y]of Object.entries(a.taggedBuilds))g!=="latest"&&l.push(` ${O.yellow("-")} ${O.cyan(y.buildNumber)} ${O.gray("/")} ${O.yellow(g)}`)}R({message:l.join(`
|
|
128
|
+
`),stdout:!0})}};import{Time as Rm}from"@sapphire/duration";import Q from"chalk";import Ue from"chalk";function xe(r){switch(r){case"READY":return Ue.green("Ready");case"RUNNING":return Ue.blue("Running");case"SUCCEEDED":return Ue.green("Succeeded");case"FAILED":return Ue.red("Failed");case"ABORTING":return Ue.yellow("Aborting");case"ABORTED":return Ue.red("Aborted");case"TIMING-OUT":return Ue.yellow("Timing Out");case"TIMED-OUT":return Ue.red("Timed Out");default:return Ue.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}m(xe,"prettyPrintStatus");var _m={"TIMED-OUT":Q.gray("after"),"TIMING-OUT":Q.gray("after"),ABORTED:Q.gray("after"),ABORTING:Q.gray("after"),FAILED:Q.gray("after"),READY:Q.gray("for"),RUNNING:Q.gray("for"),SUCCEEDED:Q.gray("after")},xm=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"}}}}),Pm=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"}}}}),Ao=class extends h{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static flags={my:w.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:w.integer({description:"Number of Actors that will be skipped.",default:0}),limit:w.integer({description:"Number of Actors that will be listed.",default:20}),desc:w.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 I(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){F(a);return}b({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let c={...a,items:await Promise.all(a.items.map(async d=>{let p=await n.actor(d.id).get(),g=await n.actor(d.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...d,actor:p??null,lastRun:g.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){F(c);return}let u=s?Pm:xm,l=c.items.reduce((d,p)=>{let g=`${p.username}/${p.name}`;return g.length>d?g.length:d},0)+2+6;for(let d of c.items){let p=d.stats.lastRunStartedAt?zt.display(d.stats.lastRunStartedAt):"",g=d.lastRun?(()=>{if(d.lastRun.finishedAt)return ue.format(d.lastRun.finishedAt.getTime()-d.lastRun.startedAt.getTime());let S=Date.now()-d.lastRun.startedAt.getTime();return`${ue.format(S)}\u2026`})():"",y=d.actor?(()=>{let S=Object.entries(d.actor.taggedBuilds??{}).find(([$,C])=>C.buildNumber===d.actor.defaultRunOptions.build||$===d.actor.defaultRunOptions.build);return S?`${Q.yellow(S[0])} / ${Q.cyan(S[1].buildNumber??d.actor.defaultRunOptions.build)}`:Q.gray("Unknown")})():Q.gray("Unknown"),v=(()=>{if(d.lastRun){let $=[xe(d.lastRun.status)];if(g&&$.push(_m[d.lastRun.status],Q.cyan(g)),d.lastRun.finishedAt){let C=Date.now()-d.lastRun.finishedAt.getTime();C<Rm.Week?$.push(`
|
|
129
129
|
`,Q.gray(`${ue.format(C)} ago`)):$.push(`
|
|
130
|
-
`,Q.gray("On",
|
|
131
|
-
${Q.gray(`${d.username}/${d.name}`)}`,Runs:
|
|
132
|
-
`);if(t)for(let
|
|
133
|
-
${
|
|
130
|
+
`,Q.gray("On",an.display(d.lastRun.finishedAt)))}return $.join(" ")}return""})();u.pushRow({Name:`${d.title}
|
|
131
|
+
${Q.gray(`${d.username}/${d.name}`)}`,Runs:B.isSmallTerminal()&&l>=56?go:Q.cyan(`${d.stats?.totalRuns??0}`),"Last run started at":p,"Last run":p,"Last run status":d.lastRun?xe(d.lastRun.status):"","Modified at":zt.display(d.modifiedAt),Builds:d.actor?Q.cyan(d.actor.stats.totalBuilds):Q.gray("Unknown"),"Last run duration":B.isSmallTerminal()?go:Q.cyan(g),"Default build":y,_Small_LastRunText:v})}R({message:u.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 ba,readdirSync as Om,writeFileSync as Sa}from"fs";import{dirname as km,join as Nm}from"path";import va from"process";import Fm from"adm-zip";import Dm from"axios";import Ta from"jju";import{gt as Lm}from"semver";import Mm from"tiged";var Ca=m(async(r,e)=>{let{data:t}=await Dm.get(r,{responseType:"arraybuffer"}),o=new Fm(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),kt=class extends h{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:w.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version",required:!1}),dir:w.string({description:"Directory where the Actor should be pulled to",required:!1})};static args={actorId:A.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=va.cwd(),t=await Ne({cwd:e});if(t.isErr()){f({message:t.unwrapErr().message}),va.exitCode=5;return}let{config:o}=t.unwrap(),s=await U(),i=await I(),n=!this.args.actorId,a=s.username||s.id,c=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!c)throw new Error("Cannot find Actor in this directory.");let u;try{u=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!u)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:l,versions:d}=u,p=m(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!u.versions.length)throw new Error(`Actor ${c} has no versions.`);let g=null;if(this.flags.version&&(g=d.find(S=>S.versionNumber===this.flags.version),!g))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);g||(g=d.reduce((S,$)=>Lm(`${$.versionNumber}.0`,`${S.versionNumber}.0`)?$:S));let y=n?e:Nm(e,this.flags.dir??l);if(ba(y,{recursive:!0}),!n&&Om(y).length!==0){f({message:`Directory ${y} is not empty. Please empty it or choose another directory.`});return}let{sourceType:v}=g;switch(v){case"TARBALL":{g.tarballUrl||p(),await Ca(g.tarballUrl,y);break}case"SOURCE_FILES":{g.sourceFiles||p();let{sourceFiles:S}=g;for(let $ of S){let C=km($.name);if(ba(`${y}/${C}`,{recursive:!0}),!$.folder){let P=$.format==="BASE64"?Buffer.from($.content,"base64").toString():$.content;if($.name===D){let N=Ta.parse(P);N.name=u.name,Sa(`${y}/${$.name}`,Ta.update(P,N))}else Sa(`${y}/${$.name}`,P)}}break}case"GIT_REPO":{g.gitRepoUrl||p();let{gitRepoUrl:S}=g,[$,C]=S.split("#"),P,N;C&&([P,N]=C.split(":"));let k=$;N&&(k+=`/${N}`),P&&(k+=`#${P}`);let M=Mm(k);try{await M.clone(y)}catch(q){throw new Error(`Failed to pull Actor from ${S}. ${q.message}`)}break}case"GITHUB_GIST":{g.gitHubGistUrl||p(),await Ca(`${g.gitHubGistUrl}/archive/master.zip`,y);break}default:throw new Error(`Unknown source type: ${v}`)}E({message:n?`Actor ${l} updated at ${y}/`:`Pulled to ${y}/`})}};import{readFileSync as Bm,statSync as Vm,unlinkSync as Gm}from"fs";import{join as Ym,resolve as Hm}from"path";import ct from"process";import qm from"open";import{fetchManifest as Jm}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as lt,ACTOR_SOURCE_TYPES as yi,MAX_MULTIFILE_BYTES as ka}from"@apify/consts";import{createHmacSignature as Km}from"@apify/utilities";import{readFileSync as Um,writeFileSync as jm}from"fs";var hi="@",Ia=100,$a=5e4,Nt=m(()=>{try{return JSON.parse(Um(Sr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Ea=m(r=>(Xs(Sr()),jm(Sr(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),Ra=m((r,e)=>{let t=Nt();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>Ia)throw new Error(`Secret name has to be string with maximum length ${Ia}.`);if(typeof e!="string"||e.length>$a)throw new Error(`Secret value has to be string with maximum length ${$a}.`);return t[r]=e,Ea(t)},"addSecret"),_a=m(r=>{let e=Nt();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Ea(e)},"removeSecret"),xa=m(r=>new RegExp(`^${hi}.{1}`).test(r),"isSecretKey"),Pa=m((r,e,{allowMissing:t=!1}={})=>{e=e||Nt();let o={},s=[];if(Object.keys(r).forEach(i=>{if(xa(r[i])){let n=r[i].replace(new RegExp(`^${hi}`),"");e[n]?o[i]=e[n]:s.push(n)}else o[i]=r[i]}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
|
|
132
|
+
`);if(t)for(let n of s)_({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
|
|
133
|
+
${i}
|
|
134
134
|
|
|
135
135
|
Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
|
|
136
|
-
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"replaceSecretsValue"),
|
|
137
|
-
`);if(t)for(let
|
|
138
|
-
${
|
|
136
|
+
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"replaceSecretsValue"),Oa=m((r,e,{allowMissing:t=!1}={})=>{e=e||Nt();let o=[],s=[];if(Object.keys(r).forEach(i=>{if(xa(r[i])){let n=r[i].replace(new RegExp(`^${hi}`),"");e[n]?o.push({name:i,value:e[n],isSecret:!0}):s.push(n)}else o.push({name:i,value:r[i]})}),s.length>0){let i=s.map(n=>` - ${n}`).join(`
|
|
137
|
+
`);if(t)for(let n of s)_({message:`Value for ${n} not found in local secrets. Set it by calling "apify secrets add ${n} [SECRET_VALUE]"`});else throw new Error(`The following secrets are missing:
|
|
138
|
+
${i}
|
|
139
139
|
|
|
140
140
|
Set them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
|
|
141
|
-
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"transformEnvToEnvVars");var
|
|
142
|
-
Files under '${
|
|
141
|
+
If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return o},"transformEnvToEnvVars");var wi="temp_file.zip",Wm={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Na="0.0",zm="latest",Ft=class extends h{static name="push";static description=`Deploys Actor to Apify platform using settings from '${D}'.
|
|
142
|
+
Files under '${ka/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
|
|
143
143
|
Files matched by .gitignore and .actorignore are excluded. Use negation patterns (e.g. !dist/) in .actorignore to force-include git-ignored files.
|
|
144
|
-
Use --force to override newer remote versions.`;static enableJsonFlag=!0;static flags={version:w.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${D}' file.`,required:!1}),"build-tag":w.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${D}' file`,required:!1}),"wait-for-finish":w.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:w.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:w.boolean({char:"f",description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:w.string({description:"Directory where the Actor is located",required:!1}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};static args={actorId:A.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 '${D}' file.`})};async run(){let e=
|
|
145
|
-
`)}),ct.exitCode=4;return}let o=await I(),s=await
|
|
146
|
-
Skipping push. Use --force to override.`)}
|
|
147
|
-
${
|
|
148
|
-
|
|
149
|
-
|
|
144
|
+
Use --force to override newer remote versions.`;static enableJsonFlag=!0;static flags={version:w.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${D}' file.`,required:!1}),"build-tag":w.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${D}' file`,required:!1}),"wait-for-finish":w.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),open:w.boolean({description:"Whether to open the browser automatically to the Actor details page.",default:!1,required:!1}),force:w.boolean({char:"f",description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:w.string({description:"Directory where the Actor is located",required:!1}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};static args={actorId:A.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 '${D}' file.`})};async run(){let e=Hm(ct.cwd(),this.flags.dir??"."),t=await en(e);if(!t.length){f({message:"You need to call this command from a folder that has an Actor in it!"}),ct.exitCode=4;return}if(![Cr,"actor.json",".actor/actor.json",".actor"].some(L=>t.some(re=>re===L||re.startsWith(L)))){f({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(`
|
|
145
|
+
`)}),ct.exitCode=4;return}let o=await I(),s=await Ne({cwd:e});if(s.isErr()){f({message:s.unwrapErr().message}),ct.exitCode=5;return}let{config:i}=s.unwrap(),n=await U(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",u,l,d=!1,p=this.flags.version||i?.version||Na,g=this.flags.buildTag||i?.buildTag;!g&&p===Na&&(g=zm);let y=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,v=this.args.actorId;if(v){if(l=await o.actor(v).get(),!l)throw new Error(`Cannot find Actor with ID '${v}' in your account.`);u=l.id}else{let L=n.username||n.id;if(l=await o.actor(`${L}/${i.name}`).get(),l)u=l.id;else{let{templates:re}=await Jm(),Se=re.find(Ar=>Ar.name===i.template)?.defaultRunOptions||Wm,mt={name:i.name,title:i.title,description:i.description,defaultRunOptions:Se,versions:[{versionNumber:p,buildTag:g,sourceType:yi.SOURCE_FILES,sourceFiles:[]}]};i.usesStandbyMode&&(mt.actorStandby={isEnabled:!0}),l=await o.actors().create(mt),u=l.id,d=!0,b({message:`Created Actor with name ${i.name} on Apify.`})}}let S=o.actor(u);b({message:`Deploying Actor '${i.name}' to Apify.`});let $=await Yi(t,e),C,P,N;if($<ka){let L=await S.get();if(!d){let re=t.reduce((Se,mt)=>{let{mtimeMs:Ar,ctimeMs:Fi}=Vm(Ym(e,mt)),Di=Ar>Fi?Ar:Fi;return Se>Di?Se:Di},0),be=L?.modifiedAt.valueOf();if(!this.flags.force&&be&&re<be&&(i?.name||v))throw new Error(`Actor with identifier "${i?.name||v}" is already on the platform and was modified there since modified locally.
|
|
146
|
+
Skipping push. Use --force to override.`)}P=await Qi(t,e),C=yi.SOURCE_FILES}else{ve({message:"Zipping Actor files"}),await tn(wi,t,e);let L=await o.keyValueStores().getOrCreate(`actor-${u}-source`),re=`version-${p}.zip`,be=Bm(wi);await o.keyValueStore(L.id).setRecord({key:re,value:be,contentType:"application/zip"}),Gm(wi);let Se=new URL(`${o.baseUrl}/key-value-stores/${L.id}/records/${re}?disableRedirect=true`);if(L?.urlSigningSecretKey){let mt=Km(L.urlSigningSecretKey,re);Se.searchParams.set("signature",mt)}N=Se.toString(),C=yi.TARBALL}let k=await S.version(p).get(),M=i.environmentVariables?Oa(i.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(k){let L={tarballUrl:N,sourceFiles:P,buildTag:g,sourceType:C,envVars:M};await S.version(p).update(L),ve({message:`Updated version ${p} for Actor ${l.name}.`})}else{let L={versionNumber:p,tarballUrl:N,sourceFiles:P,buildTag:g,sourceType:C,envVars:M};await S.versions().create({...L}),ve({message:`Created version ${p} for Actor ${l.name}.`})}if(!d&&!!i.usesStandbyMode!=!!l.actorStandby?.isEnabled){let L=!!i.usesStandbyMode;await S.update({actorStandby:{isEnabled:L}}),b({message:`${L?"Enabled":"Disabled"} standby mode for Actor ${l.name}.`})}ve({message:`Building Actor ${l.name}`});let q=await S.build(p,{useCache:!0,waitForFinish:2});try{await Pe({job:q,timeoutMillis:y,apifyClient:o})}catch(L){_({message:"Can not get log:"}),console.error(L)}if(q=await o.build(q.id).get(),this.flags.json){F(q);return}Us({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${q.actId}#/builds/${q.buildNumber}`}),Us({message:"Actor detail",url:`https://console.apify.com${c}/actors/${q.actId}`}),this.flags.open&&await qm(`https://console.apify.com${c}/actors/${q.actId}`),q.status===lt.SUCCEEDED?E({message:"Actor was deployed to Apify cloud and built there."}):q.status===lt.READY?_({message:"Build is waiting for allocation."}):q.status===lt.RUNNING?_({message:"Build is still running."}):q.status===lt.ABORTED||q.status===lt.ABORTING?(_({message:"Build was aborted!"}),ct.exitCode=3):q.status===lt.TIMED_OUT||q.status===lt.TIMING_OUT?(_({message:"Build timed out!"}),ct.exitCode=2):(f({message:"Build failed!"}),ct.exitCode=1)}};var bo=class extends h{static name="rm";static description="Permanently removes an Actor from your account.";static args={actorId:A.string({description:"The Actor ID to delete.",required:!0})};async run(){let{actorId:e}=this.args,t=await I();if(!await t.actor(e).get()){f({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await X({message:"Are you sure you want to delete this Actor?"})){b({message:`Deletion of Actor "${e}" was canceled.`});return}try{await t.actor(e).delete(),E({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;f({message:`Failed to delete Actor "${e}".
|
|
147
|
+
${n.message||n}`})}}};import{ApifyClient as Xm}from"apify-client";import Ai from"chalk";var Zm={FREE:"Free",FLAT_PRICE_PER_MONTH:"Subscription",PRICE_PER_DATASET_ITEM:"Pay per result",PAY_PER_EVENT:"Pay per event"};function Qm(r){return r?Zm[r]??r:Ai.gray("Unknown")}m(Qm,"formatPricingModel");function ed(r,e=60){return r?r.length<=e?r:`${r.slice(0,e-1)}\u2026`:""}m(ed,"truncateDescription");var So=class extends h{static name="search";static description=`Searches Actors in the Apify Store.
|
|
148
|
+
|
|
149
|
+
Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static args={query:A.string({description:"Search query to find Actors by title, name, description, username, or readme.",required:!1})};static flags={"sort-by":w.string({description:"Sort order for the results.",options:["relevance","popularity","newest","lastUpdate"],default:"relevance"}),category:w.string({description:"Filter by category (e.g. AI)."}),username:w.string({description:"Filter by Actor author username."}),"pricing-model":w.string({description:"Filter by pricing model.",options:["FREE","FLAT_PRICE_PER_MONTH","PRICE_PER_DATASET_ITEM","PAY_PER_EVENT"]}),limit:w.integer({description:"Maximum number of results to return.",default:20}),offset:w.integer({description:"Number of results to skip for pagination.",default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:t,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c}=this.flags,u=qt();delete u.token;let l=new Xm(u),d;try{d=await l.store().list({search:e,sortBy:o,category:s,username:i,pricingModel:n,limit:a,offset:c})}catch(g){process.exitCode=1,f({message:`Failed to search Apify Store: ${g instanceof Error?g.message:String(g)}`,stdout:!0});return}if(d.count===0){if(t){F(d);return}b({message:"No Actors found matching your search.",stdout:!0});return}if(t){F(d);return}let p=new B({allColumns:["Name","Description","Users (30d)","Pricing"],mandatoryColumns:["Name","Pricing"],columnAlignments:{"Users (30d)":"right",Name:"left"}});for(let g of d.items)p.pushRow({Name:`${g.title}
|
|
150
|
+
${Ai.gray(`${g.username}/${g.name}`)}`,Description:ed(g.description),"Users (30d)":Ai.cyan(`${g.stats?.totalUsers30Days??0}`),Pricing:Qm(g.currentPricingInfo?.pricingModel)});R({message:p.render(1),stdout:!0})}};import se from"chalk";var vo=class extends h{static name="start";static description=`Starts Actor remotely and returns run details immediately.
|
|
151
|
+
Uses authenticated account and local key-value store for input.`;static flags={...Ot("Actor"),input:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.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:A.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 '${D}' file.`})};async run(){let e=process.cwd(),t=Me(e)||{},o=await I(),s=await U(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await Je.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),u={};this.flags.build&&(u.build=this.flags.build),this.flags.timeout&&(u.timeout=this.flags.timeout),this.flags.memory&&(u.memory=this.flags.memory);let l=await xt(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let d=Pt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:u,type:"Actor",inputOverride:l?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let N of d)p=N;if(this.flags.json){F(p);return}let g=`https://console.apify.com/actors/${n}/runs/${p.id}`,y=`https://console.apify.com/storage/datasets/${p.defaultDatasetId}`,v=[`${se.gray("Run:")} Calling Actor ${a} (${se.gray(n)})`,"",`${se.yellow("Started")}: ${Y.display(p.startedAt)}`];p.containerUrl&&v.push(`${se.yellow("Container URL")}: ${se.blue(p.containerUrl)}`);let S=p.buildNumber.split(".").slice(0,2).join("."),$=c.versions.find(N=>N.versionNumber===S),C=Object.entries(c.taggedBuilds??{}).find(([,N])=>N.buildNumber===p.buildNumber)?.[0],P=[`${se.yellow("Build")}:`,se.cyan(p.buildNumber)];C?P.push(`(${se.yellow(C)})`):P.push(`(${se.gray("N/A")})`),$&&P.push(`| ${se.gray("Actor version:")} ${se.cyan($.versionNumber)} (${se.yellow($.buildTag)})`),v.push(P.join(" ")),v.push(`${se.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),v.push(`${se.yellow("Memory")}: ${p.options.memoryMbytes} MB`),v.push("",`${se.blue("Export results")}: ${y}`,`${se.blue("View on Apify Console")}: ${g}`),R({message:v.join(`
|
|
152
|
+
`),stdout:!0})}};var To=class extends h{static name="actors";static description="Manages Actor creation, deployment, and execution on the Apify platform.";static subcommands=[vo,bo,So,Ft,kt,Ao,wo,Je,po];async run(){this.printHelp()}};import od from"chalk";import sd from"computer-name";import id from"cors";import bi from"express";import nd from"open";import{cryptoRandomObjectId as ad}from"@apify/utilities";import td from"@inquirer/password";var Fa=Oe(async({message:r,mask:e})=>await td({message:r,mask:e??"*"}));import rd from"@inquirer/select";var Ke=Oe(async({message:r,choices:e,pageSize:t,loop:o,default:s})=>await rd({message:r,choices:e,pageSize:t,loop:o,default:s}));var vi="https://console.apify.com/settings/integrations",cd=new URL(vi).origin,ld=vi.includes("localhost")?"http://localhost:3333":void 0,Da="v1",Si=m(async r=>{let e=await Jt(r,ld),t=await U();return e?(await Mr(t.id),E({message:`You are logged in to Apify as ${t.username||t.id}. ${od.gray(`Your token is stored at ${pe()}.`)}`})):f({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Dt=class extends h{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ae(pe())}'.
|
|
150
153
|
All other commands use these stored credentials.
|
|
151
154
|
|
|
152
|
-
Run 'apify logout' to remove authentication.`;static flags={token:w.string({char:"t",description:"Apify API token",required:!1}),method:w.string({char:"m",description:"Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await
|
|
153
|
-
Run 'apify login' to authenticate again.`;async run(){await Ut(pe()),await
|
|
154
|
-
${u.message||u}`,stdout:!0})}}};import te from"chalk";var
|
|
155
|
-
`),stdout:!0})}};var
|
|
156
|
-
`});try{await
|
|
157
|
-
`,stdout:!0});let g=Object.entries(d).sort((y,v)=>y[0].localeCompare(v[0]));for(let[y,v]of g){if(!v?.length){R({message:`No builds for version ${y}`,stdout:!0});continue}let S=l.versions.find(N=>N.versionNumber===y)?.buildTag,$=this.generateTableForActorVersion({buildsForVersion:v,buildTagToActorVersion:p}),C=S?` (latest build gets tagged with ${we.yellow(S)})`:"",
|
|
158
|
-
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=
|
|
159
|
-
${d.message||d}`,stdout:!0})}}};import
|
|
160
|
-
${c.message||c}`,stdout:!0})}}};var
|
|
155
|
+
Run 'apify logout' to remove authentication.`;static flags={token:w.string({char:"t",description:"Apify API token",required:!1}),method:w.string({char:"m",description:"Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await Si(e);return}let o=t;if(t||(o=await Ke({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=bi();i.use(id({origin:cd,allowedHeaders:["Content-Type","Authorization"]})),i.use((l,d,p)=>{d.set("Connection","close"),p()}),i.use(bi.json());let n=ad();i.use((l,d,p)=>{let{token:g}=l.query;if(!g){let y=l.get("Authorization");if(y){let[v,S,...$]=y.trim().split(/\s+/);v.toLowerCase()==="bearer"&&S&&$.length===0&&(g=S)}}g!==n?(d.status(401),d.send("Authorization failed")):p()});let a=bi.Router();i.use(`/api/${Da}`,a),a.post("/login-token",async(l,d)=>{try{if(l.body.apiToken)await Si(l.body.apiToken);else throw new Error("Request did not contain API token");d.end()}catch(p){let g=`Login to Apify failed with error: ${p.message}`;f({message:g}),d.status(500),d.send(g)}s.close()}),a.post("/exit",(l,d)=>{l.body.isWindowClosed?f({message:"Login to Apify failed, the console window was closed."}):l.body.actionCanceled?f({message:"Login to Apify failed, the action was canceled in the Apify Console."}):f({message:"Login to Apify failed."}),d.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),u=new URL(vi);u.searchParams.set("localCliCommand","login"),u.searchParams.set("localCliPort",`${c}`),u.searchParams.set("localCliToken",n),u.searchParams.set("localCliApiVersion",Da);try{u.searchParams.set("localCliComputerName",encodeURIComponent(sd()))}catch{}b({message:`Opening Apify Console at "${u.href}"...`}),await nd(u.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await Fa({message:"token:"});await Si(s)}}};var Lt=class extends h{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ae(pe())}'.
|
|
156
|
+
Run 'apify login' to authenticate again.`;async run(){await Ut(pe()),await Mr(null),E({message:"You are logged out from your Apify account."})}};var Co=class extends h{static name="token";static description="Prints the current API token for the Apify CLI.";async run(){await I();let e=await U();e.token&&R({message:e.token,stdout:!0})}};var Io=class extends h{static name="auth";static description="Manages authentication for Apify CLI.";static subcommands=[Dt,Lt,Co];async run(){this.printHelp()}};import $o from"chalk";var Eo=class extends h{static name="add-tag";static description="Adds a tag to a specific Actor build.";static flags={build:w.string({char:"b",description:"The build ID to tag.",required:!0}),tag:w.string({char:"t",description:"The tag to add to the build.",required:!0})};async run(){let{build:e,tag:t}=this.flags,o=await I(),s=await o.build(e).get();if(!s){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(s.status!=="SUCCEEDED"){f({message:`Build with ID "${e}" has status "${s.status}". Only successful builds can be tagged.`,stdout:!0});return}let i=await o.actor(s.actId).get();if(!i){f({message:`Actor with ID "${s.actId}" was not found.`,stdout:!0});return}let a=(i.taggedBuilds??{})[t];if(a?.buildId===e){_({message:`Build "${e}" is already tagged as "${t}".`,stdout:!0});return}try{await o.actor(s.actId).update({taggedBuilds:{[t]:{buildId:s.id}}});let c=a?.buildNumber?` (previously pointed to build ${$o.gray(a.buildNumber)})`:"";E({message:`Tag "${$o.yellow(t)}" added to build ${$o.gray(s.buildNumber)} (${$o.gray(e)})${c}`,stdout:!0})}catch(c){let u=c;f({message:`Failed to add tag "${t}" to build "${e}".
|
|
157
|
+
${u.message||u}`,stdout:!0})}}};import te from"chalk";var ud=m(r=>r,"noColor");function ee({bytes:r,shortBytes:e=!1,colorFunc:t=ud,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])}`}m(ee,"prettyPrintBytes");var Ro=class extends h{static name="info";static description="Prints information about a specific build.";static args={buildId:A.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){F(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[g,y]of Object.entries(s.taggedBuilds))if(y.buildId===o.id){i=g;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",c=i?` (tagged as ${te.yellow(i)})`:"",u=typeof n<"u"?` (exit code: ${te.gray(n)})`:"",l=[`${te.yellow("Actor")}: ${a} (${te.gray(o.actId)})`,"",`${te.yellow("Build Information")} (ID: ${te.gray(o.id)})`,` ${te.yellow("Build Number")}: ${o.buildNumber}${c}`,` ${te.yellow("Status")}: ${xe(o.status)}${u}`,` ${te.yellow("Started")}: ${Y.display(o.startedAt)}`];if(o.finishedAt)l.push(` ${te.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${te.gray(Xt.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();l.push(` ${te.yellow("Finished")}: ${te.gray(`Running for ${Xt.format(g)}`)}`)}o.stats?.computeUnits&&l.push(` ${te.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let d=Reflect.get(o.stats??{},"imageSizeBytes");d&&l.push(` ${te.yellow("Docker Image Size")}: ${ee({bytes:d})}`),l.push(` ${te.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),l.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;l.push(`${te.blue("View in Apify Console")}: ${p}`),R({message:l.join(`
|
|
158
|
+
`),stdout:!0})}};var _o=class extends h{static name="log";static description="Prints the log of a specific build.";static args={buildId:A.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for build with ID "${e}":
|
|
159
|
+
`});try{await Pe({job:o,apifyClient:t})}catch(s){f({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import we from"chalk";var md=m(()=>new B({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),xo=class extends h{static name="ls";static description="Lists all builds of the Actor.";static flags={offset:w.integer({description:"Number of builds that will be skipped.",default:0}),limit:w.integer({description:"Number of builds that will be listed.",default:10}),desc:w.boolean({description:"Sort builds in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.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 I(),c=await He({providedActorNameOrId:n,client:a});if(!c.valid){f({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let u=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),l=await a.actor(c.id).get(),d=Dr(u.items,y=>{let v=Reflect.get(y,"buildNumber"),[S,$]=v.split(".");return`${S}.${$}`}),p=Object.entries(l.taggedBuilds??{}).reduce((y,[v,S])=>(y[S.buildNumber]=v,y),{});if(i){for(let y of u.items){let v=Reflect.get(y,"buildNumber"),S=p[v];S&&Reflect.set(y,"buildTag",S)}F(u);return}R({message:`${we.reset("Showing")} ${we.yellow(u.items.length)} out of ${we.yellow(u.total)} builds for Actor ${we.yellow(c.userFriendlyId)} (${we.gray(c.id)})
|
|
160
|
+
`,stdout:!0});let g=Object.entries(d).sort((y,v)=>y[0].localeCompare(v[0]));for(let[y,v]of g){if(!v?.length){R({message:`No builds for version ${y}`,stdout:!0});continue}let S=l.versions.find(N=>N.versionNumber===y)?.buildTag,$=this.generateTableForActorVersion({buildsForVersion:v,buildTagToActorVersion:p}),C=S?` (latest build gets tagged with ${we.yellow(S)})`:"",P=[we.reset(`Builds for Actor Version ${we.yellow(y)}${C}`),$.render(s?0:-1),""];R({message:P.join(`
|
|
161
|
+
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=md();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${we.yellow(t[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=we.gray(`${ue.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=we.gray(`Running for ${ue.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:we.gray(s.id),Status:xe(s.status),Took:a})}return o}};import mr from"chalk";var Po=class extends h{static name="remove-tag";static description="Removes a tag from a specific Actor build.";static flags={build:w.string({char:"b",description:"The build ID to remove the tag from.",required:!0}),tag:w.string({char:"t",description:"The tag to remove from the build.",required:!0}),yes:w.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts.',default:!1})};async run(){let{build:e,tag:t,yes:o}=this.flags,s=await I(),i=await s.build(e).get();if(!i){f({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let n=await s.actor(i.actId).get();if(!n){f({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let c=(n.taggedBuilds??{})[t];if(!c){f({message:`Tag "${t}" does not exist on Actor "${n.name}".`,stdout:!0});return}if(c.buildId!==e){f({message:`Tag "${t}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});return}if(!await X({message:`Are you sure you want to remove tag "${mr.yellow(t)}" from build ${mr.gray(i.buildNumber)}?`,providedConfirmFromStdin:o||void 0})){b({message:"Tag removal was canceled.",stdout:!0});return}try{await s.actor(i.actId).update({taggedBuilds:{[t]:null}}),E({message:`Tag "${mr.yellow(t)}" removed from build ${mr.gray(i.buildNumber)} (${mr.gray(e)})`,stdout:!0})}catch(l){let d=l;f({message:`Failed to remove tag "${t}" from build "${e}".
|
|
162
|
+
${d.message||d}`,stdout:!0})}}};import dd from"@inquirer/input";var La=Oe(async({message:r,expectedValue:e,failureMessage:t})=>await dd({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Oo=class extends h{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static args={buildId:A.string({description:"The build ID to delete.",required:!0})};async run(){let{buildId:e}=this.args,t=await I(),o=await t.build(e).get();if(!o){f({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,c]of Object.entries(s.taggedBuilds))if(e===c.buildId){i=a;break}}if(!await(i?La:X)({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(),E({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete build "${e}".
|
|
163
|
+
${c.message||c}`,stdout:!0})}}};var ko=class extends h{static name="builds";static description="Manages Actor build processes and versioning.";static subcommands=[Eo,Po,Oo,xo,_o,Ro,_t];async run(){this.printHelp()}};var No=class extends Je{static name="call"};import pd from"assert";import{existsSync as Ma,openSync as fd}from"fs";import{mkdir as Ua,readFile as gd,symlink as hd,unlink as yd,writeFile as ja}from"fs/promises";import{homedir as wd}from"os";import{dirname as Ad,join as We}from"path";import{ReadStream as bd}from"tty";import H from"chalk";import Ba from"which";var Sd=m(r=>We(r,".install-marker"),"pathToInstallMarker"),Va=m(()=>process.env.HOME??wd(),"HOMEDIR"),dr=class extends h{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}=W();if(e!=="bundle"){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}pd(t,"When CLI is installed via bundles, the install path must be set");let s=Sd(t);if(Ma(s)){b({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}if(process.platform!=="win32"){await this.symlinkToLocalBin(t);try{await this.promptAddToShell()}catch(i){f({message:i.message||"Failed to automatically handle shell integration"})}R({message:""})}await ja(s,o),T("[install] install marker written to",s),R({message:["",H.green("Apify and Actor CLI were installed successfully!"),"",H.gray(` Version: ${H.green(o)}`),H.gray(` Location: ${H.bold.white(ae(We(t,"apify")))} and ${H.bold.white(ae(We(t,"actor")))}`)].join(`
|
|
161
164
|
`)}),R({message:""}),E({message:"To get started, run:"}),R({message:H.white.bold(` apify --help
|
|
162
|
-
actor --help`)})}async symlinkToLocalBin(e){let t=
|
|
163
|
-
`)},"writeDone");try{return T("[install] opening /dev/tty for raw mode"),t=
|
|
164
|
-
`?(o.removeListener("data",c),
|
|
165
|
-
`),a(!1))},"onData");o.on("data",c)})}catch(
|
|
165
|
+
actor --help`)})}async symlinkToLocalBin(e){let t=Va();if(T("[install -> symlinkToLocalBin] user home directory",t),!t){T("[install -> symlinkToLocalBin] user home directory not found"),_({message:H.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=We(t,".local","bin");await Ua(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=We(e,i);if(!Ma(n)){T("[install] file not found for symlinking",i,n),_({message:H.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=We(o,i);await yd(a).catch(()=>{}),await hd(n,a),T("[install] symlink created for item",i,a)}b({message:H.gray(`Symlinked apify, actor, and apify-cli to ${ae(o)}`)})}async confirmFromTty(e){let t,o,s=`${H.green("?")} ${H.bold(e)} ${H.dim("(Y/n)")} `,i=m(n=>{process.stdout.write(`\r\x1B[2K${H.green("?")} ${H.bold(e)} ${H.cyan(n)}
|
|
166
|
+
`)},"writeDone");try{return T("[install] opening /dev/tty for raw mode"),t=fd("/dev/tty","r"),o=new bd(t),process.stdout.write(s),o.setRawMode(!0),o.resume(),await new Promise(a=>{let c=m(u=>{let l=u.toString();l==="y"||l==="Y"||l==="\r"||l===`
|
|
167
|
+
`?(o.removeListener("data",c),i("Yes"),a(!0)):l==="n"||l==="N"?(o.removeListener("data",c),i("No"),a(!1)):(l===""||l==="")&&(o.removeListener("data",c),process.stdout.write(`
|
|
168
|
+
`),a(!1))},"onData");o.on("data",c)})}catch(n){return T("[install] failed to open /dev/tty for raw mode",n),!1}finally{o&&(o.setRawMode(!1),o.pause(),o.destroy())}}async promptAddToShell(){let[e,t]=await Promise.allSettled([Ba("apify",{nothrow:!0}),Ba("actor",{nothrow:!0})]);if(e.status==="fulfilled"&&t.status==="fulfilled"&&e.value&&t.value){T("[install -> promptAddToShell] already in PATH",{apifyCliPath:e,actorCliPath:t}),b({message:H.gray("Apify and Actor CLIs are already in PATH, skipping shell integration")});return}let o=Va();T("[install -> promptAddToShell] user home directory",o);let s=process.env.APIFY_CLI_INSTALL??We(o,".apify"),i=process.env.FINAL_BIN_DIR??We(s,"bin"),n=process.env.PROVIDED_INSTALL_DIR??s;if(!n){_({message:H.gray("Install directory not found, cannot add to shell")});return}let a=process.env.FINAL_BIN_DIR??i;R({message:""});let c="Should the CLI handle adding itself to your shell automatically?",u;process.env.APIFY_OPEN_TTY?u=await this.confirmFromTty(c):(T("[install] opening /dev/tty for raw mode not requested, falling back to normal flow"),u=await X({message:c,providedConfirmFromStdin:!1}));let l=ln(),d=un(o,l),p=`"${n.replaceAll('"','\\"')}"`,g=[],y=!0;switch(l){case"bash":case"zsh":{g.push(`export APIFY_CLI_INSTALL=${p}`),g.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');break}case"fish":{g.push(`set --export APIFY_CLI_INSTALL ${p}`),g.push(`set --export PATH ${a} $PATH`);break}default:{g.push(`export APIFY_CLI_INSTALL=${p}`),g.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),u=!1,y=!1;break}}if(R({message:""}),u&&d){let $=`${await gd(d,"utf-8").catch(C=>{if(C.code==="ENOENT")return"";throw new Error(`Failed to read config file "${ae(d)}". Received error code: ${C.code}; ${C.message}`)})}
|
|
166
169
|
|
|
167
170
|
# apify cli
|
|
168
171
|
${g.join(`
|
|
169
172
|
`)}
|
|
170
|
-
`;try{await
|
|
173
|
+
`;try{await Ua(Ad(d),{recursive:!0}),await ja(d,$)}catch(C){throw C.code==="EACCES"?new Error(`Failed to write to config file "${ae(d)}", as the CLI does not have permission to write to it.`):new Error(`Failed to write to config file "${ae(d)}". Received error code: ${C.code}; ${C.message}`)}b({message:[H.gray(`Added "${ae(a)}" to your PATH in ${ae(d)}.`),H.gray(` You may need to run ${H.white.bold(`source ${ae(d)}`)} to reload your shell.`)].join(`
|
|
171
174
|
`)});return}let v=d??"your shell config file";if(y){let S=`echo -e '${g.join("\\n")}' >> "${v}" && source "${v}"`;b({message:[H.gray("The Apify & Actor CLIs are not in your PATH. Run:"),"",H.white.bold(` ${S}`)].join(`
|
|
172
175
|
`)});return}b({message:[H.gray(`Manually add the following lines to ${v} or similar:`),...g.map(S=>H.white.bold(` ${S}`))].join(`
|
|
173
|
-
`)})}};import{spawn as
|
|
174
|
-
`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=
|
|
176
|
+
`)})}};import{spawn as _d}from"child_process";import{existsSync as xd}from"fs";import{lstat as Pd,readdir as Od,writeFile as Ha}from"fs/promises";import{dirname as kd,join as Ti}from"path";import Ci from"chalk";import{gte as qa}from"semver";import{Result as vd}from"@sapphire/result";import{execa as Td}from"execa";var Cd=m(async(r,e,t)=>{let o=Ve(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=Td(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 vd.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function de({cmd:r,args:e=[],opts:t={},overrideCommand:o}){ve({message:`${o||r} ${e.join(" ")}`});let s=await Cd(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(f({message:i.message}),i.cause)throw i.cause}}m(de,"execWithLog");import{execSync as Ga}from"child_process";import{existsSync as Id,readFileSync as $d}from"fs";var je=W();function Ed(){return je.platform==="linux"?Id("/etc/alpine-release"):!1}m(Ed,"isInstalledOnMusl");function Rd(){return je.platform==="darwin"&&je.arch==="x64"?!Ga("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):je.platform==="linux"&&je.arch==="x64"?!$d("/proc/cpuinfo","utf-8").includes("avx2"):je.platform==="windows"?je.arch==="arm64"?!0:Ga(`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}m(Rd,"isInstalledOnBaseline");async function Ya(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":st}});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=Ed(),n=Rd(),a=s.assets.filter(c=>{let[u,l,d,p,g,y]=c.name.replace(e,"version").replace(".exe","").split("-");return d!==je.platform||p!==je.arch?!1:i?g==="musl":n?y==="baseline"||g==="baseline":!g&&!y});return T("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}m(Ya,"useCLIVersionAssets");var Ja={bundle:m((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:m(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:m(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:m(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:m(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:m(r=>["volta","install",`apify-cli@${r}`],"volta")},Fo="1.0.1",Ka="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",pr=class extends h{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:w.boolean({description:"[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.",required:!1,char:"f"}),version:w.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":w.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 Kn(!this.flags.internalAutomaticCall),{installMethod:t}=W();if(!e.shouldUpdate||e.currentVersion===js){T("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||b({message:`${this.cliName} is up to date \u{1F44D}
|
|
177
|
+
`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=Ja[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 ${Ci.bgWhite(Ci.black(o))} to update! \u{1F44D}
|
|
175
178
|
`].join(`
|
|
176
|
-
`);_({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!
|
|
177
|
-
`)});return}let a=
|
|
178
|
-
`)});return}if(
|
|
179
|
-
`)}),process.exit(1));let
|
|
180
|
-
`)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){b({message:`Would write asset ${
|
|
181
|
-
`)})}}}};import{mkdir as
|
|
179
|
+
`);_({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!qa(e,Fo)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Fo}.`});return}let t=await Ya(e);if(!t){f({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!qa(s,Fo)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Fo}.`});return}let i=W();if(i.installMethod==="bundle"){if(!o.length){f({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(`
|
|
180
|
+
`)});return}let a=kd(process.execPath);T("[upgrade] bundleDirectory",a);let c=await Od(a);if(!c.some(u=>u.startsWith("apify")||u.startsWith("actor"))){T("[upgrade] directoryEntries",c),f({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(`
|
|
181
|
+
`)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=Ja[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){b({message:`Would run command: ${n.join(" ")}`});return}try{await de({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{f({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){E({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Ti(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=_d("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=>{f({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=Ti(e,"upgrade.ps1");if(xd(t))return;let o=W(),s=await fetch(Ka,{headers:{"User-Agent":st}});s.ok||(f({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: ${Ka}`,`- The status code of the response: ${s.status}`].join(`
|
|
182
|
+
`)}),process.exit(1));let i=await s.arrayBuffer();await Ha(t,Buffer.from(i)),T("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=W();for(let i of o){let n=i.name.split("-")[0],a=Ti(e,n);b({message:`Downloading \`${n}\` binary of the Apify CLI...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":st}});if(!c.ok){let l=await c.text();T("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:l}),f({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: ${c.status}`,`- The body of the response: ${l}`].join(`
|
|
183
|
+
`)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){b({message:`Would write asset ${n} to ${a}`});continue}b({message:Ci.gray(`Writing ${n} to ${a}...`)});let u=await c.arrayBuffer();try{let l=await Pd(a).then(d=>d.mode).catch(()=>493);await Ha(a,Buffer.from(u),{mode:l|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(l){T("[upgrade] failed to write asset",{error:l}),f({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: ${l.message}`].join(`
|
|
184
|
+
`)})}}}};import{mkdir as jd,readdir as Bd,stat as tc}from"fs/promises";import{join as ut}from"path";import rc from"process";import{gte as Vd,minVersion as Gd}from"semver";import{fetchManifest as Yd,manifestUrl as Hd}from"@apify/actor-templates";import{createWriteStream as Nd}from"fs";import{pipeline as Fd}from"stream/promises";import{Separator as za}from"@inquirer/core";var Wa=["JavaScript","TypeScript","Python"];async function Ii(r){return r?(Wt(r),r):Dd()}m(Ii,"ensureValidActorName");async function Xa(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 ec(t)}m(Xa,"getTemplateDefinition");async function Za(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await _r(t.localReadmeSuffixUrl),s=Nd(r,{flags:"a"});s.write(`
|
|
182
185
|
|
|
183
|
-
`),await
|
|
186
|
+
`),await Fd(o,s)}catch(o){_({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}m(Za,"enhanceReadmeWithLocalSuffix");function Qa(r){let{actorName:e,dependenciesInstalled:t,postCreate:o,gitRepositoryInitialized:s,installCommandSuggestion:i}=r,n=`\u2705 Actor '${e}' created successfully!`;return t?n+=`
|
|
184
187
|
|
|
185
188
|
Next steps:
|
|
186
189
|
|
|
187
190
|
cd "${e}"
|
|
188
|
-
apify run`:
|
|
191
|
+
apify run`:n+=`
|
|
189
192
|
|
|
190
193
|
Next steps:
|
|
191
194
|
|
|
192
195
|
cd "${e}"
|
|
193
|
-
${
|
|
194
|
-
apify run`,
|
|
196
|
+
${i||"install dependencies with your package manager"}
|
|
197
|
+
apify run`,n+=`
|
|
195
198
|
|
|
196
199
|
\u{1F4A1} Tip: Use 'apify push' to deploy your Actor to the Apify platform
|
|
197
|
-
\u{1F4D6} Docs: https://docs.apify.com/platform/actors/development`,s&&(
|
|
198
|
-
\u{1F331} Git repository initialized in '${e}'. You can now commit and push your Actor to Git.`),o&&(
|
|
199
|
-
|
|
200
|
-
${o}`),
|
|
201
|
-
`)}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 U(),
|
|
202
|
-
Operations: ${y.join(" / ")}`;if(
|
|
203
|
-
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${
|
|
204
|
-
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})}`;let S=[`Dataset ID: ${
|
|
205
|
-
`),$=
|
|
206
|
-
`);
|
|
207
|
-
`).map(L=>L.trim());M.shift();let
|
|
200
|
+
\u{1F4D6} Docs: https://docs.apify.com/platform/actors/development`,s&&(n+=`
|
|
201
|
+
\u{1F331} Git repository initialized in '${e}'. You can now commit and push your Actor to Git.`),o&&(n+=`
|
|
202
|
+
|
|
203
|
+
${o}`),n}m(Qa,"formatCreateSuccessMessage");async function ec(r){let e=await Ld();for(;;){let t=await Md(r,e);if(t){if(await Ud())return t}else return ec(r)}}m(ec,"executePrompts");async function Dd(){return await it({message:"Name of your new Actor:",validate:m(e=>{try{Wt(e)}catch(t){return t.message}return!0},"validate")})}m(Dd,"promptActorName");async function Ld(){return await Ke({message:"Choose the programming language of your new Actor:",choices:Wa,loop:!1,default:Wa[0]})}m(Ld,"promptProgrammingLanguage");async function Md(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new za,{name:"Go back",value:!1}];return await Ke({message:"Choose a template for your new Actor. You can check more information at https://apify.com/templates.",default:t[0],choices:t,loop:!1,pageSize:8})}m(Md,"promptTemplateDefinition");async function Ud(){let r=[{name:"Install dependencies",value:!0},new za,{name:"Go back",value:!1}];return await Ke({message:"Almost done! Last step is to install dependencies.",default:r[0],choices:r,loop:!1})}m(Ud,"promptTemplateInstallation");var Do=class extends h{static name="create";static description="Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.";static flags={template:w.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Hd} to find available template names.`,required:!1}),"skip-dependency-install":w.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":w.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":w.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1}),"skip-git-init":w.boolean({description:"Skip initializing a git repository in the Actor directory.",required:!1})};static args={actorName:A.string({required:!1,description:"Name of the Actor and its directory"})};async run(){let{actorName:e}=this.args,{template:t,skipDependencyInstall:o,skipGitInit:s}=this.flags,{templateArchiveUrl:i}=this.flags,n=!1,a=Yd().catch(C=>new Error(`Could not fetch template list from server. Cause: ${C?.message}`));e=await Ii(e);let c=rc.cwd(),u=ut(c,e);for(;;){let C=await tc(u).catch(()=>null),P=C&&await Bd(u).then(N=>N.length>0).catch(()=>!1);if(C?.isDirectory()&&P){f({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 Ii(),u=ut(c,e);continue}C||await jd(u,{recursive:!0});break}let l=null;if(this.telemetryData.fromArchiveUrl=!!i,!i){let C=await Xa(t,a);({archiveUrl:i,messages:l}=C),this.telemetryData.templateId=C.id,this.telemetryData.templateName=C.name,this.telemetryData.templateLanguage=C.category,"skipOptionalDeps"in C&&(n=C.skipOptionalDeps)}this.flags.omitOptionalDeps&&(n=!0),await Fr({url:i,pathTo:u});let d=le(ut(u,D));await xr(Object.assign(d||br,{name:e}),u),await Pr(u),await co(u);let p=ut(u,"package.json"),g=ut(u,"README.md");await Za(g,a);let y=!1;o||await(await ke({cwd:u})).inspectAsync(async P=>{let N=Gd(Te);if(!P.runtime){switch(P.type){case 0:{_({message:`No Node.js detected! Please install Node.js ${N} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{_({message:`No Python detected! Please install Python ${rt} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:k}=P;switch(P.type){case 0:{Nr(k.version)||_({message:`You are running Node.js version ${k.version}, which is no longer supported. Please upgrade to Node.js version ${N} or later.`}),await Gi(p,{name:e});let M=["install"];if(n)switch(k.pmName){case"npm":{Vd(k.pmVersion,"7.0.0")?M.push("--omit=optional"):M.push("--no-optional");break}case"bun":{M.push("--omit=optional");break}case"deno":{M.push("--node-modules-dir");break}default:}await de({cmd:k.pmPath,args:M,opts:{cwd:u},overrideCommand:k.pmName}),y=!0;break}case 1:case 2:{if(!kr(k.version)){_({message:`Python Actors require Python 3.9 or higher, but you have Python ${k.version}!`}),_({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let M=ut(u,".venv");b({message:`Python version ${k.version} detected.`}),b({message:`Creating a virtual environment in "${M}" and installing dependencies from "requirements.txt"...`}),rc.env.VIRTUAL_ENV||(await de({cmd:k.executablePath,args:["-m","venv","--prompt",".",ji],opts:{cwd:u}}),k=(await er({cwd:u,force:!0})).unwrap(),P.runtime=k),await de({cmd:k.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:u}}),await de({cmd:k.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:u}}),y=!0;break}default:}});let v={success:!0},S=await tc(ut(c,".git")).catch(()=>null);if(!s&&!S)try{await de({cmd:"git",args:["init"],opts:{cwd:u}})}catch(C){v={success:!1,error:C}}let $=y?null:await An(u);R({message:""}),E({message:Qa({actorName:e,dependenciesInstalled:y,postCreate:l?.postCreate??null,gitRepositoryInitialized:!s&&!S&&v.success,installCommandSuggestion:$})}),!s&&!S&&!v.success&&(_({message:`Failed to initialize git repository: ${v.error.message}`}),_({message:'You can manually run "git init" in the Actor directory if needed.'}))}};import sc from"chalk";async function oc(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 U(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}m(oc,"tryToGetStorage");async function Le(r,e){return oc(r,e,"dataset")}m(Le,"tryToGetDataset");async function ie(r,e){return oc(r,e,"keyValueStore")}m(ie,"tryToGetKeyValueStore");var Lo=class extends h{static name="create";static description="Creates a new dataset for storing structured data on your account.";static args={datasetName:A.string({description:"Optional name for the Dataset",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await I();if(e&&await Le(t,e)){f({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){F(o);return}E({message:`Dataset with ID ${sc.yellow(o.id)}${e?` (called ${sc.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as ze}from"apify-client";var ic={[ze.JSON]:"application/json",[ze.JSONL]:"application/jsonl",[ze.CSV]:"text/csv",[ze.HTML]:"text/html",[ze.RSS]:"application/rss+xml",[ze.XML]:"application/xml",[ze.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},Mo=class extends h{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static flags={limit:w.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:w.integer({description:"The offset in the dataset where to start getting items."}),format:w.string({description:"The format of the returned output. By default, it is set to 'json'",choices:Object.keys(ic),default:ze.JSON})};static args={datasetId:A.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 I(),n=await this.tryToGetDataset(i,s);if(!n){f({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let c=await a.downloadItems(o,{limit:e,offset:t}),u=ic[o]??"application/octet-stream";R({message:u}),process.stdout.write(c),process.stdout.write(`
|
|
204
|
+
`)}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 U(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import G from"chalk";function Uo(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}m(Uo,"getUserPlanPricing");var nc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),jo=class extends h{static name="info";static description="Prints information about a specific dataset.";static args={storeId:A.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await I(),o=await Le(t,e);if(!o){f({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(L=>L),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){F({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let u=s.stats?.storageBytes||0,l=s.stats?.readCount||0,d=s.stats?.writeCount||0,p=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),y=[`${G.bold(l.toLocaleString("en-US"))} ${G.gray(this.pluralString(l,"read","reads"))}`,`${G.bold(d.toLocaleString("en-US"))} ${G.gray(this.pluralString(d,"write","writes"))}`],v=`Items: ${G.bold(p)} ${G.gray("clean")} / ${G.bold(g)} ${G.gray("total")}
|
|
205
|
+
Operations: ${y.join(" / ")}`;if(i.plan){let L=Uo(i.plan);if(L){let re=L.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e9),be=re*24*30,Se=be>1?`$${be.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
206
|
+
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${G.gray(`${Se} per month`)}`}}else v+=`
|
|
207
|
+
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})}`;let S=[`Dataset ID: ${G.bgGray(s.id)}`,`Name: ${s.name?G.bgGray(s.name):G.bold(G.italic("Unnamed"))}`,`Created: ${G.bold(Y.display(s.createdAt))}`,`Modified: ${G.bold(Y.display(s.modifiedAt))}`].join(`
|
|
208
|
+
`),$=G.bold("\u2014");s.actRunId&&(a?$=G.bgBlue(a.id):$=G.italic(G.gray("Run removed")));let C=G.bold("\u2014");n&&(C=G.blue(n.title||n.name));let P=G.bold("\u2014");c&&(P=G.blue(c.title||c.name));let N=[`Run: ${$}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
209
|
+
`);nc.pushRow({Row1:S,Row2:N});let M=nc.render(2).split(`
|
|
210
|
+
`).map(L=>L.trim());M.shift();let q=[`${G.bold(s.name||G.italic("Unnamed"))}`,`${G.gray(s.name?`${i.username}/${s.name}`:s.id)} ${G.gray("Owned by")} ${G.blue(i.username)}`,"",M.join(`
|
|
208
211
|
`),"",v].join(`
|
|
209
|
-
`);R({message:
|
|
210
|
-
${d.message||d}`})}}};import Xe from"chalk";var
|
|
211
|
-
${l.message||l}`})}}};import
|
|
212
|
-
${c.message||c}`})}}};var
|
|
213
|
-
`}),b({message:`Editing input schema at "${t}"...`});let o,s=
|
|
214
|
-
`,g.length>3&&(a=
|
|
215
|
-
`)
|
|
216
|
-
`);let v=
|
|
217
|
-
`,
|
|
218
|
-
`,()=>{a.write(l),u()})})}),E({message:"The Scrapy project has been wrapped successfully."})}m(
|
|
212
|
+
`);R({message:q,stdout:!0})}};import ac from"chalk";var cc=new B({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),Bo=class extends h{static name="ls";static description="Prints all datasets on your account.";static flags={offset:w.integer({description:"Number of datasets that will be skipped.",default:0}),limit:w.integer({description:"Number of datasets that will be listed.",default:20}),desc:w.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:w.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 I(),a=await U(),c=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){F(c);return}if(c.count===0){b({message:"You don't have any Datasets on your account",stdout:!0});return}for(let u of c.items){let l=Reflect.get(u.stats,"s3StorageBytes");cc.pushRow({"Dataset ID":u.id,Created:Y.display(u.createdAt),Items:`${u.itemCount}`,Modified:Y.display(u.modifiedAt),Name:u.name?`${a.username}/${u.name}`:"",Size:typeof l=="number"?ee({bytes:l,shortBytes:!0,colorFunc:ac.gray,precision:0}):ac.gray("N/A")})}R({message:cc.render(1),stdout:!0})}};import Vo from"chalk";var Go=class extends h{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static args={nameOrId:A.string({required:!0,description:"The dataset ID or name to push the objects to",ignoreStdin:!0}),item:A.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await I(),s=await Le(o,e);if(!s){f({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||Ee;if(!c){f({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(l){f({message:`Failed to parse data as JSON string: ${l.message}`});return}if(Array.isArray(a)&&a.length===0){f({message:"No items were provided."});return}let u=n.name?`Dataset named ${Vo.yellow(n.name)} (${Vo.gray("ID:")} ${Vo.yellow(n.id)})`:`Dataset with ID ${Vo.yellow(n.id)}`;try{await i.pushItems(a),E({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${u} successfully.`})}catch(l){let d=l;f({message:`Failed to push items into ${u}
|
|
213
|
+
${d.message||d}`})}}};import Xe from"chalk";var Yo=class extends h{static name="rename";static description="Change dataset name or removes name with --unname flag.";static flags={unname:w.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:A.string({description:"The dataset ID or name to delete.",required:!0}),newName:A.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){f({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){f({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await Le(s,o);if(!i){f({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,c=a?e?`The name of the dataset with ID ${Xe.yellow(n)} has been removed (was ${Xe.yellow(a)} previously).`:`The name of the dataset with ID ${Xe.yellow(n)} was changed from ${Xe.yellow(a)} to ${Xe.yellow(t)}.`:`The name of the dataset with ID ${Xe.yellow(n)} has been set to: ${Xe.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),E({message:c,stdout:!0})}catch(u){let l=u;f({message:`Failed to rename dataset with ID ${Xe.yellow(n)}
|
|
214
|
+
${l.message||l}`})}}};import $i from"chalk";var Ho=class extends h{static name="rm";static description="Permanently removes a dataset.";static args={datasetNameOrId:A.string({description:"The dataset ID or name to delete",required:!0})};async run(){let{datasetNameOrId:e}=this.args,t=await I(),o=await Le(t,e);if(!o){f({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({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(),E({message:`Dataset with ID ${$i.yellow(i)}${n?` (called ${$i.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete dataset with ID ${$i.yellow(i)}
|
|
215
|
+
${c.message||c}`})}}};var qo=class extends h{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[Lo,Mo,Bo,jo,Ho,Yo,Go];async run(){this.printHelp()}};import{existsSync as Ei,mkdirSync as qd,readFileSync as Jd,writeFileSync as Kd}from"fs";import{dirname as Wd}from"path";import zd from"cors";import Xd from"detect-indent";import Ri from"express";import Zd from"open";import{cryptoRandomObjectId as Qd}from"@apify/utilities";var uc="https://apify.github.io/input-schema-editor-react/",ep=new URL(uc).origin,lc="v1",Jo=class extends h{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:A.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 At({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${D}' is not yet supported.`);_({message:`This command is still experimental and might break at any time. Use at your own risk.
|
|
216
|
+
`}),b({message:`Editing input schema at "${t}"...`});let o,s=Ri();s.use(zd({origin:ep,allowedHeaders:["Content-Type","Authorization"]})),s.use((d,p,g)=>{p.set("Connection","close"),g()}),s.use(Ri.json());let i=Qd();s.use((d,p,g)=>{let{token:y}=d.query;if(!y){let v=d.get("Authorization");if(v){let[S,$,...C]=v.trim().split(/\s+/);S.toLowerCase()==="bearer"&&$&&C.length===0&&(y=$)}}y!==i?(p.status(401),p.send("Authorization failed")):g()});let n=Ri.Router();s.use(`/api/${lc}`,n);let a=" ",c=!0;n.get("/input-schema",(d,p)=>{let g;try{g=Ei(t)?Jd(t,{encoding:"utf-8"}):`{}
|
|
217
|
+
`,g.length>3&&(a=Xd(g).indent||a),g&&(c=g[g.length-1]===`
|
|
218
|
+
`),Ei(t)?b({message:`Input schema loaded from "${t}"`}):b({message:"Empty input schema initialized."})}catch(v){let S=`Reading input schema from disk failed with: ${v.message}`;f({message:S}),p.status(500),p.send(S);return}let y;try{y=JSON.parse(g||"{}")}catch(v){let S=`Parsing input schema failed with error: ${v.message}`;f({message:S}),p.status(500),p.send(S);return}p.send(y),b({message:"Input schema sent to editor."})}),n.post("/input-schema",(d,p)=>{try{b({message:"Got input schema from editor..."});let g=d.body,y=JSON.stringify(g,null,a);c&&(y+=`
|
|
219
|
+
`);let v=Wd(t);Ei(v)||qd(v,{recursive:!0}),Kd(t,y,{encoding:"utf-8",flag:"w+"}),p.end(),b({message:"Input schema saved to disk."})}catch(g){let y=`Saving input schema failed with error: ${g.message}`;f({message:y}),p.status(500),p.send(y)}}),n.post("/exit",(d,p)=>{d.body.isWindowClosed?b({message:"Editor closed, finishing..."}):b({message:"Editing finished, you can close the editor."}),p.end(),o.close(()=>E({message:"Done."}))}),o=s.listen(0);let{port:u}=o.address();b({message:`Listening for messages from input schema editor on port ${u}...`});let l=`${uc}?localCliPort=${u}&localCliToken=${i}&localCliApiVersion=${lc}`;b({message:`Opening input schema editor at "${l}"...`}),await Zd(l)}};import Ko from"chalk";var fr=class extends h{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:A.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=Zr(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=Z.get(t);if(!o){let i=to(t),n=Ko.gray(`Command ${Ko.whiteBright(e)} not found`);i.length&&(n+=`
|
|
220
|
+
`,n+=Ko.gray(`Did you mean: ${i.map(a=>Ko.whiteBright(a)).join(", ")}?`)),f({message:n});return}let s=zr(o);console.log(s)}};import mc from"chalk";var Wo=class extends h{static name="info";static description="Prints details about your currently authenticated Apify account.";async run(){await I();let e=await U();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${mc.gray(o)}: ${mc.bold(t[o])}`)}}};import{basename as gp}from"path";import Oi from"process";import{appendFileSync as tp,copyFileSync as rp,createWriteStream as op,existsSync as _i,mkdirSync as sp,readFileSync as dc,rmSync as ip,writeFileSync as np}from"fs";import{basename as ap,join as xi,relative as pc,sep as Pi}from"path";import{fileURLToPath as cp}from"url";import lp from"@root/walk";import up from"configparser";import mp from"handlebars";import{fetchManifest as dp,wrapperManifestUrl as pp}from"@apify/actor-templates";var fp=[".dockerignore",".gitignore"],zo=cp(new URL("./templates/python-scrapy",import.meta.url));async function fc(r,e,t={bindings:{}}){await lp.walk(r,async(o,s,i)=>{if(s===r)return;let n=pc(r,s),a=n.split(Pi).map(u=>{if(u.startsWith("{")&&u.endsWith("}")){u=u.replace("{","").replace("}","");let l=t.bindings[u];if(!l)throw new Error(`Binding for ${u} not found.`);return l}return u}).join(Pi),c=xi(e,a);if(i.isDirectory())return _i(c)||sp(c),fc(s,c);n.includes(".template")?np(xi(e,a.replace(".template","")),mp.compile(dc(s,"utf8"))(t.bindings)):_i(c)&&fp.includes(ap(a))?tp(c,dc(s)):rp(s,c)})}m(fc,"merge");async function Xo({projectPath:r}){r||(r=".");let e=new nt(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 Ke({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((u,l)=>({name:`${u.class_name} (${u.pathname})`,value:l}))});function o(u){return`.${pc(r,u).split(Pi).slice(1).join(".").replace(".py","")}`}m(o,"translatePathToRelativeModuleName");let s={botName:Or(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 dp(pp);b({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:u})=>u==="python-scrapy");_i(zo)&&ip(zo,{recursive:!0}),await Fr({url:n,pathTo:zo}),b({message:"Wrapping the Scrapy project..."}),await fc(zo,r,{bindings:s});let a=new up;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=op(xi(r,"scrapy.cfg"),{flags:"a"});await new Promise(u=>{c.on("open",l=>{c.write(`
|
|
221
|
+
`,()=>{a.write(l),u()})})}),E({message:"The Scrapy project has been wrapped successfully."})}m(Xo,"wrapScrapyProject");var Zo=class extends h{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
|
|
219
222
|
If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
|
|
220
223
|
Creates the '${D}' file and the '${tt}' directory in the current directory, but does not touch any other existing files or directories.
|
|
221
224
|
|
|
222
|
-
WARNING: Overwrites existing '${tt}' directory.`;static args={actorName:A.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:w.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}),dockerfile:w.string({description:'Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").',required:!1})};async run(){let{actorName:e}=this.args,t=
|
|
225
|
+
WARNING: Overwrites existing '${tt}' directory.`;static args={actorName:A.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:w.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}),dockerfile:w.string({description:'Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").',required:!1})};async run(){let{actorName:e}=this.args,t=Oi.cwd(),o=await ke();o.isErr()&&(f({message:o.unwrapErr().message}),Oi.exit(1));let s=o.unwrap();if(s.warnings?.length)for(let a of s.warnings)_({message:a});let i=gp(t);if(s.type===1&&s.entrypoint?.path){let a=s.entrypoint.path,c=a.includes(".")?a.split(".").pop():a;i=Or(c)}if(s.type===2)return b({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper="scrapy",Xo({projectPath:t});if(!this.flags.yes&&s.type===3&&(_({message:"The current directory does not look like a Node.js or Python project."}),!await X({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let n=await Ne({cwd:t});if(n.isOkAnd(a=>a.exists&&!a.migrated))_({message:`Skipping creation of '${D}', the file already exists in the current directory.`});else{if(n.isErr()){f({message:n.unwrapErr().message}),Oi.exitCode=5;return}if(!e){let u=n.isOkAnd(l=>l.exists)?n.unwrap().config.name:null;for(;!u;)try{let l=await it({message:"Actor name:",default:i});Wt(l),u=l}catch(l){f({message:l.message})}e=u}let c={...{...br,...n.unwrap().config},name:e};this.flags.dockerfile&&(c.dockerfile=this.flags.dockerfile),await xr(c,t)}await Pr(t),await co(t),E({message:"The Actor has been initialized in the current directory."})}};var Qo=class extends h{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
|
|
223
226
|
|
|
224
227
|
It adds the following features:
|
|
225
228
|
- Automatic retry of failed requests
|
|
226
229
|
- Automatic proxy rotation
|
|
227
230
|
- Automatic user agent rotation
|
|
228
231
|
...
|
|
229
|
-
`;static args={path:A.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await
|
|
230
|
-
${u.message||u}`})}}};var
|
|
231
|
-
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${
|
|
232
|
-
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${
|
|
233
|
-
`),$=
|
|
234
|
-
`);
|
|
235
|
-
`).map(L=>L.trim());M.shift();let
|
|
232
|
+
`;static args={path:A.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await Xo({projectPath:this.args.path}),b({message:"Scrapy project wrapped successfully."})}};import gc from"chalk";var es=class extends h{static name="create";static description="Creates a new key-value store on your account.";static args={"key-value store name":A.string({description:"Optional name for the key-value store",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await I();if(e&&await ie(t,e)){f({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){F(o);return}E({message:`Key-value store with ID ${gc.yellow(o.id)}${e?` (called ${gc.yellow(e)})`:""} was created.`,stdout:!0})}};import hp from"chalk";var ts=class extends h{static name="delete-value";static description="Delete a value from a key-value store.";static args={"store id":A.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:A.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 I(),s=await ie(o,e);if(!s){f({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(t)){f({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await X({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 "${hp.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(c){let u=c;f({message:`Failed to delete record with key "${t}" from the key-value store.
|
|
233
|
+
${u.message||u}`})}}};var rs=class extends h{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":w.boolean({description:"Only return the content type of the specified key",default:!1})};static args={keyValueStoreId:A.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:A.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 I(),i=await ie(s,t);if(!i){f({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){f({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:c}=a,u=[];for await(let d of c)u.push(d);let l=Buffer.concat(u).toString();try{let d=JSON.parse(l);R({message:JSON.stringify(d,null,2),stdout:!0})}catch{R({message:l,stdout:!0})}return}a.value.pipe(process.stdout)}};import V from"chalk";var hc=new B({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),os=class extends h{static name="info";static description="Shows information about a key-value store.";static args={storeId:A.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 I(),o=await ie(t,e);if(!o){f({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(L=>L),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){F({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let u=s.stats?.storageBytes||0,l=s.stats?.readCount||0,d=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,g=s.stats?.listCount||0,v=`Operations: ${[`${V.bold(l.toLocaleString("en-US"))} ${V.gray(this.pluralString(l,"read","reads"))}`,`${V.bold(d.toLocaleString("en-US"))} ${V.gray(this.pluralString(d,"write","writes"))}`,`${V.bold(p.toLocaleString("en-US"))} ${V.gray(this.pluralString(p,"delete","deletes"))}`,`${V.bold(g.toLocaleString("en-US"))} ${V.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let L=Uo(i.plan);if(L){let re=L.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e9),be=re*24*30,Se=be>1?`$${be.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
234
|
+
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${V.gray(`${Se} per month`)}`}}else v+=`
|
|
235
|
+
Storage size: ${ee({bytes:u,shortBytes:!0,precision:1})} / ${V.gray("$unknown per month")}`;let S=[`Store ID: ${V.bgGray(s.id)}`,`Name: ${s.name?V.bgGray(s.name):V.bold(V.italic("Unnamed"))}`,`Created: ${V.bold(Y.display(s.createdAt))}`,`Modified: ${V.bold(Y.display(s.modifiedAt))}`].join(`
|
|
236
|
+
`),$=V.bold("\u2014");s.actRunId&&(a?$=V.bgBlue(a.id):$=V.italic(V.gray("Run removed")));let C=V.bold("\u2014");n&&(C=V.blue(n.title||n.name));let P=V.bold("\u2014");c&&(P=V.blue(c.title||c.name));let N=[`Run: ${$}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
237
|
+
`);hc.pushRow({Row1:S,Row2:N});let M=hc.render(2).split(`
|
|
238
|
+
`).map(L=>L.trim());M.shift();let q=[`${V.bold(s.name||V.italic("Unnamed"))}`,`${V.gray(s.name?`${i.username}/${s.name}`:s.id)} ${V.gray("Owned by")} ${V.blue(i.username)}`,"",M.join(`
|
|
236
239
|
`),"",v].join(`
|
|
237
|
-
`);R({message:
|
|
238
|
-
${l.message||l}`})}}};import
|
|
239
|
-
${c.message||c}`})}}};var
|
|
240
|
-
${u.message||u}`})}}};var
|
|
240
|
+
`);R({message:q,stdout:!0})}};var yc=new B({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),ss=class extends h{static name="keys";static description="Lists all keys in a key-value store.";static flags={limit:w.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":w.string({description:"The key to start the list from."})};static args={storeId:A.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 I(),i=await ie(s,e);if(!i){f({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){F(a);return}for(let c of a.items)yc.pushRow({Key:c.key,Size:ee({bytes:c.size,shortBytes:!0,precision:0})});R({message:yc.render(1),stdout:!0})}};import wc from"chalk";var Ac=new B({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),is=class extends h{static name="ls";static description="Lists all key-value stores on your account.";static flags={offset:w.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:w.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:w.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:w.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 I(),a=await U(),c=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){F(c);return}if(c.count===0){b({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let u of c.items){let d=Reflect.get(u,"stats").s3StorageBytes;Ac.pushRow({"Store ID":u.id,Created:Y.display(u.createdAt),Modified:Y.display(u.modifiedAt),Name:u.name?`${a.username}/${u.name}`:"",Size:typeof d=="number"?ee({bytes:d,shortBytes:!0,colorFunc:wc.gray,precision:0}):wc.gray("N/A")})}R({message:Ac.render(1),stdout:!0})}};import Ze from"chalk";var ns=class extends h{static name="rename";static description="Renames a key-value store, or removes its unique name.";static flags={unname:w.boolean({description:"Removes the unique name of the key-value store"})};static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete",required:!0}),newName:A.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){f({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){f({message:"You cannot provide a new name and the --unname flag."});return}let s=await I(),i=await ie(s,o);if(!i){f({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,c=a?e?`The name of the key-value store with ID ${Ze.yellow(n)} has been removed (was ${Ze.yellow(a)} previously).`:`The name of the key-value store with ID ${Ze.yellow(n)} was changed from ${Ze.yellow(a)} to ${Ze.yellow(t)}.`:`The name of the key-value store with ID ${Ze.yellow(n)} has been set to: ${Ze.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),E({message:c,stdout:!0})}catch(u){let l=u;f({message:`Failed to rename key-value store with ID ${Ze.yellow(n)}
|
|
241
|
+
${l.message||l}`})}}};import ki from"chalk";var as=class extends h{static name="rm";static description="Permanently removes a key-value store.";static args={keyValueStoreNameOrId:A.string({description:"The key-value store ID or name to delete",required:!0})};async run(){let{keyValueStoreNameOrId:e}=this.args,t=await I(),o=await ie(t,e);if(!o){f({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:"Are you sure you want to delete this Key-value store?"})){b({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),E({message:`Key-value store with ID ${ki.yellow(i)}${n?` (called ${ki.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete key-value store with ID ${ki.yellow(i)}
|
|
242
|
+
${c.message||c}`})}}};var cs=class extends h{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static flags={"content-type":w.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:A.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:A.string({description:"The key of the item in the key-value store.",required:!0}),value:A.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await I(),n=await ie(i,e);if(!n){f({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}),E({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let u=c;f({message:`Failed to set value with key "${t}" in the key-value store.
|
|
243
|
+
${u.message||u}`})}}};var ls=class extends h{static name="key-value-stores";static description=`Manages persistent key-value storage.
|
|
241
244
|
|
|
242
|
-
Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[
|
|
245
|
+
Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[es,ts,rs,os,ss,is,ns,as,cs];async run(){this.printHelp()}};var us=class extends Dt{static name="login"};var ms=class extends Lt{static name="logout"};var ds=class extends kt{static name="pull"};var ps=class extends Ft{static name="push"};var fs=class extends h{static name="request-queues";static description="Manages URL queues for web scraping and automation tasks.";async run(){this.printHelp()}};import{existsSync as Sc,renameSync as Sp}from"fs";import{mkdir as gs,readFile as vp,stat as vc,writeFile as hr}from"fs/promises";import{dirname as hs,join as ys}from"path";import Be from"process";import Tp from"mime";import{minVersion as Cp}from"semver";import{APIFY_ENV_VARS as ws}from"@apify/consts";import{validateInputSchema as Ip,validateInputUsingValidator as Tc}from"@apify/input_schema";import{none as gr,some as yp}from"@sapphire/result";import{execa as wp}from"execa";var Ni=m(r=>`
|
|
243
246
|
(async () => {
|
|
244
247
|
const [nodeModule, process, path, fs] = await Promise.all([
|
|
245
248
|
import('node:module'),
|
|
@@ -271,31 +274,31 @@ Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[Zo,Qo,es,ts,rs,os,s
|
|
|
271
274
|
}
|
|
272
275
|
})();
|
|
273
276
|
`.replaceAll(`
|
|
274
|
-
`," ").replaceAll(" "," "),"jsScript"),
|
|
277
|
+
`," ").replaceAll(" "," "),"jsScript"),Ap=m(r=>`
|
|
275
278
|
try:
|
|
276
279
|
import ${r}
|
|
277
280
|
print(${r}.__version__)
|
|
278
281
|
except:
|
|
279
282
|
print('n/a')
|
|
280
|
-
`,"pyScript"),
|
|
283
|
+
`,"pyScript"),bp={node(r){return["-e",`"${Ni(r)}"`]},deno(r){return["eval",`"${Ni(r)}"`]},bun(r){return["--eval",`"${Ni(r)}"`]},python(r){return["-c",`"${Ap(r)}"`]}};async function bc({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),gr;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}),gr;let o=bp[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),gr;try{let s=await wp(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}),gr):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),yp(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),gr}}m(bc,"useModuleVersion");var As=class extends h{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
|
|
281
284
|
Stores data in local '${tt}' directory.
|
|
282
285
|
|
|
283
286
|
NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static flags={purge:w.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:w.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:w.string({description:["Optional entrypoint for running with injected environment variables.",`
|
|
284
287
|
`,"For Python, it is the module name, or a path to a file.",`
|
|
285
|
-
`,"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:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.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"]}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};async run(){let e=Be.cwd(),{proxy:t,id:o,token:s}=await U(),
|
|
286
|
-
${M.message}`:""}`}),Be.exitCode=5;return}let{config:
|
|
288
|
+
`,"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:w.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":w.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"]}),"allow-missing-secrets":w.boolean({description:"Allow the command to continue even when secret values are not found in the local secrets storage.",required:!1,default:!1})};async run(){let e=Be.cwd(),{proxy:t,id:o,token:s}=await U(),i=await Ne({cwd:e});if(i.isErr()){let{message:k,cause:M}=i.unwrapErr();f({message:`${k}${M?`
|
|
289
|
+
${M.message}`:""}`}),Be.exitCode=5;return}let{config:n}=i.unwrap(),a=ge(),c=await ke({cwd:e});if(c.isErr()){f({message:c.unwrapErr().message}),Be.exitCode=5;return}let u=c.unwrap(),{type:l,entrypoint:d,runtime:p}=u;if(u.warnings?.length)for(let k of u.warnings)_({message:k});if(l===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(!p){switch(l){case 0:f({message:`No Node.js detected! Please install Node.js ${Te} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:f({message:`No Python detected! Please install Python ${rt} (or higher) to be able to run Python Actors locally.`});break;default:f({message:`No runtime detected! Make sure you have Python ${rt} (or higher) or Node.js ${Te} (or higher) installed.`})}return}let g,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let k=ys(e,this.flags.entrypoint),M=await vc(k).catch(()=>null);M?.isDirectory()?g=1:M?.isFile()?g=0:g=2}else if(d?.script)g=2,y=d.script;else if(d?.path)g=l!==0?1:0,y=d.path;else{f({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}Sc(Bs)&&!Sc(a)&&(Sp(Bs,a),_({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let v=await bc({moduleName:"crawlee",project:u}),S="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(S="1",v.isNone()&&(await Promise.all([rn(),sn(),on()]),b({message:"All default local stores were purged."}))),this.flags.purge||!await nn()&&!this.flags.resurrect&&_({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 $=await xt(e,this.flags.input,this.flags.inputFile);if($===!1)return;let C=await this.validateAndStoreInput($),P={[ws.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:S};if(t&&t.password&&(P[ws.PROXY_PASSWORD]=t.password),o&&(P[ws.USER_ID]=o),s&&(P[ws.TOKEN]=s),n.environmentVariables){let k=Pa(n.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(P,k)}let N=Object.assign(P,Be.env);o||_({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(l){case 0:{let k=Cp(Te);if(Nr(p.version)?N.NODE_OPTIONS=N.NODE_OPTIONS?`${N.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":_({message:`You are running Node.js version ${p.version}, which is no longer supported. Please upgrade to Node.js version ${k} or later.`}),g===0||g===1)await de({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});else{let M=await vp(ys(e,"package.json"),"utf8").catch(()=>"{}"),q=JSON.parse(M);if(!q.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(!q.scripts[y])throw new Error(`The script "${y}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!p.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 de({cmd:p.pmPath,args:["run",y],opts:{env:N,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!kr(p.version)){f({message:`Python Actors require Python 3.9 or higher, but you have Python ${p.version}!`}),f({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await de({cmd:p.executablePath,args:["-m",y],opts:{env:N,cwd:e}}):await de({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});break}default:f({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(k){let{stderr:M}=k}finally{if(C)if(C.existingInput){let k=await vc(C.inputFilePath);if(Math.trunc(k.mtimeMs)-C.writtenAt>=5){_({message:`The "${C.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await hr(C.inputFilePath,C.existingInput.body)}else await jt(C.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await At({cwd:Be.cwd()});if(!t){if(!e)return null;let u=Kt(Be.cwd()),l=ys(Be.cwd(),fe(),u?.fileName??"INPUT.json");return await gs(hs(l),{recursive:!0}),await hr(l,JSON.stringify(e.input,null,2)),{existingInput:u,inputFilePath:l,writtenAt:Date.now()}}let o=new Ht({strict:!1,unicodeRegExp:!1});Ip(o,t);let s=la(t),i=ua(t,o),n=Kt(Be.cwd()),a=ys(Be.cwd(),fe(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
|
|
287
290
|
`;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
|
|
288
291
|
`;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
|
|
289
292
|
`:c=`The input in your storage is invalid. Please fix the following errors:
|
|
290
|
-
`;break}if(e){let u={...s,...e.input},l=
|
|
291
|
-
`)}`);return await
|
|
292
|
-
`)}`);return await
|
|
293
|
-
${
|
|
294
|
-
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(
|
|
295
|
-
`,stdout:!0});try{await
|
|
296
|
-
`),stdout:!0})}};import{ACTOR_JOB_STATUSES as
|
|
297
|
-
${
|
|
298
|
-
${
|
|
293
|
+
`;break}if(e){let u={...s,...e.input},l=Tc(i,t,u);if(l.length>0)throw new Error(`${c}${l.map(d=>` - ${d.message.replace("Field input.","Field ")}`).join(`
|
|
294
|
+
`)}`);return await gs(hs(a),{recursive:!0}),await hr(a,JSON.stringify(u,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await gs(hs(a),{recursive:!0}),await hr(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(Tp.getExtension(n.contentType)==="json"){let u=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(u))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let l={...s,...u},d=Tc(i,t,l);if(d.length>0)throw new Error(`${c}${d.map(p=>` - ${p.message.replace("Field input.","Field ")}`).join(`
|
|
295
|
+
`)}`);return await gs(hs(a),{recursive:!0}),await hr(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as bs}from"@apify/consts";var $p=[bs.READY,bs.RUNNING],Ep=[bs.ABORTING,bs.TIMING_OUT],Ss=class extends h{static name="abort";static description="Aborts an Actor run.";static args={runId:A.string({required:!0,description:"The run ID to abort."})};static flags={force:w.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 I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!$p.includes(o.status)){Ep.includes(o.status)?f({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):f({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){F(s);return}this.flags.force?E({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):E({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;f({message:`Failed to abort run "${e}".
|
|
296
|
+
${i.message||i}`,stdout:!0})}}};import x from"chalk";var yr=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Cc={"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"},vs=class extends h{static name="info";static description="Prints information about an Actor run.";static args={runId:A.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:w.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 I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,c]=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){F({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let u=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",l=[`${x.yellow("Actor")}: ${u} (${x.grey(o.actId)})`];n?l.push(`\u2514\u2500 ${x.yellow("Task")}: ${n.title??n.name} (${x.gray(o.actorTaskId)})`,""):o.actorTaskId?l.push(`\u2514\u2500 ${x.yellow("Task")}: unknown-task (${x.gray(o.actorTaskId)})`,""):l.push("");let d=` (exit code: ${x.gray(o.exitCode!==null?o.exitCode:"N/A")})`;l.push(`${x.yellow("Status")}: ${xe(o.status)}${d}`),o.statusMessage&&l.push(`\u2514\u2500 ${x.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;l.push(`${x.yellow("Results")}: ${x.cyan(p.toLocaleString("en-US"))}`),c?l.push(`${x.yellow("Requests")}: ${x.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${x.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):l.push(`${x.yellow("Requests")}: ${x.gray("unknown handled")}`);let g=this.flags.verbose?"":x.gray(` (run with ${x.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?l.push(`${x.yellow("Usage")}: ${x.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):l.push(`${x.yellow("Usage")}: $${x.gray("0.000")}${g}`),this.flags.verbose&&l.push(yr.render(0)),l.push(""),l.push(`${x.yellow("Started")}: ${Y.display(o.startedAt)}`),o.finishedAt)l.push(`${x.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${x.gray(ue.format(o.stats.durationMillis))})`);else{let $=Date.now()-o.startedAt.getTime();l.push(`${x.yellow("Finished")}: ${x.gray(`Running for ${ue.format($)}`)}`)}if(l.push(""),o.stats.resurrectCount?l.push(`${x.yellow("Resurrected")}: Yes, ${x.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):l.push(`${x.yellow("Resurrected")}: No`),o.containerUrl&&l.push(`${x.yellow("Container URL")}: ${x.blue(o.containerUrl)}`),l.push(`${x.yellow("Origin")}: ${o.meta.origin}`),s){let $=o.buildNumber.split(".").slice(0,2).join("."),C=s.versions.find(k=>k.versionNumber===$),P=Object.entries(s.taggedBuilds??{}).find(([,k])=>k.buildNumber===o.buildNumber)?.[0],N=[`${x.yellow("Build")}:`,x.cyan(o.buildNumber)];P?N.push(`(${x.yellow(P)})`):N.push(`(${x.gray("N/A")})`),C&&N.push(`| ${x.gray("Actor version:")} ${x.cyan(C.versionNumber)} (${x.yellow(C.buildTag)})`),l.push(N.join(" "))}else l.push(`${x.yellow("Build")}: ${x.cyan(o.buildNumber)}`);l.push(`${x.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),l.push(`${x.yellow("Memory")}: ${o.options.memoryMbytes} MB`),l.push(""),l.push(`${x.yellow("CPU")}: ${x.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${x.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),l.push(`${x.yellow("Memory")}: ${x.gray("Average:")} ${ee({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${x.gray("Maximum:")} ${ee({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),l.push("");let y=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,v=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,S=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;l.push(`${x.blue("Export results")}: ${v}`),l.push(`${x.blue("View saved items")}: ${S}`),l.push(`${x.blue("View in Apify Console")}: ${y}`),R({message:l.join(`
|
|
297
|
+
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(Cc))yr.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Cc)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{yr.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":{yr.pushRow({"":s,Unit:ee({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:yr.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var Ts=class extends h{static name="log";static description="Prints the log of a specific run.";static args={runId:A.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}b({message:`Log for run with ID "${e}":
|
|
298
|
+
`,stdout:!0});try{await Pe({job:o,apifyClient:t})}catch(s){f({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import Ae from"chalk";var Ic=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"}}),Cs=class extends h{static name="ls";static description="Lists all runs of the Actor.";static flags={offset:w.integer({description:"Number of runs that will be skipped.",default:0}),limit:w.integer({description:"Number of runs that will be listed.",default:10}),desc:w.boolean({description:"Sort runs in descending order.",default:!1}),compact:w.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:A.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 I(),c=await He({providedActorNameOrId:n,client:a});if(!c.valid){f({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){F(u);return}if(!u.items.length){R({message:"There are no recent runs found for this Actor."});return}let l=[`${Ae.reset("Showing")} ${Ae.yellow(u.items.length)} out of ${Ae.yellow(u.total)} runs for Actor ${Ae.yellow(c.userFriendlyId)} (${Ae.gray(c.id)})`],d=new Map(await Promise.all(u.items.map(async p=>a.dataset(p.defaultDatasetId).get().then(g=>[p.id,Ae.yellow(g?.itemCount??0)],()=>[p.id,Ae.gray("N/A")]))));for(let p of u.items){let g;if(p.finishedAt){let y=p.finishedAt.getTime()-p.startedAt.getTime();g=Ae.gray(`${ue.format(y,void 0,{left:""})}`)}else{let y=Date.now()-p.startedAt.getTime();g=Ae.gray(`Running for ${ue.format(y,void 0,{left:""})}`)}Ic.pushRow({ID:Ae.gray(p.id),Status:xe(p.status),Results:d.get(p.id)||Ae.gray("N/A"),Usage:Ae.cyan(`$${(p.usageTotalUsd??0).toFixed(3)}`),"Started At":zt.display(p.startedAt),Took:g,"Build No.":p.buildNumber,Origin:p.meta.origin??"UNKNOWN"})}l.push(Ic.render(s?0:1)),R({message:l.join(`
|
|
299
|
+
`),stdout:!0})}};import{ACTOR_JOB_STATUSES as Is}from"@apify/consts";var Rp=[Is.SUCCEEDED,Is.FAILED,Is.ABORTED,Is.TIMED_OUT],$s=class extends h{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static args={runId:A.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Rp.includes(o.status)){f({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){F(s);return}E({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;f({message:`Failed to resurrect run "${e}".
|
|
300
|
+
${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Es}from"@apify/consts";var _p=[Es.SUCCEEDED,Es.FAILED,Es.ABORTED,Es.TIMED_OUT],Rs=class extends h{static name="rm";static description="Deletes an Actor Run.";static args={runId:A.string({description:"The run ID to delete.",required:!0})};async run(){let{runId:e}=this.args,t=await I(),o=await t.run(e).get();if(!o){f({message:`Run with ID "${e}" was not found on your account.`});return}if(!_p.includes(o.status)){f({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:"Are you sure you want to delete this Actor Run?"})){b({message:`Deletion of run "${e}" was canceled.`});return}try{await t.run(e).delete(),E({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;f({message:`Failed to delete run "${e}".
|
|
301
|
+
${n.message||n}`})}}};var _s=class extends h{static name="runs";static description="Manages Actor run operations ";static subcommands=[Ss,vs,Ts,Cs,$s,Rs];async run(){this.printHelp()}};var xs=class extends h{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static args={name:A.string({required:!0,description:"Name of the secret"}),value:A.string({required:!0,description:"Value of the secret"})};async run(){let{name:e,value:t}=this.args;Ra(e,t)}};import xp from"chalk";var $c=new B({allColumns:["Secret Name"],mandatoryColumns:["Secret Name"],columnAlignments:{"Secret Name":"left"}}),Ps=class extends h{static name="ls";static description="Lists all secret keys stored in your local configuration.";static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=Nt(),o=Object.keys(t);if(e){F({keys:o});return}if(o.length===0){b({message:"You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.",stdout:!0});return}for(let s of o)$c.pushRow({"Secret Name":xp.cyan(s)});R({message:$c.render(1),stdout:!0})}};var Os=class extends h{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static args={name:A.string({required:!0,description:"Name of the secret"})};async run(){let{name:e}=this.args;_a(e)}};var ks=class extends h{static name="secrets";static description=`Manages secure environment variables for Actors.
|
|
299
302
|
|
|
300
303
|
Example:
|
|
301
304
|
$ apify secrets add mySecret TopSecretValue123
|
|
@@ -309,15 +312,15 @@ The "mySecret" value can be used in an environment variable defined in '${D}' fi
|
|
|
309
312
|
"version": "0.1"
|
|
310
313
|
}
|
|
311
314
|
|
|
312
|
-
When the Actor is pushed to Apify cloud, the "SECRET_ENV_VAR" and its value is stored as a secret environment variable of the Actor.`;static subcommands=[
|
|
315
|
+
When the Actor is pushed to Apify cloud, the "SECRET_ENV_VAR" and its value is stored as a secret environment variable of the Actor.`;static subcommands=[xs,Ps,Os];async run(){this.printHelp()}};import Ec from"chalk";var Ns=class extends h{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
313
316
|
Customize with --memory and --timeout flags.
|
|
314
|
-
`;static flags=
|
|
315
|
-
`),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
|
|
316
|
-
Read more: https://docs.apify.com/cli/docs/telemetry`;static subcommands=[
|
|
317
|
+
`;static flags=Ot("Task");static args={taskId:A.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await I(),t=await U(),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 c,u,l=Pt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let d of l)c=`https://console.apify.com/actors/${d.actId}/runs/${d.id}`,u=`https://console.apify.com/storage/datasets/${d.defaultDatasetId}`;R({message:["",`${Ec.blue("Export results")}: ${u}`,`${Ec.blue("View on Apify Console")}: ${c}`].join(`
|
|
318
|
+
`),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 Fs=class extends h{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[Ns];async run(){this.printHelp()}};var Ds=class extends h{static name="disable";static description="Disables telemetry.";async run(){(await he()).enabled?(await Ur(!1),E({message:"Telemetry disabled."})):b({message:"Telemetry is already disabled."})}};var Ls=class extends h{static name="enable";static description="Enables telemetry.";async run(){(await he()).enabled?b({message:"Telemetry is already enabled."}):(await Ur(!0),E({message:"Telemetry enabled."}))}};var wr=class extends h{static name="telemetry";static description=`Manages telemetry settings. We use this data to improve the CLI and the Apify platform.
|
|
319
|
+
Read more: https://docs.apify.com/cli/docs/telemetry`;static subcommands=[Ls,Ds];async run(){this.printHelp()}};import Pp from"process";var Ms=class extends h{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
|
|
317
320
|
1. Object in '${D}' under "input" key
|
|
318
321
|
2. JSON file path in '${D}' "input" key
|
|
319
322
|
3. .actor/INPUT_SCHEMA.json
|
|
320
323
|
4. INPUT_SCHEMA.json
|
|
321
324
|
|
|
322
|
-
Optionally specify custom schema path to validate.`;static args={path:A.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(){await no({forcePath:this.args.path,cwd:
|
|
323
|
-
//# sourceMappingURL=chunk-
|
|
325
|
+
Optionally specify custom schema path to validate.`;static args={path:A.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(){await no({forcePath:this.args.path,cwd:Pp.cwd(),getMessage:m(e=>e?`Validating input schema at ${e}`:`Validating input schema embedded in '${D}'`,"getMessage")}),E({message:"Input schema is valid."})}};var pk=[mo,To,Io,ko,qo,ls,fs,_s,ks,Fs,wr,No,pr,dr,Do,Jo,Wo,Qo,Zo,us,ms,ds,ps,As,Ms,fr],fk=[Rt,Et,$t,It,Ct,wt,yt,Tt,fr,pr,dr,wr];export{zy as a,Xy as b,pk as c,fk as d};
|
|
326
|
+
//# sourceMappingURL=chunk-SWHV5KL3.js.map
|