apify-cli 1.4.2-beta.3 → 1.4.2-beta.4
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-KJH5D735.js +303 -0
- package/dist/chunk-KJH5D735.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-D7HO3WVQ.js +0 -326
- package/dist/chunk-D7HO3WVQ.js.map +0 -1
package/dist/chunk-D7HO3WVQ.js
DELETED
|
@@ -1,326 +0,0 @@
|
|
|
1
|
-
var kc=Object.defineProperty;var u=(r,e)=>kc(r,"name",{value:e,configurable:!0});import Re from"process";import{parseArgs as ea}from"util";import ro from"chalk";import{satisfies as Lu}from"semver";import ni from"chalk";import hu from"indent-string";import yu from"widest-line";import wu from"wrap-ansi";import Fi from"ci-info";var Nc=[["CLAUDECODE","claude_code"],["CLAUDE_CODE_ENTRYPOINT","claude_code"],["CURSOR_AGENT","cursor"],["CLINE_ACTIVE","cline"],["CODEX_SANDBOX","codex_cli"],["CODEX_THREAD_ID","codex_cli"],["GEMINI_CLI","gemini_cli"],["OPENCODE","open_code"],["OPENCLAW_SHELL","openclaw"]];function Mi(){for(let[r,e]of Nc)if(process.env[r])return e}u(Mi,"detectAiAgent");function Ui(){return Fi.isCI?{isCi:!0,ciProvider:Fi.id?.toLowerCase()??"unknown"}:{isCi:!1,ciProvider:void 0}}u(Ui,"detectCi");function ji(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}u(ji,"detectIsInteractive");import Dc from"chalk";function T(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Dc.gray(`[${r}]`),...e)}u(T,"cliDebugPrint");import{realpathSync as Lc}from"fs";import{dirname as Fc}from"path";import dt from"chalk";function Qe(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}u(Qe,"internalLog");function R(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}u(R,"simpleLog");function f(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.red("Error:"),r.message]})}u(f,"error");function _(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.yellow.bold("Warning:"),r.message]})}u(_,"warning");function $(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.green("Success:"),r.message]})}u($,"success");function ve(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.gray("Run:"),r.message]})}u(ve,"run");function b(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.white("Info:"),r.message]})}u(b,"info");function Us(r){Qe({[r.stdout?"stdoutOutput":"stderrOutput"]:[dt.blue(r.message),r.url]})}u(Us,"link");var js="0.0.0";var Mc="1.4.2-beta.3",Uc="497e2db121ef3d3999fdbfc67d1d2b07ead4fe3a";function jc(){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=Lc(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"}u(jc,"detectInstallMethod");function Bc(){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}}u(Bc,"getRuntimeInfo");var Mt=null;function W(){if(Mt)return Mt;let r=jc(),e=Bc();return Mt={version:Mc,hash:Uc,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=Fc(process.execPath)),Mt}u(W,"useCLIMetadata");import{existsSync as El,mkdirSync as $l,readFileSync as Rl,writeFileSync as _l}from"fs";import{dirname as xl}from"path";import{cryptoRandomObjectId as Pl}from"@apify/utilities";import{homedir as Gc}from"os";import{join as et}from"path";import{KEY_VALUE_STORE_KEYS as Yc,META_ORIGINS as Hc}from"@apify/consts";var Bi={name:"apify-cli",version:"1.4.2-beta.3",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 --exclude ./test/e2e","test:e2e":"vitest run --testNamePattern '\\[e2e\\]' --exclude ./test/api","test:e2e:local":"vitest run --testNamePattern '^(?=.*\\[e2e\\])(?!.*\\[api\\]).*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '^(?=.*\\[api\\])(?!.*\\[e2e\\]).*$' --exclude ./test/e2e","test:python":"vitest run --testNamePattern '\\[python\\]'",lint:"eslint src test scripts --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts --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","ci-info":"~4.4.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","@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,Sr={actorSpecification:Vs,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Vi=1440*60*1e3,pt=u(()=>{let r=et(Gc(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?et(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),fe=u(()=>et(pt(),"auth.json"),"AUTH_FILE_PATH"),vr=u(()=>et(pt(),"secrets.json"),"SECRETS_FILE_PATH"),Tr=u(()=>et(pt(),"state.json"),"STATE_FILE_PATH"),Cr=u(()=>et(pt(),"telemetry.json"),"TELEMETRY_FILE_PATH"),Ir="apify.json",Er=".actor",qc="actor.json",L=et(Er,qc),Gs=new RegExp(`(^${Yc.INPUT}(?:\\.[^.]+)?$)`),Te=Bi.engines.node,Gi={"X-Apify-Request-Origin":Hc.CLI},rt="3.9.0",Yi=".venv";import{execSync as el}from"child_process";import{createWriteStream as tl,existsSync as oe,mkdirSync as rl,readdirSync as zi,readFileSync as Yt,writeFileSync as Rr}from"fs";import{mkdir as ol,readFile as _r}from"fs/promises";import{get as sl}from"https";import{homedir as Ys}from"os";import{dirname as ft,join as J,relative as il}from"path";import z from"process";import{finished as nl}from"stream/promises";import{DurationFormatter as Xi,TimeTypes as ot}from"@sapphire/duration";import{Timestamp as Hs}from"@sapphire/timestamp";import al from"adm-zip";import cl from"ajv/dist/2019.js";import{ApifyClient as Zi}from"apify-client";import ll from"archiver";import{AxiosHeaders as ul}from"axios";import ml from"escape-string-regexp";import dl from"ignore";import{getEncoding as pl}from"istextorbinary";import{Mime as fl}from"mime";import gl from"mime/types/other.js";import hl from"mime/types/standard.js";import{gte as yl,minVersion as wl,satisfies as Al}from"semver";import{glob as qs}from"tinyglobby";import{ACTOR_ENV_VARS as Js,ACTOR_JOB_TERMINAL_STATUSES as bl,ACTOR_NAME as Vt,APIFY_ENV_VARS as Sl,KEY_VALUE_STORE_KEYS as Wi,LOCAL_ACTOR_ENV_VARS as Ks,LOCAL_STORAGE_SUBDIRS as Ws,SOURCE_FILE_FORMATS as Bt}from"@apify/consts";import{existsSync as Jc,mkdirSync as Kc}from"fs";import{readFile as Wc,stat as Hi,unlink as zc,writeFile as Xc}from"fs/promises";import{join as qi,sep as Zc}from"path";import{rimraf as Qc}from"rimraf";var Ji=u(async(r,e={},t=null)=>{let o=await Wc(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await Xc(r,JSON.stringify(i,null," "))},"updateLocalJson"),$r=u((r,e)=>{e||(e=r,r="."),e.split(Zc).reduce((o,s)=>(o=qi(o,s),Jc(o)||Kc(o),o),r)},"ensureFolderExistsSync"),Ut=u(async r=>{await Qc(r)},"rimrafPromised"),jt=u(async r=>{(await Hi(r)).isFile()&&await zc(r)},"deleteFile"),Ki=u(async(r,e)=>(await Promise.all(r.map(async s=>Hi(qi(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var Gt=dl,Ht=cl,xr=u(async r=>new Promise((e,t)=>{sl(r,o=>{o.statusCode===301||o.statusCode===302?(e(xr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),he=u(()=>{let r=Sl.LOCAL_STORAGE_DIR;return z.env[r]||z.env.CRAWLEE_STORAGE_DIR||tt},"getLocalStorageDir"),ge=u(r=>{let e=Js.DEFAULT_KEY_VALUE_STORE_ID,t=r||z.env[e]||Ks[e];return J(he(),Ws.keyValueStores,t)},"getLocalKeyValueStorePath"),Qi=u(r=>{let e=Js.DEFAULT_DATASET_ID,t=r||z.env[e]||Ks[e];return J(he(),Ws.datasets,t)},"getLocalDatasetPath"),en=u(r=>{let e=Js.DEFAULT_REQUEST_QUEUE_ID,t=r||z.env[e]||Ks[e];return J(he(),Ws.requestQueues,t)},"getLocalRequestQueuePath"),U=u(async()=>{let r={};try{let e=await _r(fe(),"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}u(I,"getLoggedClientOrThrow");var tn=u(r=>{if(!r&&oe(pt())&&oe(fe())){let e=Yt(fe(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),qt=u((r,e)=>(r=tn(r),{token:r,baseUrl:e||z.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new ul;for(let[o,s]of Object.entries(Gi))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Jt(r,e){r=tn(r);let t=new Zi(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(fe()),Rr(fe(),JSON.stringify({token:t.token,...o},null," ")),t}u(Jt,"getLoggedClient");var zs=u(r=>J(r,L),"getLocalConfigPath"),le=u(r=>{if(oe(r))return JSON.parse(Yt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Me=u(r=>le(zs(r)),"getLocalConfig"),Pr=u(async(r,e)=>{let t=J(e||z.cwd(),L);await ol(ft(t),{recursive:!0}),Rr(t,JSON.stringify(r,null," "))},"setLocalConfig"),vl=[he(),"node_modules",".venv"],Or=u(async r=>{let e=ge();$r(r,Qi()),$r(r,en()),$r(r,e);let t=J(r,".gitignore"),o="";oe(t)&&(o=Yt(t,{encoding:"utf-8"}));let s=[];for(let i of vl)RegExp(`^${ml(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),Rr(t,`
|
|
2
|
-
${s.join(`
|
|
3
|
-
`)}
|
|
4
|
-
`,{flag:"a"})):Rr(t,`${s.join(`
|
|
5
|
-
`)}
|
|
6
|
-
`,{flag:"w"}))},"setLocalEnv"),rn=new fl(hl,gl).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),Tl=u((r,e)=>{let t=rn.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:pl(e)==="binary"?Bt.BASE64:Bt.TEXT},"getSourceFileFormat"),on=u(async(r,e)=>r.map(t=>{let o=Yt(J(e,t)),s=Tl(t,o);return{name:t,format:s,content:s===Bt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Cl=u(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 _r(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 _r(s,"utf-8"),n=il(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 l;if(n?i.startsWith(`${n}/`)?l=i.slice(n.length+1):l=null:l=c?`${c}/${i}`:i,l!==null&&a.ignores(l))return!1}return!0})},"getGitignoreFallbackFilter"),Il=u(async r=>{let e=J(r,".actorignore");if(!oe(e))return{excludeFilter:null,forceIncludePatterns:[]};let o=(await _r(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(l=>!c.ignores(l))}:null,forceIncludePatterns:i}},"parseActorIgnore"),sn=u(async r=>{let e=r??z.cwd(),t=[".git/**","apify_storage","node_modules","storage","crawlee_storage"],{excludeFilter:o,forceIncludePatterns:s}=await Il(e),i=null;try{let l=el("git ls-files --others --ignored --exclude-standard --directory",{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
8
|
-
`).filter(Boolean);if(l.length>0){let m=Gt().add(l);i=u(d=>d.filter(p=>!m.ignores(p)),"gitIgnoreFilter")}}catch{i=await Cl(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 l=Gt().add(s),m=n.filter(p=>l.ignores(p)),d=new Set(a);for(let p of m)d.add(p);a=[...d]}let c=n.filter(l=>l===".actor"||l.startsWith(".actor/"));if(c.length>0){let l=new Set(a);for(let m of c)l.add(m);a=[...l]}return a},"getActorLocalFilePaths"),nn=u(async(r,e,t)=>{oe(r)&&await jt(r);let o=tl(r),s=ll("zip",{zlib:{level:6}});s.pipe(o),e.forEach(i=>s.file(J(t,i),{name:i})),await s.finalize()},"createActZip"),Kt=u(r=>{let e=ge();if(!oe(J(r,e)))return;let s=zi(J(r,e)).find(a=>!!a.match(Gs));if(!s)return;let i=Yt(J(r,e,s)),n=rn.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),an=u(async()=>{let r=en();oe(he())&&oe(r)&&await Ut(r)},"purgeDefaultQueue"),cn=u(async()=>{let r=Qi();oe(he())&&oe(r)&&await Ut(r)},"purgeDefaultDataset"),ln=u(async()=>{let r=ge();if(!oe(he())||!oe(r))return;let e=zi(r),t=[];e.forEach(o=>{o.match(Gs)||t.push(jt(J(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),Pe=u(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new Zi({baseUrl:z.env.APIFY_CLIENT_BASE_URL});if(bl.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",l=>{z.env.APIFY_NO_LOGS_IN_TESTS||z.stderr.write(l.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var un=u(async()=>(await qs([`${he()}/**`,`!${ge()}/${Wi.INPUT}.*`,`!${ge()}/${Wi.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Wt=u(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"),kr=u(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"),Nr=u(r=>Al(r,`^${rt}`),"isPythonVersionSupported"),Dr=u(r=>{let e=wl(Te);return yl(r,e)},"isNodeVersionSupported"),Lr=u(async({url:r,pathTo:e})=>{let t=await xr(r),o=[];t.on("data",i=>o.push(i)),await nl(t),new al(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Xs(r){let e=ft(r);rl(e,{recursive:!0})}u(Xs,"ensureApifyDirectory");var Y=new Hs("YYYY-MM-DD [at] HH:mm:ss"),zt=new Hs(`YYYY-MM-DD[
|
|
9
|
-
]HH:mm:ss`),mn=new Hs("YYYY-MM-DD"),Xt=new Xi,ue=new Xi({[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 Fr(r,e){if("groupBy"in Object)return Object.groupBy(r,e);let t={},o=0;for(let s of r){let i=e(s,o++);t[i]||(t[i]=[]),t[i].push(s)}return t}u(Fr,"objectGroupBy");function dn(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}u(dn,"mapGroupBy");function D(r){console.log(JSON.stringify(r,null,2))}u(D,"printJsonToStdout");var ae=u(r=>r.startsWith(Ys())?r.replace(Ys(),"~"):r,"tildify");function pn(){let r=z.env.SHELL??"";return r.includes("zsh")?"zsh":r.includes("bash")?"bash":r.includes("fish")?"fish":"unknown"}u(pn,"detectShell");function fn(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}}u(fn,"shellConfigFile");var Ol=["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 gn(){return`CLI:${Pl()}`}u(gn,"createAnonymousId");async function kl(r){if(r.version&&r.version>=1)return!1;let e=r,t=await U().catch(()=>({}));return Zt({version:1,enabled:!0},o=>{t.id&&e.distinctId===t.id?(o.anonymousId=gn(),o.userId=t.id):o.anonymousId=e.distinctId}),!0}u(kl,"migrateStateV0ToV1");async function me(){let r=Cr();if(!El(r)){let s=await U().catch(()=>({}));return Zt({version:1,enabled:!0,anonymousId:gn(),userId:s.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&b({message:Ol}),me()}let t=JSON.parse(Rl(r,"utf-8"));return await kl(t)?me():t}u(me,"useTelemetryState");function Zt(r,e){let t={...r};e?.(t);let o=Cr(),s=xl(o);$l(s,{recursive:!0}),_l(Cr(),JSON.stringify(t,null," "))}u(Zt,"updateTelemetryState");async function Mr(r){let e=await me();Zt(e,t=>{t.userId=r})}u(Mr,"updateUserId");var Nl=1e4;async function hn(r){try{let e=await me(),t=Date.now(),o=e.lastCommand===r&&t-(e.lastCommandTimestamp??0)<Nl;return Zt(e,s=>{s.lastCommand=r,s.lastCommandTimestamp=t}),o}catch{return!1}}u(hn,"checkAndUpdateLastCommand");async function Ur(r){let e=await me();Zt(e,t=>{t.enabled=r})}u(Ur,"updateTelemetryEnabled");async function yn(){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 me();return T("telemetry state",{telemetryState:r}),r.enabled}u(yn,"useTelemetryEnabled");async function wn(){let r=await me();return{anonymousId:r.anonymousId,userId:r.userId}}u(wn,"useTelemetryIdentifiers");var Qt=W(),Dl="https://api.segment.io/v1/track",Ll=Qt.isBeta?"rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC":"2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t";async function An(r,e){let t=await wn(),o={anonymousId:t.anonymousId,context:{app:{name:"apify-cli",version:Qt.version,build:Qt.hash},library:{name:"apify-cli",version:Qt.version},os:{name:Qt.platform},userAgent:st,channel:"server"},event:r,properties:{...e,app:"cli"},timestamp:new Date().toISOString(),userId:t.userId,writeKey:Ll};if(T("trackEvent",o),!await yn()){T("trackEvent","telemetry disabled");return}try{let i=await fetch(Dl,{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)}}u(An,"trackEvent");import{access as ri,readdir as gt,readFile as Ql,stat as eu}from"fs/promises";import{join as j,resolve as Nn}from"path";import tu from"process";import{err as ru,ok as ti}from"@sapphire/result";import{existsSync as Tn,readdirSync as Gl}from"fs";import{join as Gr,resolve as Yl}from"path";import Hl from"configparser";import Bl from"@inquirer/input";import jl from"is-ci";import{constants as bn,fstat as Fl}from"fs";import Sn from"process";import{promisify as Ml}from"util";var Ul=Ml(Fl),Zs;async function jr(){if(Zs)return Zs;let r=Sn.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Ul(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()}),Sn.platform==="win32"){if((o.mode&bn.S_IFIFO)===bn.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}u(jr,"useStdin");var Qs="confirm",vn=`no-${Qs}`;function Oe(r,{errorMessageForStdin:e=`Please use the --${Qs}/--${vn} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await jr(),n=t;if(jl||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${Qs}/--${vn} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}u(Oe,"stdinCheckWrapper");var it=Oe(async({message:r,validate:e,default:t})=>await Bl({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});import{readFileSync as Vl}from"fs";var Br=class{static{u(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{u(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=Vl(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{u(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return Tn(Gr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Hl,t=Yl(Gr(this.pathname,"scrapy.cfg"));if(!Tn(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=Gl(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 In,some as En}from"@sapphire/result";import{execa as Rn}from"execa";import $n from"which";import{stat as Yr}from"fs/promises";import{isAbsolute as ql,join as Hr}from"path";function Ve(r){return r?r.startsWith('"')?r:ql(r)&&r.includes(" ")?`"${r}"`:r:null}u(Ve,"normalizeExecutablePath");async function Cn(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}u(Cn,"getInstallCommandSuggestion");var qr=new Map,Jl={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function Kl(r,e){try{let t=await Rn(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}}u(Kl,"getRuntimeVersion");async function Wl(r){let e=await Rn(r,["--version"],{shell:!0,windowsHide:!0,verbose:ei.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}u(Wl,"getNpmVersion");async function _n(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 $n(t)),i=await Kl(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ve(await $n("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Wl(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return qr.set(r,En(n)),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:qr.get(r)?.unwrap()}),En(n)}}catch{}return qr.set(r,In),T("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),In}u(_n,"useJavaScriptRuntime");import{platform as zl}from"os";import{join as xn}from"path";import Jr from"process";import{none as Pn,some as On}from"@sapphire/result";import{execa as Xl}from"execa";import Zl from"which";var Ge=new Map;async function kn(r){try{let e=await Xl(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}}u(kn,"getPythonVersion");async function tr({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=zl()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Jr.env.VIRTUAL_ENV?i=xn(Jr.env.VIRTUAL_ENV,...s):i=xn(r,".venv",...s),i=Ve(i);try{let a=await kn(i);if(a)return Ge.set(r,On({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 Zl(a)),l=await kn(c);if(l)return Ge.set(r,On({executablePath:c,version:l})),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:Ge.get(r)?.unwrap()}),Ge.get(r)}catch{}return Ge.set(r,Pn),T("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),Pn}u(tr,"usePythonRuntime");var Dn=new Map;async function ke({cwd:r=tu.cwd()}={}){let e=Dn.get(r);if(e)return T("useCwdProject",{cacheHit:!0,project:e}),ti(e);let t={type:3},s=await u(async()=>{if(await au(r)){t.type=2;let a=await tr({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 l=await Mn(r);l&&(t.entrypoint={path:l})}catch{}return}let n=await ou(r);if(!n){let a=null;try{a=await Mn(r)}catch(c){return ru({message:c instanceof Error?c.message:String(c)})}if(a){t.type=1;let c=await tr({cwd:r});t.entrypoint={path:a},t.runtime=c.unwrapOr(void 0);let l=j(r,a.replace(/\./g,"/"));await rr(j(l,"__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 _n();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}),Dn.set(r,t),ti(t))}u(ke,"useCwdProject");async function ou(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(Nn(r,s.main)),{path:Nn(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}u(ou,"checkNodeProject");async function rr(r){try{return await ri(r),!0}catch{return!1}}u(rr,"fileExists");async function Un(r){try{return(await eu(r)).isDirectory()}catch{return!1}}u(Un,"dirExists");function jn(r){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)}u(jn,"isValidPythonIdentifier");async function su(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}}u(su,"hasPythonFilesInDirOrSubdirs");async function iu(r){try{return(await gt(r,{withFileTypes:!0})).some(t=>t.isFile()&&t.name.endsWith(".py")&&t.name!=="__init__.py")}catch{return!1}}u(iu,"dirHasPyFiles");async function Ln(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=jn(o.name),i=await rr(j(r,o.name,"__init__.py")),n=i||await iu(j(r,o.name));s&&i||n&&t.push({name:o.name,needsRename:!s,needsInit:!i})}return t}catch{return[]}}u(Ln,"findNearMissPackagesInDir");async function Fn(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("_")||!jn(s))continue;let i=j(r,s,"__init__.py");await rr(i)&&t.push({name:s,path:j(r,s)})}return t}catch{return[]}}u(Fn,"findPackagesInDir");async function nu(r){let e=[],t=await Fn(r);e.push(...t.map(i=>i.name));let o=j(r,"src"),s=await rr(j(o,"__init__.py"));if(await Un(o)&&!s){let i=await Fn(o);e.push(...i.map(n=>`src.${n.name}`))}return e}u(nu,"discoverPythonPackages");async function Mn(r){let e=await nu(r);if(e.length===1)return e[0];if(e.length>1){let c=e.map(l=>` - ${l}`).join(`
|
|
12
|
-
`);throw new Error(`Multiple Python packages found:
|
|
13
|
-
${c}
|
|
14
|
-
|
|
15
|
-
Apify CLI cannot determine which package to run.
|
|
16
|
-
Please specify the package using the --entrypoint flag, e.g.:
|
|
17
|
-
apify run --entrypoint <package_name>`)}let t=await Ln(r),o=j(r,"src"),i=!await rr(j(o,"__init__.py"))&&await Un(o)?await Ln(o):[],n=[...t.map(c=>({...c,prefix:""})),...i.map(c=>({...c,prefix:"src/"}))];if(n.length>0){let c=n.map(({name:l,prefix:m,needsRename:d,needsInit:p})=>{let g=[];return d&&g.push(`rename to "${m}${l.replace(/[^a-zA-Z0-9_]/g,"_")}/"`),p&&g.push("add __init__.py"),` - "${m}${l}/" \u2192 ${g.join(" and ")}`}).join(`
|
|
18
|
-
`);throw new Error(`Found directories that appear to be Python packages but have issues:
|
|
19
|
-
${c}
|
|
20
|
-
|
|
21
|
-
A valid Python package requires a directory with a valid identifier name (letters, numbers, underscores) and an __init__.py file.`)}if(await su(r))throw new Error(`No Python package found. Found Python files, but no valid package structure detected.
|
|
22
|
-
A Python package requires:
|
|
23
|
-
- A directory with a valid Python identifier name (letters, numbers, underscores)
|
|
24
|
-
- An __init__.py file inside the directory
|
|
25
|
-
|
|
26
|
-
Common package structures:
|
|
27
|
-
my_package/
|
|
28
|
-
__init__.py
|
|
29
|
-
main.py
|
|
30
|
-
|
|
31
|
-
src/
|
|
32
|
-
my_package/
|
|
33
|
-
__init__.py
|
|
34
|
-
main.py`);return null}u(Mn,"checkPythonProject");async function au(r){return nt.isApplicable(r)}u(au,"checkScrapyProject");import K from"chalk";import sr from"chalk";import Yn from"indent-string";import Hn from"widest-line";import qn from"wrap-ansi";import Kr from"chalk";import oi from"indent-string";import mu from"string-width";import Vn from"strip-ansi";import Gn from"widest-line";import si from"wrap-ansi";import cu from"chalk";import lu from"indent-string";import Bn from"string-width";import uu 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}u(ce,"getMaxLineWidth");var ht=class{static{u(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(cu.bold("DESCRIPTION"));let t=uu(this.command.description,ce()-2,{trim:!1}),o=lu(t,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=Bn(e.join(" ").split(`
|
|
36
|
-
`).at(-1)||"")+o,i=Bn(t);s+i>ce()&&e.push(`
|
|
37
|
-
`),e.push(t)}kebabFlagName(e){return Ie(Ee(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{u(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
|
|
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(Kr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+mu(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 E=a.get(S),C=this.makeFlagString(S,E);v.push(C),E.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?v.join(" | "):`[${v.join(" | ")}]`,indentSize:o})}let l=si(s.join(" "),ce()-o),m=oi(l,o+1).trim();e.push(` ${m}`,""),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=Gn(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=Gn([...o.keys()].map(Vn).join(`
|
|
41
|
-
`));for(let[i,n]of o){let a=s-Vn(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
|
|
42
|
-
<options: ${n.choices.join("|")}>`);let l=si(c,ce()-s),m=oi(l,s).trim().split(`
|
|
43
|
-
`).map(d=>/^-[a-z]/.test(d.trim())?d:` ${d}`).join(`
|
|
44
|
-
`);e.push(` ${m}`)}e.push("")}};import du from"chalk";import pu from"indent-string";import fu from"widest-line";import gu from"wrap-ansi";var or=class extends ht{static{u(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
|
|
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(du.bold("SUBCOMMANDS"));let t=fu(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
|
|
47
|
-
`));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
|
|
48
|
-
`)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=gu(i,ce()-t-2),a=pu(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var ir=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){ir.set(e,new or(r,e));for(let t of e.subcommands)ii(`${r} ${e.name}`,t)}else ir.set(e,new Wr(r,e))}u(ii,"registerCommandForHelpGeneration");function zr(r){let e=ir.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}u(zr,"renderHelpForCommand");function Xr(r,e){let t=ir.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}u(Xr,"selectiveRenderHelpForCommand");function Jn(r,e){return r[0].name.localeCompare(e[0].name)}u(Jn,"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(sr.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(sr.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=dn(ir,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof or?"subcommand":"command"),s=o.get("subcommand")?.sort(Jn),i=o.get("command")?.sort(Jn);if(s?.length){t.push(sr.bold("TOPICS"));let n=[],a=Hn(s.map(([c])=>c.name).join(`
|
|
49
|
-
`));for(let[c]of s){if(c.hidden)continue;let l=c.shortDescription||c.description?.split(`
|
|
50
|
-
`)[0]||"",m=`${c.name.padEnd(a)} ${l}`,d=qn(m,ce()-a-2);n.push(` ${Yn(d,a+2+2).trim()}`)}t.push(...n,"")}if(i?.length){t.push(sr.bold("COMMANDS"));let n=[],a=Hn(i.map(([c])=>c.name).join(`
|
|
51
|
-
`));for(let[c]of i){if(c.hidden)continue;let l=c.shortDescription||c.description?.split(`
|
|
52
|
-
`)[0]||"",m=`${c.name.padEnd(a)} ${l}`,d=qn(m,ce()-a-2);n.push(` ${Yn(d,a+2+2).trim()}`)}t.push(...n,"")}return t.push(sr.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()}u(Zr,"renderMainHelpMenu");var Qr=(m=>(m[m.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",m[m.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",m[m.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",m[m.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",m[m.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",m[m.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",m[m.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",m[m.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",m[m.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",m[m.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",m))(Qr||{}),de=class r extends Error{static{u(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
|
-
|
|
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
|
-
|
|
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? ${$e?"Yes":"No"}`].join(`
|
|
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
|
-
${e.ambiguousMessage.split(`
|
|
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 Kn(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}u(Kn,"camelCaseString");function Ie(r){return r.replace(/[\s_]+/g,"-")}u(Ie,"kebabCaseString");function Ee(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}u(Ee,"camelCaseToKebabCase");var Au={type:"boolean",multiple:!1,short:"h"},bu={type:"boolean",multiple:!1},Z=new Map,Su=["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;let n=Ui();this.telemetryData.aiAgent=Mi(),this.telemetryData.isCi=n.isCi,this.telemetryData.ciProvider=n.ciProvider,this.telemetryData.isInteractive=ji()}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 t=Date.now(),{values:o,positionals:s,tokens:i}=e;o.help&&this.ctor.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof o.json=="boolean"?this.flags.json=o.json:this.flags.json=!1);let n=new Map;if(this.ctor.args){let a=0;for(let[c,l]of Object.entries(this.ctor.args)){if(typeof l=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let m=Kn(c),d=s[a++];if(d)switch(l.argTag){default:this.args[m]=String(d),d==="-"&&l.stdin&&(this.args[m]=this._handleStdin(l.stdin)),l.catchAll&&(this.args[m]=s.slice(a-1).join(" "));break}else l.required&&n.set(c,l)}}if(n.size){process.exitCode=1,this._printMissingRequiredArgs(n);return}this._parseFlags(o,i);try{await this.run()}catch(a){f({message:a.message}),process.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Su.includes(this.commandString)&&(await ke()).inspect(c=>{c.type===0?(this.telemetryData.actorLanguage="javascript",this.telemetryData.actorRuntime=c.runtime.runtimeShorthand||"node",this.telemetryData.actorRuntimeVersion=c.runtime.version):(c.type===1||c.type===2)&&(this.telemetryData.actorLanguage="python",this.telemetryData.actorRuntime="python",this.telemetryData.actorRuntimeVersion=c.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof process.exitCode=="number"?process.exitCode:0,this.telemetryData.durationMs=Date.now()-t,this.telemetryData.wasRetried=await hn(this.commandString),await An(`cli_command_${this.commandString.replaceAll(" ","_").toLowerCase()}`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let o=Ie(Ee(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(Ie(Ee(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=Ie(Ee(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:l,rawBaseFlagName:m}=this._userFlagNameToRegisteredName(n,a),d=Kn(m),p=t.some(v=>v.kind==="option"&&v.name===l);if(a.exclusive?.length){let v=o.get(l)??new Set;for(let S of a.exclusive)v.add(this._commandFlagKeyToKebabCaseRegisteredName(S));o.set(l,v);for(let S of a.exclusive){let E=this._commandFlagKeyToKebabCaseRegisteredName(S),C=o.get(E)??new Set;C.add(l),o.set(E,C)}}let g=c.filter(v=>e[v]);if(g.length>1)throw new de({code:3,command:this.ctor,metadata:{flag:l}});let y=e[g[0]];if(!y&&a.required)throw new de({code:6,command:this.ctor,metadata:{flag:l,matcher:g[0]}});if(Array.isArray(y)){if(y.length>1)throw new de({code:3,command:this.ctor,metadata:{flag:l}});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]=m.startsWith("no-")?!y:y;break}case"integer":{let v=Number(y);if(Number.isNaN(v)||!Number.isInteger(v))throw new de({code:4,command:this.ctor,metadata:{flag:l,value:String(y)}});this.flags[d]=v;break}default:{if(this.flags[d]=y,y==="-"&&a.stdin){if(s)throw new de({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:l}});s=l,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 de({code:5,command:this.ctor,metadata:{flag:l,choices:a.choices.map(v=>ni.white.bold(v)).join(", ")}});if(this.flags[d]==null&&(a.required||y!=null))throw new de({code:6,command:this.ctor,metadata:{flag:l,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 l=e[n][0],m=e[c][0],d=u((p,g)=>typeof g=="boolean"?g?`--${p}`:`--no-${p}`:`--${p}=${g}`,"flagRepresentation");i.push([d(n,l),d(c,m)]);break}if(i.length)throw new de({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t;try{t=Xr(this.ctor,{showUsageString:!0})}catch{}let o=yu([...e.keys()].join(`
|
|
65
|
-
`)),s=[];for(let[n,a]of e){let c=`${n.padEnd(o)} ${a.description}`,l=wu(c,ce()-o-2),m=hu(l,o+2+2).trim();s.push(` ${ni.red(">")} ${m}`)}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?($e?.toString("utf8")??"").trim():$e}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:Au}};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(Ee(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=bu),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 Wn(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,l]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let m=Ie(Ee(l)).toLowerCase();m.startsWith("no-")?o.values[m.slice(3)]=!a:o.values[m]=a}}let i=new e(r,e.name,e.name);i.skipTelemetry=!0,await i._run(o)}u(Wn,"internalRunCommand");import{once as vu}from"events";async function zn(){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 vu(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}u(zn,"readStdin");import{gt as xu}from"semver";import{existsSync as Tu,mkdirSync as Cu,readFileSync as Iu,writeFileSync as Eu}from"fs";import{dirname as $u}from"path";function Ru(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}u(Ru,"migrateStateV0ToV1");var _u={version:1};function ai(){let r=Tr();if(!Tu(r))return _u;let t=JSON.parse(Iu(r,"utf-8"));return Ru(t)?ai():t}u(ai,"useLocalState");function ci(r,e){let t={...r};e(t);let o=Tr(),s=$u(o);Cu(s,{recursive:!0}),Eu(Tr(),JSON.stringify(t,null," "))}u(ci,"updateLocalState");var eo=W(),Xn=`Apify CLI/${eo.version} (https://github.com/apify/apify-cli)`,Pu=["https://1.1.1.1","https://8.8.8.8"];async function Ou(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Pu.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":Xn},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)}u(Ou,"isOnline");async function ku(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":Xn}});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}u(ku,"getLatestVersion");function Zn(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}u(Zn,"shouldSkipVersionCheck");async function Qn(r=!1){let e=ai(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>Vi,o=r||t&&await Ou(),s=o?await ku(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:eo.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=xu(s,eo.version);return{currentVersion:eo.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}u(Qn,"useCLIVersionCheck");import{jaroWinkler as Nu}from"@skyra/jaro-winkler";import Du 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(),l=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,m=Du(t,n),d=Nu(t,n),p=m<=2||d>=.975;return p?(T("useCommandSuggestions",{inputString:t,lowercased:n,matches:p,levenshtein:m,jaroWinkler:d}),l?{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)}u(to,"useCommandSuggestions");var $e=await zn(),nr=W(),st=`Apify CLI/${nr.version} (https://github.com/apify/apify-cli)`;function cw(r){nr.installMethod!=="bundle"&&(Lu(Re.version,Te)||(f({message:`${r} CLI requires Node.js version ${Te}. Your current version is ${Re.version}.`}),Re.exit(1)))}u(cw,"processVersionCheck");function Fu(r){r.values.version===!0&&r.positionals.length===0&&(console.log(nr.fullVersionString),Re.exit(0))}u(Fu,"printCLIVersionAndExitIfFlagUsed");function Mu(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(Zr(e)),Re.exit(0))}u(Mu,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function ta(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)}u(ta,"handleCommandNotFound");async function Uu(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(Zn()){T("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await Wn(r,t,{flags_internalAutomaticCall:!0})}u(Uu,"runVersionCheck");async function lw(r){T("CLIMetadata",{...nr,fullVersionString:nr.fullVersionString,argv:Re.argv,cwd:Re.cwd(),execPath:Re.execPath});let e=Re.argv.slice(2);T("ProcessArgv",e);let t=ea({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Fu(t),Mu(t,r),await Uu(r,t.positionals[0]),T("TopLevelOptions",t);let[o,s]=t.positionals,i=!1,n=Z.get(o);if(!n)return ta(o);let a=n;if(n.subcommands?.length){if(!s)return n.printHelp();i=!0,a=Z.get(`${o} ${s}`)}if(!a)return ta(`${o} ${s}`);let c=[...e],l=c.indexOf(o);if(T("CommandNameIndex",l),c.splice(l,1),i){let p=c.indexOf(s);T("SubcommandNameIndex",p),c.splice(p,1)}T("RebuiltArgs",c),T("CommandToRun",a);let m=new a(r,i?`${n.name} ${s}`:n.name,o,i?s:void 0),d=m._buildParseArgsOption();T("ParserOptionsForCommand",d);try{let p=ea({...d,args:c});await m._run(p),T("CommandArgsResult",p)}catch(p){let g=de.into(p,a);f({message:g.getPrettyMessage()}),Re.exit(1)}}u(lw,"runCLI");import{join as sm,resolve as im}from"path";import ui from"process";import{calculateRunDynamicMemory as nm}from"@apify/actor-memory-expression";var w={string:ju,boolean:Bu,integer:Vu};function ju(r){return{flagTag:"string",builder:u(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(Ee(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}}u(ju,"stringFlag");function Bu(r){return{flagTag:"boolean",builder:u(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(Ee(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}}u(Bu,"booleanFlag");function Vu(r){return{flagTag:"integer",builder:u(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(Ee(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}}u(Vu,"integerFlag");import{mkdir as Ku,rename as na,writeFile as Wu}from"fs/promises";import{dirname as zu,join as Xu}from"path";import ia from"process";import{inspect as Zu}from"util";import{err as ar,ok as io}from"@sapphire/result";import{createPrompt as Gu,isEnterKey as Yu,makeTheme as Hu,useKeypress as qu,usePrefix as Ju,useState as ra}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}u(li,"getBooleanValue");function oa(r){return r?"Yes":"No"}u(oa,"boolToString");var sa=Gu((r,e)=>{let t=oa,[o,s]=ra("idle"),[i,n]=ra(""),a=Hu(),c=Ju({status:o,theme:a});qu((p,g)=>{if(Yu(p)){let y=li(i,r.default);n(t(y)),s("done"),e(y);return}if(p.name==="tab"){let y=oa(!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 l=i,m="";o==="done"?l=a.style.answer(i):m=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let d=a.style.message(r.message,o);return`${c} ${d}${m} ${l}`});var X=Oe(async({message:r,default:e})=>await sa({message:r,default:e}));var Qu=u(r=>Xu(r,Ir),"getDeprecatedLocalConfigPath"),so=new Map;async function Ne({cwd:r=ia.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:ia.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(l){return ar({message:`Failed to read local config at path: '${s}':`,cause:l,exists:!1,config:{}})}try{a=le(i)}catch(l){return ar({message:`Failed to read local config at path: '${i}':`,cause:l,exists:!1,config:{}})}if(n&&a&&t&&await em(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 l=await rm(a,i,s);if(l.isErr())return ar(l.unwrapErr());n=l.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||{}})}u(Ne,"useActorConfig");async function em(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 na(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
|
-
${t.message||t}`}):f({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
|
|
69
|
-
${Zu(t,{showHidden:!1})}`})}}u(em,"handleBothConfigVersionsFound");var tm=["name","version","buildTag"];async function rm(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=om(o)),o={actorSpecification:Vs,environmentVariables:r?.env||void 0,...tm.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 ar({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 Ku(zu(t),{recursive:!0}),await Wu(t,JSON.stringify(o,null," "))}catch(i){let n=i;return ar({message:`Failed to write the new "actor.json" file to path: '${t}'.
|
|
70
|
-
${n.message||n}`,exists:!0,config:o})}try{await na(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)}u(rm,"handleMigrationFlow");function om(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}u(om,"updateLocalConfigStructure");var am=sm(ge("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:am}),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=im(ui.cwd(),e),a=le(n)??{};b({message:`Evaluating memory expression: ${t}`});try{let c=await nm(t,{input:a,runOptions:i}),l=Math.min(Math.max(c,o),s);$({message:`Calculated memory: ${l} 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 fm}from"@apify/consts";import cr from"process";import{pipeline as cm}from"stream/promises";import{MemoryStorage as lm}from"@crawlee/memory-storage";import{ApifyClient as um}from"apify-client";import{ACTOR_ENV_VARS as aa,APIFY_ENV_VARS as ca,KEY_VALUE_STORE_KEYS as mm,LOCAL_ACTOR_ENV_VARS as dm}from"@apify/consts";var lr={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},mi=u(async()=>{let r=cr.env[ca.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=u(async(r={},e=Reflect.has(cr.env,ca.IS_AT_HOME))=>{let t=he();if(t&&!e)return new lm({localDataDirectory:t,...r});let o=await mi();return new um({...qt(o),...r})},"getApifyStorageClient"),ur=u(r=>{let e=aa[`DEFAULT_${r}_ID`];return cr.env[e]||dm[e]},"getDefaultStorageId"),di=u(async r=>{let e=await at(),t=ur(lr.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await cm(o.value,cr.stdout,{end:!1})},"outputRecordFromDefaultStore"),la=u(async()=>di(cr.env[aa.INPUT_KEY]||mm.INPUT),"outputInputFromDefaultStore");function pm(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}u(pm,"stringArg");var A={string:pm};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[fm.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 Am,writeFile as lo}from"fs/promises";import vt from"path";import Aa from"process";import{compile as uo}from"json-schema-to-typescript";import{existsSync as gm,writeFileSync as hm}from"fs";import{join as mr}from"path";import{cloneDeep as ym}from"es-toolkit";import{KEY_VALUE_STORE_KEYS as wm}from"@apify/consts";import{validateInputSchema as ma}from"@apify/input_schema";var ua=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],At=u(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=mr(e,Er,t.input);return{inputSchema:le(o),inputSchemaPath:o}}for(let o of ua){let s=mr(e,o);if(gm(s))return{inputSchema:le(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:mr(e,ua[0])}},"readInputSchema"),no=u(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 ma(i,o),{inputSchema:o,inputSchemaPath:s}},"readAndValidateInputSchema"),ao=u(({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=mr(r,Er,i),a=le(n);return a?{schema:a,schemaPath:n}:(_({message:`${t} schema file not found at ${n} (referenced in '${L}').`}),null)}return null},"readStorageSchema"),da=u(({cwd:r})=>{let e=ao({cwd:r,key:"dataset",label:"Dataset"});return e?{datasetSchema:e.schema,datasetSchemaPath:e.schemaPath}:null},"readDatasetSchema"),pa=u(({cwd:r})=>{let e=ao({cwd:r,key:"output",label:"Output",getRef:u(t=>t?.output,"getRef")});return e?{outputSchema:e.schema,outputSchemaPath:e.schemaPath}:null},"readOutputSchema"),co=u(async r=>{let e={};try{let{inputSchema:t}=await At({cwd:r});if(t){let o=new Ht({strict:!1});ma(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=ge(),o=mr(r,t,`${wm.INPUT}.json`);hm(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),fa=u(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),ga=u((r,e)=>{let t=ym(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");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}u(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}u(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}u(ye,"stripTitles");function ha(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}u(ha,"prepareFieldsSchemaForCompilation");function ya(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}u(ya,"prepareOutputSchemaForCompilation");function wa(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}u(wa,"prepareKvsCollectionsForCompilation");var bm=`
|
|
73
|
-
// biome-ignore-all lint: generated
|
|
74
|
-
// biome-ignore-all format: generated
|
|
75
|
-
/* eslint-disable */
|
|
76
|
-
/* prettier-ignore-start */
|
|
77
|
-
/*
|
|
78
|
-
* This file was automatically generated by json-schema-to-typescript.
|
|
79
|
-
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
|
|
80
|
-
* and run apify actor generate-schema-types to regenerate this file.
|
|
81
|
-
*/
|
|
82
|
-
`,Tt=class extends h{static name="generate-schema-types";static hiddenAliases=["generate-types"];static description=`Generate TypeScript types from Actor schemas.
|
|
83
|
-
|
|
84
|
-
Generates types from the input schema and, when no custom path is provided,
|
|
85
|
-
also from the Dataset, Output (experimental), and Key-Value Store (experimental)
|
|
86
|
-
schemas defined in '${L}'.
|
|
87
|
-
|
|
88
|
-
Reads the input schema from one of these locations (in priority order):
|
|
89
|
-
1. Object in '${L}' under "input" key
|
|
90
|
-
2. JSON file path in '${L}' "input" key
|
|
91
|
-
3. .actor/INPUT_SCHEMA.json
|
|
92
|
-
4. INPUT_SCHEMA.json
|
|
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=Aa.cwd(),{inputSchema:t}=await no({forcePath:this.args.path,cwd:e,getMessage:u(l=>l?`Generating types from input schema at ${l}`:`Generating types from input schema embedded in '${L}'`,"getMessage")}),o="input",s=this.flags.allOptional?St(t):pi(t),i={bannerComment:bm,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 Am(a,{recursive:!0});let c=vt.join(a,`${o}.ts`);if(await lo(c,n,"utf-8"),$({message:`Generated types written to ${c}`}),!this.args.path){let l=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})]),m=["Dataset","Output","Key-Value Store"],d=!1;for(let[p,g]of l.entries())g.status==="rejected"&&(d=!0,f({message:`Failed to generate types for ${m[p]} schema: ${g.reason instanceof Error?g.reason.message:String(g.reason)}`}));d&&(Aa.exitCode=1)}}async generateDatasetTypes({cwd:e,outputDir:t,compileOptions:o}){let s=da({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 '${L}'`});let a=ha(i);if(!a){_({message:"Dataset schema has no fields defined, skipping type generation."});return}let c="dataset",l=this.flags.allOptional?St(a):a,m=await uo(ye(l),c,o),d=vt.join(t,`${c}.ts`);await lo(d,m,"utf-8"),$({message:`Generated types written to ${d}`})}async generateOutputTypes({cwd:e,outputDir:t,compileOptions:o}){let s=pa({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 '${L}'`});let a=ya(i);if(!a){_({message:"Output schema has no properties defined, skipping type generation."});return}let c="output",l=this.flags.allOptional?St(a):a,m=await uo(ye(l),c,o),d=vt.join(t,`${c}.ts`);await lo(d,m,"utf-8"),$({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 '${L}'`});let a=wa(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:m,schema:d}of a){let p=this.flags.allOptional?St(d):d,g=await uo(ye(p),m,{...o,bannerComment:c.length===0?o.bannerComment:""});c.push(g)}let l=vt.join(t,"key-value-store.ts");await lo(l,c.join(`
|
|
95
|
-
`),"utf-8"),$({message:`Generated types written to ${l}`})}};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 la()}};import{ACTOR_ENV_VARS as fi,APIFY_ENV_VARS as Sm}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[Sm.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 Et=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 $t=class extends h{static name="push-data";static description=`Saves data to Actor's run default dataset.
|
|
96
|
-
|
|
97
|
-
Accept input as:
|
|
98
|
-
- JSON argument:
|
|
99
|
-
$ apify actor push-data {"key": "value"}
|
|
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||$e;if(!t){f({message:"No item was provided."});return}let o=await at(),s=ur(lr.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
|
-
|
|
103
|
-
It is possible to pass data using argument or stdin.
|
|
104
|
-
|
|
105
|
-
Passing data using argument:
|
|
106
|
-
$ apify actor set-value KEY my-value
|
|
107
|
-
|
|
108
|
-
Passing data using stdin with pipe:
|
|
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
|
-
- If empty, the record in the key-value store is deleted.
|
|
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,n=(await at()).keyValueStore(ur(lr.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,$t,Et,It,Ct,wt,yt,Tt];async run(){this.printHelp()}};import De from"chalk";import vm from"process";async function He({providedActorNameOrId:r,client:e}){let t=await U(),o=t.username||t.id,s=Me(vm.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"}}u(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(),m=Fr(c.versions,C=>C.buildTag??"latest")[e??"latest"],d=c.versions.find(C=>C.versionNumber===t),p,g=e;if(d){if(e&&(!m||!m.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(m&&(p=m[0].versionNumber,g=e??"latest",m.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: ${m.map(C=>De.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){D(y);return}let v=[`${De.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${De.gray(y.actId)})`,` ${De.yellow("Version")}: ${p} (tagged with ${De.yellow(g)})`,"",`${De.greenBright("Build Started")} (ID: ${De.gray(y.id)})`,` ${De.yellow("Build Number")}: ${y.buildNumber} (will get tagged once finished)`,` ${De.yellow("Started")}: ${Y.display(y.startedAt)}`,""],S=`https://console.apify.com/actors/${y.actId}/builds/${y.buildNumber}`,E=`${De.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:E,stdout:!0})}};var po=class extends _t{static name="build"};import Ta from"process";import{DownloadItemsFormat as $m}from"apify-client";import ne from"chalk";import{access as Tm,readFile as Cm}from"fs/promises";import Im,{resolve as ba}from"path";import Le from"process";import Em from"mime";function Sa(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Kt(r);s&&(Em.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}}u(Sa,"resolveInput");async function xt(r,e,t){let o,s;if(!e&&!t){let i=$e;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."}),Le.exitCode=5,!1;o=n,s="stdin"}catch(n){return f({message:`Cannot parse JSON input from standard input.
|
|
115
|
-
${n.message}`}),Le.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`."}),Le.exitCode=5,!1;default:{let i=await Tm(ba(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||Im.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'}),Le.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."}),Le.exitCode=5,!1;o=a,s="input"}catch(a){return f({message:`Cannot parse JSON input.
|
|
116
|
-
${a.message}`}),Le.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`."}),Le.exitCode=5,!1;default:{let i=ba(r,t),n;try{let a=await Cm(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."}),Le.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."}),Le.exitCode=5,!1;o=a,s=t}catch{return f({message:`Cannot read input file at path "${i}".
|
|
117
|
-
${n.message}`}),Le.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}u(xt,"getInputOverride");import gi from"process";import fo from"chalk";import{ACTOR_JOB_STATUSES as qe}from"@apify/consts";var va=[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:l,printRunLogs:m}=e,d=i==="Actor"?"actor":"task",p=Sa(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&&m)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(),l)for(;!va.includes(g.status)&&(g=await r.run(g.id).get(),!va.includes(g.status));)await new Promise(y=>{setTimeout(y,1e3)});c||(g.status===qe.SUCCEEDED?$({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}u(Pt,"runActorOrTaskOnCloud");var Ot=u(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 '${L}' file.`})};async run(){let e=Ta.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."}),Ta.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),l={waitForFinish:2};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let m=await xt(e,this.flags.input,this.flags.inputFile);if(m===!1)return;let d=!1,p,g,y,v=Pt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:m?.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 E=[`${ne.yellow("Started")}: ${Y.display(S.startedAt)}`];S.containerUrl&&E.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)})`),E.push(k.join(" ")),E.push(`${ne.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),E.push(`${ne.yellow("Memory")}: ${p.options.memoryMbytes} MB`),E.push(`${ne.blue("View on Apify Console")}: ${g}`,""),R({message:E.join(`
|
|
124
|
-
`),stdout:!this.flags.json})}if(this.flags.json){D(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,E,C=4;do{if(E=await o.dataset(S).get(),E?.itemCount)break;await new Promise(N=>{setTimeout(N,250)})}while(C--);let P=await o.dataset(S).downloadItems($m.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 Rm from"cli-table3";var _m={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},xm={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Pm={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 Om={[-1]:void 0,0:_m,1:xm,2:Pm};function km(r){return Array.from({length:r},()=>"cyan")}u(km,"generateHeaderColors");var Nm=process.stdout.columns??100,go=Symbol.for("@apify/cli:responsive-table:skip-column"),B=class r{static{u(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=km(t.length),s=e===0||e===2,i=Om[e],n=[],a=[],c=[];for(let m of t)this.options.hiddenColumns?.includes(m)||this.rows.some(d=>d[m]===go)||(n.push(this.options.columnAlignments?.[m]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[m]?.label??m),c.push(this.options.breakpointOverrides?.small?.[m]?.valueFrom??m)):(a.push(m),c.push(m)));let l=new Rm({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let m of this.rows){let d=c.map(p=>m[p]);l.push(d)}return l.toString()}static isSmallTerminal(){return Nm<100}};var ho="\u200B",yo="\u200B\u200B",Ca=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){D(a);return}let l=a.taggedBuilds?.latest;if(t){if(!l){f({message:"No README found for this Actor.",stdout:!0});return}if(!l.build?.readme){f({message:"No README found for this Actor.",stdout:!0});return}R({message:l.build.readme,stdout:!0})}if(o){if(!l){f({message:"No input schema found for this Actor.",stdout:!0});return}if(!l.build?.inputSchema){f({message:"No input schema found for this Actor.",stdout:!0});return}R({message:l.build.inputSchema,stdout:!0})}let m=[`Information about Actor ${O.yellow(`${a.username}/${a.name}`)} (${O.gray(a.id)})`,""];a.title&&m.push(`${O.yellow("Title:")} ${O.bold(a.title)}`),a.description&&m.push(`${O.yellow("Description:")} ${a.description}`),m.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&&(m.push("",`${O.yellow("Made by:")} ${O.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(m[m.length-1]+=` ${O.bgGray("Maintained by Apify")}`)),a.isPublic?m.push("",`${O.yellow("Actor is")} ${O.green("PUBLIC")}`):m.push("",`${O.yellow("Actor is")} ${O.cyan("PRIVATE")}`),a.isDeprecated&&m.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(m.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let g=p.trialMinutes*60*1e3,y=Xt.format(g);m.push(` ${O.yellow("Trial duration:")} ${O.bold(y)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=p.pricePerUnitUsd*1e3;m.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{m.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay per event")}`);let g=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let S of g)Ca.pushRow({[ho]:S.eventTitle,[yo]:O.bold(`$${S.eventPriceUsd.toFixed(2)}`)});let v=Ca.render(0).split(`
|
|
126
|
-
`);v.splice(1,1),m.push(v.join(`
|
|
127
|
-
`));break}case"FREE":{m.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);break}default:m.push(`${O.yellow("Pricing information:")} ${O.bgGray(`Unknown pricing model (${O.yellow(p.pricingModel)})`)}`)}}else m.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(m.push("",O.yellow("SEO information:")),a.seoTitle&&m.push(` ${O.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&m.push(` ${O.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){m.push("",O.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&m.push(` ${O.yellow("-")} ${O.cyan(p.buildNumber)} ${O.gray("/")} ${O.yellow("latest")}`);for(let[g,y]of Object.entries(a.taggedBuilds))g!=="latest"&&m.push(` ${O.yellow("-")} ${O.cyan(y.buildNumber)} ${O.gray("/")} ${O.yellow(g)}`)}R({message:m.join(`
|
|
128
|
-
`),stdout:!0})}};import{Time as Dm}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(" "))}}u(xe,"prettyPrintStatus");var Lm={"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")},Fm=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"}}}}),Mm=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){D(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){D(c);return}let l=s?Mm:Fm,m=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(([E,C])=>C.buildNumber===d.actor.defaultRunOptions.build||E===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 E=[xe(d.lastRun.status)];if(g&&E.push(Lm[d.lastRun.status],Q.cyan(g)),d.lastRun.finishedAt){let C=Date.now()-d.lastRun.finishedAt.getTime();C<Dm.Week?E.push(`
|
|
129
|
-
`,Q.gray(`${ue.format(C)} ago`)):E.push(`
|
|
130
|
-
`,Q.gray("On",mn.display(d.lastRun.finishedAt)))}return E.join(" ")}return""})();l.pushRow({Name:`${d.title}
|
|
131
|
-
${Q.gray(`${d.username}/${d.name}`)}`,Runs:B.isSmallTerminal()&&m>=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:l.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 Ia,readdirSync as Um,writeFileSync as Ea}from"fs";import{dirname as jm,join as Bm}from"path";import $a from"process";import Vm from"adm-zip";import Gm from"axios";import Ra from"jju";import{gt as Ym}from"semver";import Hm from"tiged";var _a=u(async(r,e)=>{let{data:t}=await Gm.get(r,{responseType:"arraybuffer"}),o=new Vm(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=$a.cwd(),t=await Ne({cwd:e});if(t.isErr()){f({message:t.unwrapErr().message}),$a.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 l;try{l=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!l)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:m,versions:d}=l,p=u(()=>{throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.")},"throwMissingSourceCodeAccessError");if(!l.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,E)=>Ym(`${E.versionNumber}.0`,`${S.versionNumber}.0`)?E:S));let y=n?e:Bm(e,this.flags.dir??m);if(Ia(y,{recursive:!0}),!n&&Um(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 _a(g.tarballUrl,y);break}case"SOURCE_FILES":{g.sourceFiles||p();let{sourceFiles:S}=g;for(let E of S){let C=jm(E.name);if(Ia(`${y}/${C}`,{recursive:!0}),!E.folder){let P=E.format==="BASE64"?Buffer.from(E.content,"base64").toString():E.content;if(E.name===L){let N=Ra.parse(P);N.name=l.name,Ea(`${y}/${E.name}`,Ra.update(P,N))}else Ea(`${y}/${E.name}`,P)}}break}case"GIT_REPO":{g.gitRepoUrl||p();let{gitRepoUrl:S}=g,[E,C]=S.split("#"),P,N;C&&([P,N]=C.split(":"));let k=E;N&&(k+=`/${N}`),P&&(k+=`#${P}`);let M=Hm(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 _a(`${g.gitHubGistUrl}/archive/master.zip`,y);break}default:throw new Error(`Unknown source type: ${v}`)}$({message:n?`Actor ${m} updated at ${y}/`:`Pulled to ${y}/`})}};import{readFileSync as Km,statSync as Wm,unlinkSync as zm}from"fs";import{join as Xm,resolve as Zm}from"path";import ct from"process";import Qm from"open";import{fetchManifest as ed}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as lt,ACTOR_SOURCE_TYPES as yi,MAX_MULTIFILE_BYTES as Ma}from"@apify/consts";import{createHmacSignature as td}from"@apify/utilities";import{readFileSync as qm,writeFileSync as Jm}from"fs";var hi="@",xa=100,Pa=5e4,Nt=u(()=>{try{return JSON.parse(qm(vr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),Oa=u(r=>(Xs(vr()),Jm(vr(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),ka=u((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>xa)throw new Error(`Secret name has to be string with maximum length ${xa}.`);if(typeof e!="string"||e.length>Pa)throw new Error(`Secret value has to be string with maximum length ${Pa}.`);return t[r]=e,Oa(t)},"addSecret"),Na=u(r=>{let e=Nt();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],Oa(e)},"removeSecret"),Da=u(r=>new RegExp(`^${hi}.{1}`).test(r),"isSecretKey"),La=u((r,e,{allowMissing:t=!1}={})=>{e=e||Nt();let o={},s=[];if(Object.keys(r).forEach(i=>{if(Da(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
|
-
|
|
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"),Fa=u((r,e,{allowMissing:t=!1}={})=>{e=e||Nt();let o=[],s=[];if(Object.keys(r).forEach(i=>{if(Da(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
|
-
|
|
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 wi="temp_file.zip",rd={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Ua="0.0",od="latest",Dt=class extends h{static name="push";static description=`Deploys Actor to Apify platform using settings from '${L}'.
|
|
142
|
-
Files under '${Ma/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
|
|
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 '${L}' 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 '${L}' 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 '${L}' file.`})};async run(){let e=Zm(ct.cwd(),this.flags.dir??"."),t=await sn(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(![Ir,"actor.json",".actor/actor.json",".actor"].some(F=>t.some(re=>re===F||re.startsWith(F)))){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}`:"",l,m,d=!1,p=this.flags.version||i?.version||Ua,g=this.flags.buildTag||i?.buildTag;!g&&p===Ua&&(g=od);let y=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,v=this.args.actorId;if(v){if(m=await o.actor(v).get(),!m)throw new Error(`Cannot find Actor with ID '${v}' in your account.`);l=m.id}else{let F=n.username||n.id;if(m=await o.actor(`${F}/${i.name}`).get(),m)l=m.id;else{let{templates:re}=await ed(),Se=re.find(br=>br.name===i.template)?.defaultRunOptions||rd,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}),m=await o.actors().create(mt),l=m.id,d=!0,b({message:`Created Actor with name ${i.name} on Apify.`})}}let S=o.actor(l);b({message:`Deploying Actor '${i.name}' to Apify.`});let E=await Ki(t,e),C,P,N;if(E<Ma){let F=await S.get();if(!d){let re=t.reduce((Se,mt)=>{let{mtimeMs:br,ctimeMs:Di}=Wm(Xm(e,mt)),Li=br>Di?br:Di;return Se>Li?Se:Li},0),be=F?.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 on(t,e),C=yi.SOURCE_FILES}else{ve({message:"Zipping Actor files"}),await nn(wi,t,e);let F=await o.keyValueStores().getOrCreate(`actor-${l}-source`),re=`version-${p}.zip`,be=Km(wi);await o.keyValueStore(F.id).setRecord({key:re,value:be,contentType:"application/zip"}),zm(wi);let Se=new URL(`${o.baseUrl}/key-value-stores/${F.id}/records/${re}?disableRedirect=true`);if(F?.urlSigningSecretKey){let mt=td(F.urlSigningSecretKey,re);Se.searchParams.set("signature",mt)}N=Se.toString(),C=yi.TARBALL}let k=await S.version(p).get(),M=i.environmentVariables?Fa(i.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0;if(k){let F={tarballUrl:N,sourceFiles:P,buildTag:g,sourceType:C,envVars:M};await S.version(p).update(F),ve({message:`Updated version ${p} for Actor ${m.name}.`})}else{let F={versionNumber:p,tarballUrl:N,sourceFiles:P,buildTag:g,sourceType:C,envVars:M};await S.versions().create({...F}),ve({message:`Created version ${p} for Actor ${m.name}.`})}if(!d&&!!i.usesStandbyMode!=!!m.actorStandby?.isEnabled){let F=!!i.usesStandbyMode;await S.update({actorStandby:{isEnabled:F}}),b({message:`${F?"Enabled":"Disabled"} standby mode for Actor ${m.name}.`})}ve({message:`Building Actor ${m.name}`});let q=await S.build(p,{useCache:!0,waitForFinish:2});try{await Pe({job:q,timeoutMillis:y,apifyClient:o})}catch(F){_({message:"Can not get log:"}),console.error(F)}if(q=await o.build(q.id).get(),this.flags.json){D(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?$({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(),$({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 sd}from"apify-client";import Ai from"chalk";var id={FREE:"Free",FLAT_PRICE_PER_MONTH:"Subscription",PRICE_PER_DATASET_ITEM:"Pay per result",PAY_PER_EVENT:"Pay per event"};function nd(r){return r?id[r]??r:Ai.gray("Unknown")}u(nd,"formatPricingModel");function ad(r,e=60){return r?r.length<=e?r:`${r.slice(0,e-1)}\u2026`:""}u(ad,"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,l=qt();delete l.token;let m=new sd(l),d;try{d=await m.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){D(d);return}b({message:"No Actors found matching your search.",stdout:!0});return}if(t){D(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:ad(g.description),"Users (30d)":Ai.cyan(`${g.stats?.totalUsers30Days??0}`),Pricing:nd(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 '${L}' 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}),l={};this.flags.build&&(l.build=this.flags.build),this.flags.timeout&&(l.timeout=this.flags.timeout),this.flags.memory&&(l.memory=this.flags.memory);let m=await xt(e,this.flags.input,this.flags.inputFile);if(m===!1)return;let d=Pt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:l,type:"Actor",inputOverride:m?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let N of d)p=N;if(this.flags.json){D(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("."),E=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")})`),E&&P.push(`| ${se.gray("Actor version:")} ${se.cyan(E.versionNumber)} (${se.yellow(E.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,Dt,kt,Ao,wo,Je,po];async run(){this.printHelp()}};import ud from"chalk";import md from"computer-name";import dd from"cors";import bi from"express";import pd from"open";import{cryptoRandomObjectId as fd}from"@apify/utilities";import cd from"@inquirer/password";var ja=Oe(async({message:r,mask:e})=>await cd({message:r,mask:e??"*"}));import ld from"@inquirer/select";var Ke=Oe(async({message:r,choices:e,pageSize:t,loop:o,default:s})=>await ld({message:r,choices:e,pageSize:t,loop:o,default:s}));var vi="https://console.apify.com/settings/integrations",gd=new URL(vi).origin,hd=vi.includes("localhost")?"http://localhost:3333":void 0,Ba="v1",Si=u(async r=>{let e=await Jt(r,hd),t=await U();return e?(await Mr(t.id),$({message:`You are logged in to Apify as ${t.username||t.id}. ${ud.gray(`Your token is stored at ${fe()}.`)}`})):f({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),Lt=class extends h{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ae(fe())}'.
|
|
153
|
-
All other commands use these stored credentials.
|
|
154
|
-
|
|
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(dd({origin:gd,allowedHeaders:["Content-Type","Authorization"]})),i.use((m,d,p)=>{d.set("Connection","close"),p()}),i.use(bi.json());let n=fd();i.use((m,d,p)=>{let{token:g}=m.query;if(!g){let y=m.get("Authorization");if(y){let[v,S,...E]=y.trim().split(/\s+/);v.toLowerCase()==="bearer"&&S&&E.length===0&&(g=S)}}g!==n?(d.status(401),d.send("Authorization failed")):p()});let a=bi.Router();i.use(`/api/${Ba}`,a),a.post("/login-token",async(m,d)=>{try{if(m.body.apiToken)await Si(m.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",(m,d)=>{m.body.isWindowClosed?f({message:"Login to Apify failed, the console window was closed."}):m.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(),l=new URL(vi);l.searchParams.set("localCliCommand","login"),l.searchParams.set("localCliPort",`${c}`),l.searchParams.set("localCliToken",n),l.searchParams.set("localCliApiVersion",Ba);try{l.searchParams.set("localCliComputerName",encodeURIComponent(md()))}catch{}b({message:`Opening Apify Console at "${l.href}"...`}),await pd(l.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await ja({message:"token:"});await Si(s)}}};var Ft=class extends h{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ae(fe())}'.
|
|
156
|
-
Run 'apify login' to authenticate again.`;async run(){await Ut(fe()),await Mr(null),$({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=[Lt,Ft,Co];async run(){this.printHelp()}};import Eo from"chalk";var $o=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 ${Eo.gray(a.buildNumber)})`:"";$({message:`Tag "${Eo.yellow(t)}" added to build ${Eo.gray(s.buildNumber)} (${Eo.gray(e)})${c}`,stdout:!0})}catch(c){let l=c;f({message:`Failed to add tag "${t}" to build "${e}".
|
|
157
|
-
${l.message||l}`,stdout:!0})}}};import te from"chalk";var yd=u(r=>r,"noColor");function ee({bytes:r,shortBytes:e=!1,colorFunc:t=yd,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])}`}u(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){D(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)})`:"",l=typeof n<"u"?` (exit code: ${te.gray(n)})`:"",m=[`${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)}${l}`,` ${te.yellow("Started")}: ${Y.display(o.startedAt)}`];if(o.finishedAt)m.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();m.push(` ${te.yellow("Finished")}: ${te.gray(`Running for ${Xt.format(g)}`)}`)}o.stats?.computeUnits&&m.push(` ${te.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let d=Reflect.get(o.stats??{},"imageSizeBytes");d&&m.push(` ${te.yellow("Docker Image Size")}: ${ee({bytes:d})}`),m.push(` ${te.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),m.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;m.push(`${te.blue("View in Apify Console")}: ${p}`),R({message:m.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 wd=u(()=>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 l=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),m=await a.actor(c.id).get(),d=Fr(l.items,y=>{let v=Reflect.get(y,"buildNumber"),[S,E]=v.split(".");return`${S}.${E}`}),p=Object.entries(m.taggedBuilds??{}).reduce((y,[v,S])=>(y[S.buildNumber]=v,y),{});if(i){for(let y of l.items){let v=Reflect.get(y,"buildNumber"),S=p[v];S&&Reflect.set(y,"buildTag",S)}D(l);return}R({message:`${we.reset("Showing")} ${we.yellow(l.items.length)} out of ${we.yellow(l.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=m.versions.find(N=>N.versionNumber===y)?.buildTag,E=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}`),E.render(s?0:-1),""];R({message:P.join(`
|
|
161
|
-
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=wd();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 dr 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 "${dr.yellow(t)}" from build ${dr.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}}),$({message:`Tag "${dr.yellow(t)}" removed from build ${dr.gray(i.buildNumber)} (${dr.gray(e)})`,stdout:!0})}catch(m){let d=m;f({message:`Failed to remove tag "${t}" from build "${e}".
|
|
162
|
-
${d.message||d}`,stdout:!0})}}};import Ad from"@inquirer/input";var Va=Oe(async({message:r,expectedValue:e,failureMessage:t})=>await Ad({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?Va: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(),$({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=[$o,Po,Oo,xo,_o,Ro,_t];async run(){this.printHelp()}};var No=class extends Je{static name="call"};import bd from"assert";import{existsSync as Ga,openSync as Sd}from"fs";import{mkdir as Ya,readFile as vd,symlink as Td,unlink as Cd,writeFile as Ha}from"fs/promises";import{homedir as Id}from"os";import{dirname as Ed,join as We}from"path";import{ReadStream as $d}from"tty";import H from"chalk";import qa from"which";var Rd=u(r=>We(r,".install-marker"),"pathToInstallMarker"),Ja=u(()=>process.env.HOME??Id(),"HOMEDIR"),pr=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}bd(t,"When CLI is installed via bundles, the install path must be set");let s=Rd(t);if(Ga(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 Ha(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(`
|
|
164
|
-
`)}),R({message:""}),$({message:"To get started, run:"}),R({message:H.white.bold(` apify --help
|
|
165
|
-
actor --help`)})}async symlinkToLocalBin(e){let t=Ja();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 Ya(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=We(e,i);if(!Ga(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 Cd(a).catch(()=>{}),await Td(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=u(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=Sd("/dev/tty","r"),o=new $d(t),process.stdout.write(s),o.setRawMode(!0),o.resume(),await new Promise(a=>{let c=u(l=>{let m=l.toString();m==="y"||m==="Y"||m==="\r"||m===`
|
|
167
|
-
`?(o.removeListener("data",c),i("Yes"),a(!0)):m==="n"||m==="N"?(o.removeListener("data",c),i("No"),a(!1)):(m===""||m==="")&&(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([qa("apify",{nothrow:!0}),qa("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=Ja();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?",l;process.env.APIFY_OPEN_TTY?l=await this.confirmFromTty(c):(T("[install] opening /dev/tty for raw mode not requested, falling back to normal flow"),l=await X({message:c,providedConfirmFromStdin:!1}));let m=pn(),d=fn(o,m),p=`"${n.replaceAll('"','\\"')}"`,g=[],y=!0;switch(m){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"'),l=!1,y=!1;break}}if(R({message:""}),l&&d){let E=`${await vd(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}`)})}
|
|
169
|
-
|
|
170
|
-
# apify cli
|
|
171
|
-
${g.join(`
|
|
172
|
-
`)}
|
|
173
|
-
`;try{await Ya(Ed(d),{recursive:!0}),await Ha(d,E)}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(`
|
|
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(`
|
|
175
|
-
`)});return}b({message:[H.gray(`Manually add the following lines to ${v} or similar:`),...g.map(S=>H.white.bold(` ${S}`))].join(`
|
|
176
|
-
`)})}};import{spawn as Ld}from"child_process";import{existsSync as Fd}from"fs";import{lstat as Md,readdir as Ud,writeFile as za}from"fs/promises";import{dirname as jd,join as Ti}from"path";import Ci from"chalk";import{gte as Xa}from"semver";import{Result as _d}from"@sapphire/result";import{execa as xd}from"execa";var Pd=u(async(r,e,t)=>{let o=Ve(r);T("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=xd(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 _d.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function pe({cmd:r,args:e=[],opts:t={},overrideCommand:o}){ve({message:`${o||r} ${e.join(" ")}`});let s=await Pd(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(f({message:i.message}),i.cause)throw i.cause}}u(pe,"execWithLog");import{execSync as Ka}from"child_process";import{existsSync as Od,readFileSync as kd}from"fs";var je=W();function Nd(){return je.platform==="linux"?Od("/etc/alpine-release"):!1}u(Nd,"isInstalledOnMusl");function Dd(){return je.platform==="darwin"&&je.arch==="x64"?!Ka("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):je.platform==="linux"&&je.arch==="x64"?!kd("/proc/cpuinfo","utf-8").includes("avx2"):je.platform==="windows"?je.arch==="arm64"?!0:Ka(`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}u(Dd,"isInstalledOnBaseline");async function Wa(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=Nd(),n=Dd(),a=s.assets.filter(c=>{let[l,m,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")}}u(Wa,"useCLIVersionAssets");var Za={bundle:u((r,e)=>[`${e}`,"upgrade"],"bundle"),npm:u(r=>["npm","install","-g",`apify-cli@${r}`],"npm"),pnpm:u(r=>["pnpm","install","-g",`apify-cli@${r}`],"pnpm"),bun:u(r=>["bun","install","-g",`apify-cli@${r}`],"bun"),homebrew:u(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:u(r=>["volta","install",`apify-cli@${r}`],"volta")},Do="1.0.1",Qa="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",fr=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 Qn(!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=Za[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}
|
|
178
|
-
`].join(`
|
|
179
|
-
`);_({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!Xa(e,Do)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Do}.`});return}let t=await Wa(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(!Xa(s,Do)){f({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Do}.`});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=jd(process.execPath);T("[upgrade] bundleDirectory",a);let c=await Ud(a);if(!c.some(l=>l.startsWith("apify")||l.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=Za[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){b({message:`Would run command: ${n.join(" ")}`});return}try{await pe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{f({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){$({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${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=Ld("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(Fd(t))return;let o=W(),s=await fetch(Qa,{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: ${Qa}`,`- The status code of the response: ${s.status}`].join(`
|
|
182
|
-
`)}),process.exit(1));let i=await s.arrayBuffer();await za(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 m=await c.text();T("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:m}),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: ${m}`].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 l=await c.arrayBuffer();try{let m=await Md(a).then(d=>d.mode).catch(()=>493);await za(a,Buffer.from(l),{mode:m|448}),T(`[upgrade ${n}] wrote asset to`,a)}catch(m){T("[upgrade] failed to write asset",{error:m}),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: ${m.message}`].join(`
|
|
184
|
-
`)})}}}};import{mkdir as Jd,readdir as Kd,stat as nc}from"fs/promises";import{join as ut}from"path";import ac from"process";import{gte as Wd,minVersion as zd}from"semver";import{fetchManifest as Xd,manifestUrl as Zd}from"@apify/actor-templates";import{createWriteStream as Bd}from"fs";import{pipeline as Vd}from"stream/promises";import{Separator as tc}from"@inquirer/core";var ec=["JavaScript","TypeScript","Python"];async function Ii(r){return r?(Wt(r),r):Gd()}u(Ii,"ensureValidActorName");async function rc(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 ic(t)}u(rc,"getTemplateDefinition");async function oc(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await xr(t.localReadmeSuffixUrl),s=Bd(r,{flags:"a"});s.write(`
|
|
185
|
-
|
|
186
|
-
`),await Vd(o,s)}catch(o){_({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}u(oc,"enhanceReadmeWithLocalSuffix");function sc(r){let{actorName:e,dependenciesInstalled:t,postCreate:o,gitRepositoryInitialized:s,installCommandSuggestion:i}=r,n=`\u2705 Actor '${e}' created successfully!`;return t?n+=`
|
|
187
|
-
|
|
188
|
-
Next steps:
|
|
189
|
-
|
|
190
|
-
cd "${e}"
|
|
191
|
-
apify run`:n+=`
|
|
192
|
-
|
|
193
|
-
Next steps:
|
|
194
|
-
|
|
195
|
-
cd "${e}"
|
|
196
|
-
${i||"install dependencies with your package manager"}
|
|
197
|
-
apify run`,n+=`
|
|
198
|
-
|
|
199
|
-
\u{1F4A1} Tip: Use 'apify push' to deploy your Actor to the Apify platform
|
|
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}u(sc,"formatCreateSuccessMessage");async function ic(r){let e=await Yd();for(;;){let t=await Hd(r,e);if(t){if(await qd())return t}else return ic(r)}}u(ic,"executePrompts");async function Gd(){return await it({message:"Name of your new Actor:",validate:u(e=>{try{Wt(e)}catch(t){return t.message}return!0},"validate")})}u(Gd,"promptActorName");async function Yd(){return await Ke({message:"Choose the programming language of your new Actor:",choices:ec,loop:!1,default:ec[0]})}u(Yd,"promptProgrammingLanguage");async function Hd(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new tc,{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})}u(Hd,"promptTemplateDefinition");async function qd(){let r=[{name:"Install dependencies",value:!0},new tc,{name:"Go back",value:!1}];return await Ke({message:"Almost done! Last step is to install dependencies.",default:r[0],choices:r,loop:!1})}u(qd,"promptTemplateInstallation");var Lo=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 ${Zd} 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=Xd().catch(C=>new Error(`Could not fetch template list from server. Cause: ${C?.message}`));e=await Ii(e);let c=ac.cwd(),l=ut(c,e);for(;;){let C=await nc(l).catch(()=>null),P=C&&await Kd(l).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(),l=ut(c,e);continue}C||await Jd(l,{recursive:!0});break}let m=null;if(this.telemetryData.fromArchiveUrl=!!i,!i){let C=await rc(t,a);({archiveUrl:i,messages:m}=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 Lr({url:i,pathTo:l});let d=le(ut(l,L));await Pr(Object.assign(d||Sr,{name:e}),l),await Or(l),await co(l);let p=ut(l,"package.json"),g=ut(l,"README.md");await oc(g,a);let y=!1;o||await(await ke({cwd:l})).inspectAsync(async P=>{let N=zd(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:{Dr(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 Ji(p,{name:e});let M=["install"];if(n)switch(k.pmName){case"npm":{Wd(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 pe({cmd:k.pmPath,args:M,opts:{cwd:l},overrideCommand:k.pmName}),y=!0;break}case 1:case 2:{if(!Nr(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(l,".venv");b({message:`Python version ${k.version} detected.`}),b({message:`Creating a virtual environment in "${M}" and installing dependencies from "requirements.txt"...`}),ac.env.VIRTUAL_ENV||(await pe({cmd:k.executablePath,args:["-m","venv","--prompt",".",Yi],opts:{cwd:l}}),k=(await tr({cwd:l,force:!0})).unwrap(),P.runtime=k),await pe({cmd:k.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:l}}),await pe({cmd:k.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:l}}),y=!0;break}default:}});let v={success:!0},S=await nc(ut(c,".git")).catch(()=>null);if(!s&&!S)try{await pe({cmd:"git",args:["init"],opts:{cwd:l}})}catch(C){v={success:!1,error:C}}let E=y?null:await Cn(l);R({message:""}),$({message:sc({actorName:e,dependenciesInstalled:y,postCreate:m?.postCreate??null,gitRepositoryInitialized:!s&&!S&&v.success,installCommandSuggestion:E})}),!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 lc from"chalk";async function cc(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}u(cc,"tryToGetStorage");async function Fe(r,e){return cc(r,e,"dataset")}u(Fe,"tryToGetDataset");async function ie(r,e){return cc(r,e,"keyValueStore")}u(ie,"tryToGetKeyValueStore");var Fo=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 Fe(t,e)){f({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){D(o);return}$({message:`Dataset with ID ${lc.yellow(o.id)}${e?` (called ${lc.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as ze}from"apify-client";var uc={[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(uc),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}),l=uc[o]??"application/octet-stream";R({message:l}),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}u(Uo,"getUserPlanPricing");var mc=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 Fe(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(F=>F),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){D({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,m=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(m.toLocaleString("en-US"))} ${G.gray(this.pluralString(m,"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 F=Uo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),be=re*24*30,Se=be>1?`$${be.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
206
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${G.gray(`${Se} per month`)}`}}else v+=`
|
|
207
|
-
Storage size: ${ee({bytes:l,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
|
-
`),E=G.bold("\u2014");s.actRunId&&(a?E=G.bgBlue(a.id):E=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: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
209
|
-
`);mc.pushRow({Row1:S,Row2:N});let M=mc.render(2).split(`
|
|
210
|
-
`).map(F=>F.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(`
|
|
211
|
-
`),"",v].join(`
|
|
212
|
-
`);R({message:q,stdout:!0})}};import dc from"chalk";var pc=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){D(c);return}if(c.count===0){b({message:"You don't have any Datasets on your account",stdout:!0});return}for(let l of c.items){let m=Reflect.get(l.stats,"s3StorageBytes");pc.pushRow({"Dataset ID":l.id,Created:Y.display(l.createdAt),Items:`${l.itemCount}`,Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof m=="number"?ee({bytes:m,shortBytes:!0,colorFunc:dc.gray,precision:0}):dc.gray("N/A")})}R({message:pc.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 Fe(o,e);if(!s){f({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||$e;if(!c){f({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(m){f({message:`Failed to parse data as JSON string: ${m.message}`});return}if(Array.isArray(a)&&a.length===0){f({message:"No items were provided."});return}let l=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),$({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${l} successfully.`})}catch(m){let d=m;f({message:`Failed to push items into ${l}
|
|
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 Fe(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}),$({message:c,stdout:!0})}catch(l){let m=l;f({message:`Failed to rename dataset with ID ${Xe.yellow(n)}
|
|
214
|
-
${m.message||m}`})}}};import Ei 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 Fe(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(),$({message:`Dataset with ID ${Ei.yellow(i)}${n?` (called ${Ei.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;f({message:`Failed to delete dataset with ID ${Ei.yellow(i)}
|
|
215
|
-
${c.message||c}`})}}};var qo=class extends h{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[Fo,Mo,Bo,jo,Ho,Yo,Go];async run(){this.printHelp()}};import{existsSync as $i,mkdirSync as Qd,readFileSync as ep,writeFileSync as tp}from"fs";import{dirname as rp}from"path";import op from"cors";import sp from"detect-indent";import Ri from"express";import ip from"open";import{cryptoRandomObjectId as np}from"@apify/utilities";var gc="https://apify.github.io/input-schema-editor-react/",ap=new URL(gc).origin,fc="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 '${L}' 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(op({origin:ap,allowedHeaders:["Content-Type","Authorization"]})),s.use((d,p,g)=>{p.set("Connection","close"),g()}),s.use(Ri.json());let i=np();s.use((d,p,g)=>{let{token:y}=d.query;if(!y){let v=d.get("Authorization");if(v){let[S,E,...C]=v.trim().split(/\s+/);S.toLowerCase()==="bearer"&&E&&C.length===0&&(y=E)}}y!==i?(p.status(401),p.send("Authorization failed")):g()});let n=Ri.Router();s.use(`/api/${fc}`,n);let a=" ",c=!0;n.get("/input-schema",(d,p)=>{let g;try{g=$i(t)?ep(t,{encoding:"utf-8"}):`{}
|
|
217
|
-
`,g.length>3&&(a=sp(g).indent||a),g&&(c=g[g.length-1]===`
|
|
218
|
-
`),$i(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=rp(t);$i(v)||Qd(v,{recursive:!0}),tp(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(()=>$({message:"Done."}))}),o=s.listen(0);let{port:l}=o.address();b({message:`Listening for messages from input schema editor on port ${l}...`});let m=`${gc}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=${fc}`;b({message:`Opening input schema editor at "${m}"...`}),await ip(m)}};import Ko from"chalk";var gr=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 hc 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(`${hc.gray(o)}: ${hc.bold(t[o])}`)}}};import{basename as vp}from"path";import Oi from"process";import{appendFileSync as cp,copyFileSync as lp,createWriteStream as up,existsSync as _i,mkdirSync as mp,readFileSync as yc,rmSync as dp,writeFileSync as pp}from"fs";import{basename as fp,join as xi,relative as wc,sep as Pi}from"path";import{fileURLToPath as gp}from"url";import hp from"@root/walk";import yp from"configparser";import wp from"handlebars";import{fetchManifest as Ap,wrapperManifestUrl as bp}from"@apify/actor-templates";var Sp=[".dockerignore",".gitignore"],zo=gp(new URL("./templates/python-scrapy",import.meta.url));async function Ac(r,e,t={bindings:{}}){await hp.walk(r,async(o,s,i)=>{if(s===r)return;let n=wc(r,s),a=n.split(Pi).map(l=>{if(l.startsWith("{")&&l.endsWith("}")){l=l.replace("{","").replace("}","");let m=t.bindings[l];if(!m)throw new Error(`Binding for ${l} not found.`);return m}return l}).join(Pi),c=xi(e,a);if(i.isDirectory())return _i(c)||mp(c),Ac(s,c);n.includes(".template")?pp(xi(e,a.replace(".template","")),wp.compile(yc(s,"utf8"))(t.bindings)):_i(c)&&Sp.includes(fp(a))?cp(c,yc(s)):lp(s,c)})}u(Ac,"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((l,m)=>({name:`${l.class_name} (${l.pathname})`,value:m}))});function o(l){return`.${wc(r,l).split(Pi).slice(1).join(".").replace(".py","")}`}u(o,"translatePathToRelativeModuleName");let s={botName:kr(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 Ap(bp);b({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:l})=>l==="python-scrapy");_i(zo)&&dp(zo,{recursive:!0}),await Lr({url:n,pathTo:zo}),b({message:"Wrapping the Scrapy project..."}),await Ac(zo,r,{bindings:s});let a=new yp;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=up(xi(r,"scrapy.cfg"),{flags:"a"});await new Promise(l=>{c.on("open",m=>{c.write(`
|
|
221
|
-
`,()=>{a.write(m),l()})})}),$({message:"The Scrapy project has been wrapped successfully."})}u(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.
|
|
222
|
-
If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
|
|
223
|
-
Creates the '${L}' file and the '${tt}' directory in the current directory, but does not touch any other existing files or directories.
|
|
224
|
-
|
|
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=vp(t);if(s.type===1&&s.entrypoint?.path){let a=s.entrypoint.path,c=a.includes(".")?a.split(".").pop():a;i=kr(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 '${L}', the file already exists in the current directory.`});else{if(n.isErr()){f({message:n.unwrapErr().message}),Oi.exitCode=5;return}if(!e){let l=n.isOkAnd(m=>m.exists)?n.unwrap().config.name:null;for(;!l;)try{let m=await it({message:"Actor name:",default:i});Wt(m),l=m}catch(m){f({message:m.message})}e=l}let c={...{...Sr,...n.unwrap().config},name:e};this.flags.dockerfile&&(c.dockerfile=this.flags.dockerfile),await Pr(c,t)}await Or(t),await co(t),$({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.
|
|
226
|
-
|
|
227
|
-
It adds the following features:
|
|
228
|
-
- Automatic retry of failed requests
|
|
229
|
-
- Automatic proxy rotation
|
|
230
|
-
- Automatic user agent rotation
|
|
231
|
-
...
|
|
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 bc 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){D(o);return}$({message:`Key-value store with ID ${bc.yellow(o.id)}${e?` (called ${bc.yellow(e)})`:""} was created.`,stdout:!0})}};import Tp 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 "${Tp.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(c){let l=c;f({message:`Failed to delete record with key "${t}" from the key-value store.
|
|
233
|
-
${l.message||l}`})}}};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,l=[];for await(let d of c)l.push(d);let m=Buffer.concat(l).toString();try{let d=JSON.parse(m);R({message:JSON.stringify(d,null,2),stdout:!0})}catch{R({message:m,stdout:!0})}return}a.value.pipe(process.stdout)}};import V from"chalk";var Sc=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(F=>F),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){D({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let l=s.stats?.storageBytes||0,m=s.stats?.readCount||0,d=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,g=s.stats?.listCount||0,v=`Operations: ${[`${V.bold(m.toLocaleString("en-US"))} ${V.gray(this.pluralString(m,"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 F=Uo(i.plan);if(F){let re=F.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(l/1e9),be=re*24*30,Se=be>1?`$${be.toFixed(2)}`:`$${re.toFixed(3)}`;v+=`
|
|
234
|
-
Storage size: ${ee({bytes:l,shortBytes:!0,precision:1})} / ${V.gray(`${Se} per month`)}`}}else v+=`
|
|
235
|
-
Storage size: ${ee({bytes:l,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
|
-
`),E=V.bold("\u2014");s.actRunId&&(a?E=V.bgBlue(a.id):E=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: ${E}`,`Actor: ${C}`,`Task: ${P}`].join(`
|
|
237
|
-
`);Sc.pushRow({Row1:S,Row2:N});let M=Sc.render(2).split(`
|
|
238
|
-
`).map(F=>F.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(`
|
|
239
|
-
`),"",v].join(`
|
|
240
|
-
`);R({message:q,stdout:!0})}};var vc=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){D(a);return}for(let c of a.items)vc.pushRow({Key:c.key,Size:ee({bytes:c.size,shortBytes:!0,precision:0})});R({message:vc.render(1),stdout:!0})}};import Tc from"chalk";var Cc=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){D(c);return}if(c.count===0){b({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let l of c.items){let d=Reflect.get(l,"stats").s3StorageBytes;Cc.pushRow({"Store ID":l.id,Created:Y.display(l.createdAt),Modified:Y.display(l.modifiedAt),Name:l.name?`${a.username}/${l.name}`:"",Size:typeof d=="number"?ee({bytes:d,shortBytes:!0,colorFunc:Tc.gray,precision:0}):Tc.gray("N/A")})}R({message:Cc.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}),$({message:c,stdout:!0})}catch(l){let m=l;f({message:`Failed to rename key-value store with ID ${Ze.yellow(n)}
|
|
241
|
-
${m.message||m}`})}}};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(),$({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}),$({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let l=c;f({message:`Failed to set value with key "${t}" in the key-value store.
|
|
243
|
-
${l.message||l}`})}}};var ls=class extends h{static name="key-value-stores";static description=`Manages persistent key-value storage.
|
|
244
|
-
|
|
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 Lt{static name="login"};var ms=class extends Ft{static name="logout"};var ds=class extends kt{static name="pull"};var ps=class extends Dt{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 Ec,renameSync as Rp}from"fs";import{mkdir as gs,readFile as _p,stat as $c,writeFile as yr}from"fs/promises";import{dirname as hs,join as ys}from"path";import Be from"process";import xp from"mime";import{minVersion as Pp}from"semver";import{APIFY_ENV_VARS as ws}from"@apify/consts";import{validateInputSchema as Op,validateInputUsingValidator as Rc}from"@apify/input_schema";import{none as hr,some as Cp}from"@sapphire/result";import{execa as Ip}from"execa";var Ni=u(r=>`
|
|
246
|
-
(async () => {
|
|
247
|
-
const [nodeModule, process, path, fs] = await Promise.all([
|
|
248
|
-
import('node:module'),
|
|
249
|
-
import('node:process'),
|
|
250
|
-
import('node:path'),
|
|
251
|
-
import('node:fs/promises'),
|
|
252
|
-
]);
|
|
253
|
-
|
|
254
|
-
/* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
|
|
255
|
-
const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
|
|
256
|
-
|
|
257
|
-
const _require = nodeModule.createRequire(dirname);
|
|
258
|
-
|
|
259
|
-
try {
|
|
260
|
-
const modulePath = _require.resolve('${r}');
|
|
261
|
-
const moduleDir = path.dirname(modulePath);
|
|
262
|
-
|
|
263
|
-
const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
|
|
264
|
-
|
|
265
|
-
if (!packageJson) {
|
|
266
|
-
console.log('n/a');
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
const packageJsonObj = JSON.parse(packageJson);
|
|
271
|
-
console.log(packageJsonObj.version);
|
|
272
|
-
} catch {
|
|
273
|
-
console.log('n/a');
|
|
274
|
-
}
|
|
275
|
-
})();
|
|
276
|
-
`.replaceAll(`
|
|
277
|
-
`," ").replaceAll(" "," "),"jsScript"),Ep=u(r=>`
|
|
278
|
-
try:
|
|
279
|
-
import ${r}
|
|
280
|
-
print(${r}.__version__)
|
|
281
|
-
except:
|
|
282
|
-
print('n/a')
|
|
283
|
-
`,"pyScript"),$p={node(r){return["-e",`"${Ni(r)}"`]},deno(r){return["eval",`"${Ni(r)}"`]},bun(r){return["--eval",`"${Ni(r)}"`]},python(r){return["-c",`"${Ep(r)}"`]}};async function Ic({moduleName:r,project:e}){if(!e.runtime)return T("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),hr;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}),hr;let o=$p[t]?.(r);if(!o)return T("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),hr;try{let s=await Ip(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}),hr):(T("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),Cp(s.stdout.trim()))}catch(s){return T("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),hr}}u(Ic,"useModuleVersion");var As=class extends h{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
|
|
284
|
-
Stores data in local '${tt}' directory.
|
|
285
|
-
|
|
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.",`
|
|
287
|
-
`,"For Python, it is the module name, or a path to a file.",`
|
|
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=he(),c=await ke({cwd:e});if(c.isErr()){f({message:c.unwrapErr().message}),Be.exitCode=5;return}let l=c.unwrap(),{type:m,entrypoint:d,runtime:p}=l;if(l.warnings?.length)for(let k of l.warnings)_({message:k});if(m===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(m){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 $c(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=m!==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}Ec(Bs)&&!Ec(a)&&(Rp(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 Ic({moduleName:"crawlee",project:l}),S="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(S="1",v.isNone()&&(await Promise.all([an(),ln(),cn()]),b({message:"All default local stores were purged."}))),this.flags.purge||!await un()&&!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 E=await xt(e,this.flags.input,this.flags.inputFile);if(E===!1)return;let C=await this.validateAndStoreInput(E),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=La(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(m){case 0:{let k=Pp(Te);if(Dr(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 pe({cmd:p.executablePath,args:[y],opts:{env:N,cwd:e}});else{let M=await _p(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 pe({cmd:p.pmPath,args:["run",y],opts:{env:N,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!Nr(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 pe({cmd:p.executablePath,args:["-m",y],opts:{env:N,cwd:e}}):await pe({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 $c(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 yr(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 l=Kt(Be.cwd()),m=ys(Be.cwd(),ge(),l?.fileName??"INPUT.json");return await gs(hs(m),{recursive:!0}),await yr(m,JSON.stringify(e.input,null,2)),{existingInput:l,inputFilePath:m,writtenAt:Date.now()}}let o=new Ht({strict:!1,unicodeRegExp:!1});Op(o,t);let s=fa(t),i=ga(t,o),n=Kt(Be.cwd()),a=ys(Be.cwd(),ge(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
|
|
290
|
-
`;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
|
|
291
|
-
`;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
|
|
292
|
-
`:c=`The input in your storage is invalid. Please fix the following errors:
|
|
293
|
-
`;break}if(e){let l={...s,...e.input},m=Rc(i,t,l);if(m.length>0)throw new Error(`${c}${m.map(d=>` - ${d.message.replace("Field input.","Field ")}`).join(`
|
|
294
|
-
`)}`);return await gs(hs(a),{recursive:!0}),await yr(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await gs(hs(a),{recursive:!0}),await yr(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(xp.getExtension(n.contentType)==="json"){let l=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(l))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let m={...s,...l},d=Rc(i,t,m);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 yr(a,JSON.stringify(m,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as bs}from"@apify/consts";var kp=[bs.READY,bs.RUNNING],Np=[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(!kp.includes(o.status)){Np.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){D(s);return}this.flags.force?$({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):$({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;f({message:`Failed to abort run "${e}".
|
|
296
|
-
${i.message||i}`,stdout:!0})}}};import x from"chalk";var wr=new B({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),_c={"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){D({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let l=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",m=[`${x.yellow("Actor")}: ${l} (${x.grey(o.actId)})`];n?m.push(`\u2514\u2500 ${x.yellow("Task")}: ${n.title??n.name} (${x.gray(o.actorTaskId)})`,""):o.actorTaskId?m.push(`\u2514\u2500 ${x.yellow("Task")}: unknown-task (${x.gray(o.actorTaskId)})`,""):m.push("");let d=` (exit code: ${x.gray(o.exitCode!==null?o.exitCode:"N/A")})`;m.push(`${x.yellow("Status")}: ${xe(o.status)}${d}`),o.statusMessage&&m.push(`\u2514\u2500 ${x.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;m.push(`${x.yellow("Results")}: ${x.cyan(p.toLocaleString("en-US"))}`),c?m.push(`${x.yellow("Requests")}: ${x.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${x.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):m.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?m.push(`${x.yellow("Usage")}: ${x.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):m.push(`${x.yellow("Usage")}: $${x.gray("0.000")}${g}`),this.flags.verbose&&m.push(wr.render(0)),m.push(""),m.push(`${x.yellow("Started")}: ${Y.display(o.startedAt)}`),o.finishedAt)m.push(`${x.yellow("Finished")}: ${Y.display(o.finishedAt)} (took ${x.gray(ue.format(o.stats.durationMillis))})`);else{let E=Date.now()-o.startedAt.getTime();m.push(`${x.yellow("Finished")}: ${x.gray(`Running for ${ue.format(E)}`)}`)}if(m.push(""),o.stats.resurrectCount?m.push(`${x.yellow("Resurrected")}: Yes, ${x.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):m.push(`${x.yellow("Resurrected")}: No`),o.containerUrl&&m.push(`${x.yellow("Container URL")}: ${x.blue(o.containerUrl)}`),m.push(`${x.yellow("Origin")}: ${o.meta.origin}`),s){let E=o.buildNumber.split(".").slice(0,2).join("."),C=s.versions.find(k=>k.versionNumber===E),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)})`),m.push(N.join(" "))}else m.push(`${x.yellow("Build")}: ${x.cyan(o.buildNumber)}`);m.push(`${x.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),m.push(`${x.yellow("Memory")}: ${o.options.memoryMbytes} MB`),m.push(""),m.push(`${x.yellow("CPU")}: ${x.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${x.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),m.push(`${x.yellow("Memory")}: ${x.gray("Average:")} ${ee({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${x.gray("Maximum:")} ${ee({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),m.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}`;m.push(`${x.blue("Export results")}: ${v}`),m.push(`${x.blue("View saved items")}: ${S}`),m.push(`${x.blue("View in Apify Console")}: ${y}`),R({message:m.join(`
|
|
297
|
-
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(_c))wr.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(_c)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{wr.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":{wr.pushRow({"":s,Unit:ee({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:wr.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 xc=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 l=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){D(l);return}if(!l.items.length){R({message:"There are no recent runs found for this Actor."});return}let m=[`${Ae.reset("Showing")} ${Ae.yellow(l.items.length)} out of ${Ae.yellow(l.total)} runs for Actor ${Ae.yellow(c.userFriendlyId)} (${Ae.gray(c.id)})`],d=new Map(await Promise.all(l.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 l.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:""})}`)}xc.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"})}m.push(xc.render(s?0:1)),R({message:m.join(`
|
|
299
|
-
`),stdout:!0})}};import{ACTOR_JOB_STATUSES as Is}from"@apify/consts";var Dp=[Is.SUCCEEDED,Is.FAILED,Is.ABORTED,Is.TIMED_OUT],Es=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(!Dp.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){D(s);return}$({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 $s}from"@apify/consts";var Lp=[$s.SUCCEEDED,$s.FAILED,$s.ABORTED,$s.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(!Lp.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(),$({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,Es,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;ka(e,t)}};import Fp from"chalk";var Pc=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){D({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)Pc.pushRow({"Secret Name":Fp.cyan(s)});R({message:Pc.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;Na(e)}};var ks=class extends h{static name="secrets";static description=`Manages secure environment variables for Actors.
|
|
302
|
-
|
|
303
|
-
Example:
|
|
304
|
-
$ apify secrets add mySecret TopSecretValue123
|
|
305
|
-
|
|
306
|
-
The "mySecret" value can be used in an environment variable defined in '${L}' file by adding the "@" prefix:
|
|
307
|
-
|
|
308
|
-
{
|
|
309
|
-
"actorSpecification": 1,
|
|
310
|
-
"name": "my_actor",
|
|
311
|
-
"environmentVariables": { "SECRET_ENV_VAR": "@mySecret" },
|
|
312
|
-
"version": "0.1"
|
|
313
|
-
}
|
|
314
|
-
|
|
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 Oc from"chalk";var Ns=class extends h{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
316
|
-
Customize with --memory and --timeout flags.
|
|
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,l,m=Pt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let d of m)c=`https://console.apify.com/actors/${d.actId}/runs/${d.id}`,l=`https://console.apify.com/storage/datasets/${d.defaultDatasetId}`;R({message:["",`${Oc.blue("Export results")}: ${l}`,`${Oc.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 Ds=class extends h{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[Ns];async run(){this.printHelp()}};var Ls=class extends h{static name="disable";static description="Disables telemetry.";async run(){(await me()).enabled?(await Ur(!1),$({message:"Telemetry disabled."})):b({message:"Telemetry is already disabled."})}};var Fs=class extends h{static name="enable";static description="Enables telemetry.";async run(){(await me()).enabled?b({message:"Telemetry is already enabled."}):(await Ur(!0),$({message:"Telemetry enabled."}))}};var Ar=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=[Fs,Ls];async run(){this.printHelp()}};import Mp 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):
|
|
320
|
-
1. Object in '${L}' under "input" key
|
|
321
|
-
2. JSON file path in '${L}' "input" key
|
|
322
|
-
3. .actor/INPUT_SCHEMA.json
|
|
323
|
-
4. INPUT_SCHEMA.json
|
|
324
|
-
|
|
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:Mp.cwd(),getMessage:u(e=>e?`Validating input schema at ${e}`:`Validating input schema embedded in '${L}'`,"getMessage")}),$({message:"Input schema is valid."})}};var Ik=[mo,To,Io,ko,qo,ls,fs,_s,ks,Ds,Ar,No,fr,pr,Lo,Jo,Wo,Qo,Zo,us,ms,ds,ps,As,Ms,gr],Ek=[Rt,$t,Et,It,Ct,wt,yt,Tt,gr,fr,pr,Ar];export{cw as a,lw as b,Ik as c,Ek as d};
|
|
326
|
-
//# sourceMappingURL=chunk-D7HO3WVQ.js.map
|