apify-cli 0.21.10-beta.15 → 0.21.10-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,240 +0,0 @@
1
- var Na=Object.defineProperty;var u=(r,e)=>Na(r,"name",{value:e,configurable:!0});import Se from"process";import{parseArgs as Vi}from"util";import vr from"chalk";import{satisfies as Xc}from"semver";import fs from"chalk";import _c from"indent-string";import Rc from"widest-line";import Oc from"wrap-ansi";import ct from"chalk";function We(r){r.stdoutOutput&&console.log(...r.stdoutOutput),r.stderrOutput&&console.error(...r.stderrOutput)}u(We,"internalLog");function R(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[r.message]})}u(R,"simpleLog");function p(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.red("Error:"),r.message]})}u(p,"error");function O(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.yellow.bold("Warning:"),r.message]})}u(O,"warning");function _(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.green("Success:"),r.message]})}u(_,"success");function ge(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.gray("Run:"),r.message]})}u(ge,"run");function v(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.white("Info:"),r.message]})}u(v,"info");function zs(r){We({[r.stdout?"stdoutOutput":"stderrOutput"]:[ct.blue(r.message),r.url]})}u(zs,"link");import Y from"chalk";import{realpathSync as Pa}from"fs";import{dirname as La}from"path";var Xs="0.0.0";var Da="0.21.10-beta.15",Fa="c29140ccf53be47f6f06dac82edcdf01b9a0c812";function ka(){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 O({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=Pa(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(ka,"detectInstallMethod");function Ua(){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(Ua,"getRuntimeInfo");var Et=null;function X(){if(Et)return Et;let r=ka(),e=Ua();return Et={version:Da,hash:Fa,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform==="win32"?"windows":process.platform,runtime:e.runtime,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}-${e.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:""}, installed via ${this.installMethod}`}},r==="bundle"&&(Et.installPath=La(process.execPath)),Et}u(X,"useCLIMetadata");import Ut from"chalk";import Oi from"indent-string";import xi from"widest-line";import Ni from"wrap-ansi";import{createWriteStream as Xa,existsSync as ce,mkdirSync as Za,readdirSync as li,readFileSync as xt,writeFileSync as ir}from"fs";import{mkdir as Qa,readFile as ec}from"fs/promises";import{get as tc}from"https";import{dirname as ui,join as ye}from"path";import ae from"process";import{finished as rc}from"stream/promises";import{DurationFormatter as di,TimeTypes as Qe}from"@sapphire/duration";import{Timestamp as is}from"@sapphire/timestamp";import oc from"adm-zip";import sc from"ajv/dist/2019.js";import{ApifyClient as mi}from"apify-client";import ic from"archiver";import{AxiosHeaders as nc}from"axios";import ac from"escape-string-regexp";import{globby as pi}from"globby";import{getEncoding as cc}from"istextorbinary";import{Mime as lc}from"mime";import uc from"mime/types/other.js";import dc from"mime/types/standard.js";import{gte as mc,minVersion as pc,satisfies as fc}from"semver";import{ACTOR_ENV_VARS as ns,ACTOR_JOB_TERMINAL_STATUSES as gc,ACTOR_NAME as Ot,APIFY_ENV_VARS as hc,KEY_VALUE_STORE_KEYS as ci,LOCAL_ACTOR_ENV_VARS as as,LOCAL_STORAGE_SUBDIRS as cs,SOURCE_FILE_FORMATS as Rt}from"@apify/consts";import{homedir as ja}from"os";import{join as ze}from"path";import{KEY_VALUE_STORE_KEYS as Ba,META_ORIGINS as Va}from"@apify/consts";var Zs={name:"apify-cli",version:"0.21.10-beta.15",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '\\[api\\]'","test:python":"vitest run --testNamePattern '\\[python\\]'","test:cucumber":'cross-env NODE_OPTIONS="--import tsx" cucumber-js',lint:"eslint src test scripts features --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts features --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=18"},dependencies:{"@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.15.1","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^10.1.15","@inquirer/input":"^4.2.1","@inquirer/password":"^4.0.17","@inquirer/select":"^4.3.1","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.17.1","apify-client":"^2.12.6",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.5.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.1.0",globby:"~14.1.0",handlebars:"~4.7.8","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","lodash.clonedeep":"^4.5.0",mime:"~4.0.4",mixpanel:"~0.18.0",open:"~10.2.0",ow:"~2.0.0",rimraf:"~6.0.1",semver:"~7.7.0","string-width":"^7.2.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",which:"^5.0.0","widest-line":"^5.0.0","wrap-ansi":"^9.0.0"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@cucumber/cucumber":"^12.0.0","@types/adm-zip":"^0.5.5","@types/archiver":"^6.0.2","@types/bun":"^1.2.5","@types/chai":"^4.3.17","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11","@types/is-ci":"^3.0.4","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/lodash.clonedeep":"^4","@types/mime":"^4.0.0","@types/node":"^22.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@yarnpkg/core":"^4.1.2",apify:"^3.2.4",chai:"^4.4.1","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","lint-staged":"^16.0.0","mdast-util-from-markdown":"^2.0.2","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^5.8.3","typescript-eslint":"^8.31.0",vitest:"^3.0.0"},volta:{node:"22.18.0",yarn:"4.9.2"},packageManager:"yarn@4.9.2",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"}};var Xe="storage",ts="apify_storage",rs=1,er={actorSpecification:rs,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},Qs={SCRAPY:"scrapy",CRAWLEE:"crawlee",PRE_CRAWLEE_APIFY_SDK:"apify",UNKNOWN:"unknown"},ei=1440*60*1e3,lt=u(()=>{let r=ze(ja(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?ze(r,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):r},"GLOBAL_CONFIGS_FOLDER"),ne=u(()=>ze(lt(),"auth.json"),"AUTH_FILE_PATH"),tr=u(()=>ze(lt(),"secrets.json"),"SECRETS_FILE_PATH"),rr=u(()=>ze(lt(),"state.json"),"STATE_FILE_PATH"),De=u(()=>ze(lt(),"telemetry.json"),"TELEMETRY_FILE_PATH"),or="apify.json",os=".actor",Ya="actor.json",j=ze(os,Ya),ss=new RegExp(`^${Ba.INPUT}\\..*`),he=Zs.engines.node,ti={"X-Apify-Request-Origin":Va.CLI},Ze="3.9.0",ri=".venv",oi="ea75e434d4b4d2405d79ed9d14bfc93b";import{existsSync as Ga,mkdirSync as Ha}from"fs";import{readFile as Ja,stat as si,unlink as Ka,writeFile as qa}from"fs/promises";import{join as ii,sep as Wa}from"path";import{rimraf as za}from"rimraf";var ni=u(async(r,e={},t=null)=>{let o=await Ja(r,"utf-8"),s=JSON.parse(o),i;t?(i=s,i[t]={...s[t],...e}):i={...s,...e},await qa(r,JSON.stringify(i,null," "))},"updateLocalJson"),sr=u((r,e)=>{e||(e=r,r="."),e.split(Wa).reduce((o,s)=>(o=ii(o,s),Ga(o)||Ha(o),o),r)},"ensureFolderExistsSync"),$t=u(async r=>{await za(r)},"rimrafPromised"),_t=u(async r=>{(await si(r)).isFile()&&await Ka(r)},"deleteFile"),ai=u(async(r,e)=>(await Promise.all(r.map(async s=>si(ii(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var ut=sc,nr=u(async r=>new Promise((e,t)=>{tc(r,o=>{o.statusCode===301||o.statusCode===302?(e(nr(o.headers.location)),o.destroy()):e(o)}).on("error",t)}),"httpsGet"),le=u(()=>{let r=hc.LOCAL_STORAGE_DIR;return ae.env[r]||ae.env.CRAWLEE_STORAGE_DIR||Xe},"getLocalStorageDir"),Te=u(r=>{let e=ns.DEFAULT_KEY_VALUE_STORE_ID,t=r||ae.env[e]||as[e];return ye(le(),cs.keyValueStores,t)},"getLocalKeyValueStorePath"),fi=u(r=>{let e=ns.DEFAULT_DATASET_ID,t=r||ae.env[e]||as[e];return ye(le(),cs.datasets,t)},"getLocalDatasetPath"),gi=u(r=>{let e=ns.DEFAULT_REQUEST_QUEUE_ID,t=r||ae.env[e]||as[e];return ye(le(),cs.requestQueues,t)},"getLocalRequestQueuePath"),F=u(async()=>{let r={};try{let e=await ec(ne(),"utf-8");r=JSON.parse(e)}catch{return{}}if(!r.username&&!r.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return r},"getLocalUserInfo");async function C(){let r=await Nt();if(!r)throw new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return r}u(C,"getLoggedClientOrThrow");var hi=u(r=>{if(!r&&ce(lt())&&ce(ne())){let e=xt(ne(),"utf-8");return JSON.parse(e).token}return r},"getTokenWithAuthFileFallback"),ls=u((r,e)=>(r=hi(r),{token:r,baseUrl:e||ae.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[t=>{t.headers??=new nc;for(let[o,s]of Object.entries(ti))t.headers[o]=s;return t}]}),"getApifyClientOptions");async function Nt(r,e){r=hi(r);let t=new mi(ls(r,e)),o;try{o=await t.user("me").get()}catch{return null}return et(ne()),ir(ne(),JSON.stringify({token:t.token,...o},null," ")),t}u(Nt,"getLoggedClient");var us=u(r=>ye(r,j),"getLocalConfigPath"),Ce=u(r=>{if(ce(r))return JSON.parse(xt(r,{encoding:"utf-8"}))},"getJsonFileContent"),Fe=u(r=>Ce(us(r)),"getLocalConfig"),ar=u(async(r,e)=>{let t=ye(e||ae.cwd(),j);await Qa(ui(t),{recursive:!0}),ir(t,JSON.stringify(r,null," "))},"setLocalConfig"),yc=[le(),"node_modules",".venv"],cr=u(async r=>{let e=Te();sr(r,fi()),sr(r,gi()),sr(r,e);let t=ye(r,".gitignore"),o="";ce(t)&&(o=xt(t,{encoding:"utf-8"}));let s=[];for(let i of yc)RegExp(`^${ac(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),ir(t,`
2
- ${s.join(`
3
- `)}
4
- `,{flag:"a"})):ir(t,`${s.join(`
5
- `)}
6
- `,{flag:"w"}))},"setLocalEnv"),yi=new lc(dc,uc).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),wc=u((r,e)=>{let t=yi.getType(r);return t?t.startsWith("text/")||t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("application/node")||t.includes("application/toml")||t.includes("application/x-sh")||t.includes("application/x-httpd-php")?Rt.TEXT:Rt.BASE64:cc(e)==="binary"?Rt.BASE64:Rt.TEXT},"getSourceFileFormat"),wi=u(async(r,e)=>r.map(t=>{let o=xt(ye(e,t)),s=wc(t,o);return{name:t,format:s,content:s===Rt.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),Ai=u(async r=>pi(["*","**/**"],{ignore:[".git/**","apify_storage","node_modules","storage","crawlee_storage"],gitignore:!0,dot:!0,cwd:r}),"getActorLocalFilePaths"),bi=u(async(r,e,t)=>{ce(r)&&await _t(r);let o=Xa(r),s=ic("zip");s.pipe(o),e.forEach(i=>s.glob(i,{cwd:t})),await s.finalize()},"createActZip"),Pt=u(r=>{let e=Te();if(!ce(ye(r,e)))return;let s=li(ye(r,e)).find(a=>!!a.match(ss));if(!s)return;let i=xt(ye(r,e,s)),n=yi.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),Si=u(async()=>{let r=gi();ce(le())&&ce(r)&&await $t(r)},"purgeDefaultQueue"),vi=u(async()=>{let r=fi();ce(le())&&ce(r)&&await $t(r)},"purgeDefaultDataset"),Ti=u(async()=>{let r=Te();if(!ce(le())||!ce(r))return;let e=li(r),t=[];e.forEach(o=>{o.match(ss)||t.push(_t(ye(r,o)))}),await Promise.all(t)},"purgeDefaultKeyValueStore"),Ie=u(async({job:r,timeoutMillis:e,apifyClient:t})=>{let{id:o,status:s}=r,i=t||new mi({baseUrl:ae.env.APIFY_CLIENT_BASE_URL});if(gc.includes(s)){if(ae.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();ae.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let c=null;a.on("data",d=>{ae.env.APIFY_NO_LOGS_IN_TESTS||ae.stderr.write(d.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var Ci=u(async()=>(await pi([`${le()}/**`,`!${Te()}/${ci.INPUT}.*`,`!${Te()}/${ci.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Lt=u(r=>{if(!Ot.REGEX.test(r))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(r.length<Ot.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(r.length>Ot.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),Ii=u(r=>{let e=r.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<Ot.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,Ot.MAX_LENGTH)},"sanitizeActorName"),lr=u(r=>fc(r,`^${Ze}`),"isPythonVersionSupported"),ur=u(r=>{let e=pc(he);return mc(r,e)},"isNodeVersionSupported"),dr=u(async({url:r,pathTo:e})=>{let t=await nr(r),o=[];t.on("data",i=>o.push(i)),await rc(t),new oc(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function et(r){let e=ui(r);Za(e,{recursive:!0})}u(et,"ensureApifyDirectory");var B=new is("YYYY-MM-DD [at] HH:mm:ss"),Dt=new is(`YYYY-MM-DD[
7
- ]HH:mm:ss`),Ei=new is("YYYY-MM-DD"),Ft=new di,se=new di({[Qe.Day]:{DEFAULT:"d"},[Qe.Hour]:{DEFAULT:"h"},[Qe.Minute]:{DEFAULT:"m"},[Qe.Month]:{DEFAULT:"M"},[Qe.Second]:{DEFAULT:"s"},[Qe.Week]:{DEFAULT:"w"},[Qe.Year]:{DEFAULT:"y"}});function mr(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(mr,"objectGroupBy");function $i(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($i,"mapGroupBy");function N(r){console.log(JSON.stringify(r,null,2))}u(N,"printJsonToStdout");import pr from"chalk";import ds from"indent-string";import vc from"string-width";import Tc from"strip-ansi";import Ri from"widest-line";import ms from"wrap-ansi";import Ac from"chalk";import bc from"indent-string";import _i from"string-width";import Sc from"wrap-ansi";var ke;function oe(){if(ke)return ke;let r=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(r))ke=r;else if(!process.stdout.isTTY)ke=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?ke=80:e<40?ke=40:ke=e}return ke}u(oe,"getMaxLineWidth");var dt=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(`
8
- `)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(Ac.bold("DESCRIPTION"));let t=Sc(this.command.description,oe()-2,{trim:!1}),o=bc(t,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:o}){let s=_i(e.join(" ").split(`
9
- `).at(-1)||"")+o,i=_i(t);s+i>oe()&&e.push(`
10
- `),e.push(t)}kebabFlagName(e){return we(Ae(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 fr=class extends dt{static{u(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
11
- `).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(`
12
- `).trim()}pushUsageString(e){e.push(pr.bold("USAGE"));let t=`$ ${this.entrypoint} ${this.command.name}`,o=2+vc(t),s=[t],i=Object.entries(this.command.args??{});if(i.length)for(let[f,m]of i){if(typeof m=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:m.required?`<${f}>`:`[${f}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,f])=>{if(typeof f=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!f.hidden});this.command.enableJsonFlag&&n.push(["json",{choices:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((f,m)=>{if(typeof f[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof m[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return f[1].required&&!m[1].required?-1:!f[1].required&&m[1].required?1:f[0].localeCompare(m[0])})),c=new Set;if(n.length)for(let[f,m]of a){if(typeof m=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(c.has(f))continue;let g=m.required,b=[this.makeFlagString(f,m)];if(m.exclusive?.length)for(let T of m.exclusive){c.add(T);let S=a.get(T),I=this.makeFlagString(T,S);b.push(I),S.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?b.join(" | "):`[${b.join(" | ")}]`,indentSize:o})}let d=ms(s.join(" "),oe()-o),l=ds(d,o+1).trim();e.push(` ${l}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,t){if(!t.length)return;e.push(pr.bold("ARGUMENTS"));let o=Ri(t.map(([s])=>s).join(`
13
- `));for(let[s,i]of t){let n=`${s.padEnd(o)} ${i.description}`,a=ms(n,oe()-o-2),c=ds(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,t){if(!t.size)return;e.push(pr.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)}=${pr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=Ri([...o.keys()].join(`
14
- `));for(let[i,n]of o){let a=s-Tc(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choices?.length&&(c+=`
15
- <options: ${n.choices.join("|")}>`);let d=ms(c,oe()-s),l=ds(d,s).trim().split(`
16
- `).map(f=>/^-[a-z]/.test(f.trim())?f:` ${f}`).join(`
17
- `);e.push(` ${l}`)}e.push("")}};import Cc from"chalk";import Ic from"indent-string";import Ec from"widest-line";import $c from"wrap-ansi";var kt=class extends dt{static{u(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
18
- `).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(`
19
- `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(Cc.bold("SUBCOMMANDS"));let t=Ec(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
20
- `));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
21
- `)[0]||"",i=`${this.command.name} ${o.name.padEnd(t-this.command.name.length-1)} ${s}`,n=$c(i,oe()-t-2),a=Ic(n,t+2+2).trim();e.push(` ${a}`)}e.push("")}};var Mt=new Map;function ps(r,e){if(e.name.toLowerCase()!==e.name){p({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){Mt.set(e,new kt(r,e));for(let t of e.subcommands)ps(`${r} ${e.name}`,t)}else Mt.set(e,new fr(r,e))}u(ps,"registerCommandForHelpGeneration");function gr(r){let e=Mt.get(r);if(!e)throw new Error(`No help renderer found for command ${r.name}`);return e.render()}u(gr,"renderHelpForCommand");function hr(r,e){let t=Mt.get(r);if(!t)throw new Error(`No help renderer found for command ${r.name}`);return t.selectiveRender(e)}u(hr,"selectiveRenderHelpForCommand");function Pi(r,e){return r[0].name.localeCompare(e[0].name)}u(Pi,"sortByName");function yr(r){let e=X(),t=[];t.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),t.push(Ut.bold("VERSION")),t.push(` ${e.fullVersionString}`),t.push(""),t.push(Ut.bold("USAGE")),t.push(` $ ${r} <command> [options]`),t.push("");let o=$i(Mt,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof kt?"subcommand":"command"),s=o.get("subcommand")?.sort(Pi),i=o.get("command")?.sort(Pi);if(s?.length){t.push(Ut.bold("TOPICS"));let n=[],a=xi(s.map(([c])=>c.name).join(`
22
- `));for(let[c]of s){if(c.hidden)continue;let d=c.shortDescription||c.description?.split(`
23
- `)[0]||"",l=`${c.name.padEnd(a)} ${d}`,f=Ni(l,oe()-a-2);n.push(` ${Oi(f,a+2+2).trim()}`)}t.push(...n,"")}if(i?.length){t.push(Ut.bold("COMMANDS"));let n=[],a=xi(i.map(([c])=>c.name).join(`
24
- `));for(let[c]of i){if(c.hidden)continue;let d=c.shortDescription||c.description?.split(`
25
- `)[0]||"",l=`${c.name.padEnd(a)} ${d}`,f=Ni(l,oe()-a-2);n.push(` ${Oi(f,a+2+2).trim()}`)}t.push(...n,"")}return t.push(Ut.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(`
26
- `).trim()}u(yr,"renderMainHelpMenu");var wr=(l=>(l[l.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]="NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE",l[l.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]="NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL",l[l.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]="NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION",l[l.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]="APIFY_FLAG_PROVIDED_MULTIPLE_TIMES",l[l.APIFY_INVALID_FLAG_INTEGER_VALUE=4]="APIFY_INVALID_FLAG_INTEGER_VALUE",l[l.APIFY_INVALID_CHOICE=5]="APIFY_INVALID_CHOICE",l[l.APIFY_MISSING_FLAG=6]="APIFY_MISSING_FLAG",l[l.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]="APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG",l[l.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]="APIFY_TOO_MANY_REQUESTERS_OF_STDIN",l[l.APIFY_UNKNOWN_ERROR=9]="APIFY_UNKNOWN_ERROR",l))(wr||{}),ie=class r extends Error{static{u(this,"CommandError")}code;command;metadata;constructor({code:e,message:t="",metadata:o={},command:s}){super(t||String(wr[e])),this.code=e,this.metadata=o,this.command=s}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
27
-
28
- Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '--(?<optionName>[a-zA-Z0-9]+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw new Error(`Encountered unparsable error message from argument parser: ${this.message}.
29
-
30
- Please report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion}}default:throw new Error("Not implemented")}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return r.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),t=hr(this.command,{showUsageString:!0});return[Y.gray(`Unknown flag provided: ${Y.white.bold(`--${e.name}`)}`),e.unknownOptionSuggestion?Y.gray(` ${e.unknownOptionSuggestion.trim()}`):null,"",t].filter(o=>o!==null).join(`
31
- `)}case 3:{let e=`--${this.metadata.flag}`;return Y.gray(`Flag ${Y.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,t=Y.whiteBright(String(this.metadata.value));return Y.gray(`The provided value for the '${Y.white.bold(e)}' flag could not be processed as an integer. Received: ${t}.`)}case 6:{let{flag:e,matcher:t,providedButReceivedNoValue:o}=this.metadata,s=`'${Y.white.bold(`--${e}`)}'`;return t&&(s=`${s} (alias used: '${Y.white.bold(`--${t}`)}')`),o?Y.gray(`Flag ${s} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):Y.gray(`Flag ${s} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,t=[Y.gray("The following errors occurred:")],o=Y.red(" > ");for(let[s,i]of e)t.push(Y.gray(`${o}${Y.white.bold(s)} cannot also be provided when using ${Y.white.bold(i)}`));return t.push(Y.gray(`${o}See more help with ${Y.white.bold("--help")}`)),t.join(`
32
- `)}case 8:{let{firstUse:e,secondUse:t}=this.metadata;return Y.gray(`Flag ${Y.white.bold(`--${e}`)} and ${Y.white.bold(`--${t}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=X();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} (${wr[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,"",`- Stack:
33
- ${this.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(process.argv.slice(2))}`,"",`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${be?"Yes":"No"}`].join(`
34
- `)}}}static buildMessageFromFlagData(e){let t=[`Flag ${Y.white.bold(`--${e.name}`)}`];return e.ambiguousFlag?(t.push("is ambiguous (meaning the provided value could be interpreted as a flag too)."),e.ambiguousMessage?t.push(`
35
- ${e.ambiguousMessage.split(`
36
- `).map(o=>` ${o}`).join(`
37
- `)}`):t.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?t.push("expects a value"):t.push("does not take an argument"),t.map(o=>Y.gray(o)).join(" ")}static into(e,t){if(e instanceof r)return e;if(e instanceof Error&&"code"in e){let o=e;switch(o.code){case"ERR_PARSE_ARGS_INVALID_OPTION_VALUE":return new r({code:0,message:o.message,command:t});case"ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL":return new r({code:1,message:o.message,command:t});case"ERR_PARSE_ARGS_UNKNOWN_OPTION":return new r({code:2,message:o.message,command:t});default:return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new r({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function Li(r){return r.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}u(Li,"camelCaseString");function we(r){return r.replace(/[\s_]+/g,"-")}u(we,"kebabCaseString");function Ae(r){return r.replace(/([A-Z])/g,"-$1").toLowerCase()}u(Ae,"camelCaseToKebabCase");var xc={type:"boolean",multiple:!1,short:"h"},Nc={type:"boolean",multiple:!1},q=new Map,y=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;constructor(e){this.entrypoint=e}get ctor(){return this.constructor}pluralString(e,t,o){return e===1?t:o}static printHelp(){console.log(gr(this)),process.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(e){let{values:t,positionals:o,tokens:s}=e;t.help&&this.ctor.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof t.json=="boolean"?this.flags.json=t.json:this.flags.json=!1);let i=new Map;if(this.ctor.args){let n=0;for(let[a,c]of Object.entries(this.ctor.args)){if(typeof c=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let d=Li(a),l=o[n++];if(l)switch(c.argTag){case"string":default:this.args[d]=String(l),l==="-"&&c.stdin&&(this.args[d]=this._handleStdin(c.stdin)),c.catchAll&&(this.args[d]=o.slice(n-1).join(" "));break}else c.required&&i.set(a,c)}}if(i.size){this._printMissingRequiredArgs(i);return}this._parseFlags(t,s);try{await this.run()}catch(n){p({message:n.message})}finally{}}_userFlagNameToRegisteredName(e,t){let o=we(Ae(e)).toLowerCase(),s=o;o.startsWith("no-")&&(s=o.slice(3));let i=new Set;for(let n of t.aliases??[])i.add(we(Ae(n)).toLowerCase());return{baseFlagName:s,rawBaseFlagName:o,allMatchers:[s,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=we(Ae(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:d,rawBaseFlagName:l}=this._userFlagNameToRegisteredName(n,a),f=Li(l),m=t.some(b=>b.kind==="option"&&b.name===d);if(a.exclusive?.length){let b=o.get(d)??new Set;for(let T of a.exclusive)b.add(this._commandFlagKeyToKebabCaseRegisteredName(T));o.set(d,b);for(let T of a.exclusive){let S=this._commandFlagKeyToKebabCaseRegisteredName(T),I=o.get(S)??new Set;I.add(d),o.set(S,I)}}let g=c.filter(b=>e[b]);if(g.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:d}});let h=e[g[0]];if(!h&&a.required)throw new ie({code:6,command:this.ctor,metadata:{flag:d,matcher:g[0]}});if(Array.isArray(h)){if(h.length>1)throw new ie({code:3,command:this.ctor,metadata:{flag:d}});h=h[0]}if(m&&typeof h=="string"&&h.startsWith("=")&&(h=h.slice(1)),typeof h<"u")switch(a.flagTag){case"boolean":{this.flags[f]=l.startsWith("no-")?!h:h;break}case"integer":{let b=Number(h);if(Number.isNaN(b)||!Number.isInteger(b))throw new ie({code:4,command:this.ctor,metadata:{flag:d,value:String(h)}});this.flags[f]=b;break}case"string":default:{if(this.flags[f]=h,h==="-"&&a.stdin){if(s)throw new ie({code:8,command:this.ctor,metadata:{firstUse:s,secondUse:d}});s=d,this.flags[f]=this._handleStdin(a.stdin)}break}}else typeof a.hasDefault<"u"&&(this.flags[f]=a.hasDefault);if(this.flags[f]&&a.choices&&!a.choices.includes(this.flags[f]))throw new ie({code:5,command:this.ctor,metadata:{flag:d,choices:a.choices.map(b=>fs.white.bold(b)).join(", ")}});if(this.flags[f]==null&&(a.required||h!=null))throw new ie({code:6,command:this.ctor,metadata:{flag:d,matcher:g[0],providedButReceivedNoValue:!!h}})}let i=[];for(let[n,a]of o)if(e[n]!=null)for(let c of a){if(e[c]==null)continue;let d=e[n][0],l=e[c][0],f=u((m,g)=>typeof g=="boolean"?g?`--${m}`:`--no-${m}`:`--${m}=${g}`,"flagRepresentation");i.push([f(n,d),f(c,l)]);break}if(i.length)throw new ie({code:7,command:this.ctor,metadata:{flagPairs:i}})}_printMissingRequiredArgs(e){let t=hr(this.ctor,{showUsageString:!0}),o=Rc([...e.keys()].join(`
38
- `)),s=[];for(let[i,n]of e){let a=`${i.padEnd(o)} ${n.description}`,c=Oc(a,oe()-o-2),d=_c(c,o+2+2).trim();s.push(` ${fs.red(">")} ${d}`)}p({message:[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,fs.gray(" See more help with --help"),"",t].join(`
39
- `)})}_handleStdin(e){switch(e){case 2:return(be?.toString("utf8")??"").trim();default:return be}}_buildParseArgsOption(){let e={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:{help:xc}};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=we(Ae(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=Nc),e}static registerCommand(e){if(ps(e,this),q.set(this.name,this),this.aliases?.length)for(let t of this.aliases)q.set(t,this);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)q.set(t,this);if(this.subcommands?.length)for(let t of this.subcommands){if(q.set(`${this.name} ${t.name}`,t),this.aliases?.length)for(let o of this.aliases)q.set(`${o} ${t.name}`,t);if(this.hiddenAliases?.length)for(let o of this.hiddenAliases)q.set(`${o} ${t.name}`,t);if(t.aliases?.length)for(let o of t.aliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}if(t.hiddenAliases?.length)for(let o of t.hiddenAliases){if(q.set(`${this.name} ${o}`,t),this.aliases?.length)for(let s of this.aliases)q.set(`${s} ${o}`,t);if(this.hiddenAliases?.length)for(let s of this.hiddenAliases)q.set(`${s} ${o}`,t)}}}};async function Di(r,e,t){let o={positionals:[],values:{},tokens:[]},s=0;for(let[n,a]of Object.entries(t)){let[c,d]=n.split("_");if(c==="args")o.positionals[s++]=a;else{let l=we(Ae(d)).toLowerCase();l.startsWith("no-")?o.values[l.slice(3)]=!a:o.values[l]=a}}await new e(r)._run(o)}u(Di,"internalRunCommand");import{once as kc}from"events";import{constants as Fi,fstat as Lc}from"fs";import ki from"process";import{promisify as Dc}from"util";import Pc from"chalk";function E(r,...e){process.env.APIFY_CLI_DEBUG&&console.error(Pc.gray(`[${r}]`),...e)}u(E,"cliDebugPrint");var Fc=Dc(Lc),gs;async function Ar(){if(gs)return gs;let r=ki.stdin,e={isTTY:r.isTTY,hasData:!1,waitDelay:0,stream:r},t=await Fc(0).then(o=>{if(E("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),ki.platform==="win32"){if((o.mode&Fi.S_IFIFO)===Fi.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return E("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),gs=e,e}u(Ar,"useStdin");async function Ui(){let r=await Ar(),{hasData:e,waitDelay:t,stream:o}=r;if(!e)return;let s=[],i=new AbortController,n=null;t&&(n=setTimeout(()=>{i.abort()},t).unref()),o.on("data",c=>{s.push(c),n&&(clearTimeout(n),n=null)});try{await kc(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(Ui,"readStdin");import{gt as Hc}from"semver";import{existsSync as Uc,mkdirSync as Mc,readFileSync as jc,writeFileSync as Bc}from"fs";import{dirname as Vc}from"path";function Yc(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;E("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:r,newState:{versionCheck:{lastChecked:t,lastVersion:o}}}),ys({version:1},s=>{s.versionCheck={lastChecked:t,lastVersion:o}})}return!0}u(Yc,"migrateStateV0ToV1");var Gc={version:1};function hs(){let r=rr();if(!Uc(r))return Gc;let t=JSON.parse(jc(r,"utf-8"));return Yc(t)?hs():t}u(hs,"useLocalState");function ys(r,e){let t={...r};e(t);let o=rr(),s=Vc(o);Mc(s,{recursive:!0}),Bc(rr(),JSON.stringify(t,null," "))}u(ys,"updateLocalState");var br=X(),Mi=`Apify CLI/${br.version} (https://github.com/apify/apify-cli)`,Jc=["https://1.1.1.1","https://8.8.8.8"];async function Kc(r=500){let e=new AbortController,t=setTimeout(()=>{e.abort()},r),o=await Promise.any(Jc.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":Mi},keepalive:!1}))).catch(()=>null);return clearTimeout(t),o?o.ok?(E("isOnline",{state:"online",site:o.url}),!0):(E("isOnline",{state:"offline"}),!1):(E("isOnline",{state:"timeout"}),!1)}u(Kc,"isOnline");async function qc(r){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":Mi}});if(!e.ok)return E("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),O({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 E("useCLIVersionCheck","Fetched latest version",{version:o}),ys(r,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}u(qc,"getLatestVersion");function ji(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}u(ji,"shouldSkipVersionCheck");async function Bi(r=!1){let e=hs(),t=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>ei,o=r||t&&await Kc(),s=o?await qc(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:br.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=Hc(s,br.version);return{currentVersion:br.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}u(Bi,"useCLIVersionCheck");import{jaroWinkler as Wc}from"@skyra/jaro-winkler";import zc from"js-levenshtein";function Sr(r){let e=[...q.entries()].sort(([s],[i])=>s.localeCompare(i)),t=r.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),c=a[a.length-1].toLowerCase(),d=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,l=zc(t,n),f=Wc(t,n),m=l<=2||f>=.975;return m?(E("useCommandSuggestions",{inputString:t,lowercased:n,matches:m,levenshtein:l,jaroWinkler:f}),d?{string:`${n} (alias for ${i.name})`,distance:f}:{string:`${n}`,distance:f}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}u(Sr,"useCommandSuggestions");var be=await Ui(),jt=X(),Bt=`Apify CLI/${jt.version} (https://github.com/apify/apify-cli)`;function ng(r){jt.installMethod!=="bundle"&&(Xc(Se.version,he)||(p({message:`${r} CLI requires Node.js version ${he}. Your current version is ${Se.version}.`}),Se.exit(1)))}u(ng,"processVersionCheck");function Zc(r){r.values.version===!0&&r.positionals.length===0&&(console.log(jt.fullVersionString),Se.exit(0))}u(Zc,"printCLIVersionAndExitIfFlagUsed");function Qc(r,e){(r.values.help===!0&&r.positionals.length===0||r.positionals.length===0)&&(console.log(yr(e)),Se.exit(0))}u(Qc,"printHelpAndExitIfFlagUsedOrNoCommandPassed");function Yi(r){let e=Sr(String(r)),t=vr.gray(`Command ${vr.whiteBright(r)} not found`);e.length&&(t+=`
40
- `,t+=vr.gray(`Did you mean: ${e.map(o=>vr.whiteBright(o)).join(", ")}?`)),p({message:t}),Se.exit(1)}u(Yi,"handleCommandNotFound");async function el(r,e){let t=q.get("upgrade");if([t.name,...t.aliases??[]].some(s=>e===s)){E("[VersionCheckMiddleware]","upgrade command detected, skipping version check");return}if(ji()){E("[VersionCheckMiddleware]","skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set");return}await Di(r,t,{flags_internalAutomaticCall:!0})}u(el,"runVersionCheck");async function ag(r){E("CLIMetadata",{...jt,fullVersionString:jt.fullVersionString,argv:Se.argv,cwd:Se.cwd(),execPath:Se.execPath});let e=Se.argv.slice(2);E("ProcessArgv",e);let t=Vi({allowPositionals:!0,strict:!1,options:{help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}},args:e});Zc(t),Qc(t,r),await el(r,t.positionals[0]),E("TopLevelOptions",t);let[o,s]=t.positionals,i=!1,n=q.get(o);if(!n)return Yi(o);let a=n;if(n.subcommands?.length){if(!s)return n.printHelp();i=!0,a=q.get(`${o} ${s}`)}if(!a)return Yi(`${o} ${s}`);let c=[...e],d=c.indexOf(o);if(E("CommandNameIndex",d),c.splice(d,1),i){let m=c.indexOf(s);E("SubcommandNameIndex",m),c.splice(m,1)}E("RebuiltArgs",c),E("CommandToRun",a);let l=new a(r),f=l._buildParseArgsOption();E("ParserOptionsForCommand",f);try{let m=Vi({...f,args:c});await l._run(m),E("CommandArgsResult",m)}catch(m){let g=ie.into(m,a);p({message:g.getPrettyMessage()}),Se.exit(1)}}u(ag,"runCLI");import{APIFY_ENV_VARS as ul}from"@apify/consts";import Vt from"process";import{pipeline as tl}from"stream/promises";import{MemoryStorage as rl}from"@crawlee/memory-storage";import{ApifyClient as ol}from"apify-client";import Gi from"ow";import{ACTOR_ENV_VARS as Hi,APIFY_ENV_VARS as Ji,KEY_VALUE_STORE_KEYS as sl,LOCAL_ACTOR_ENV_VARS as il}from"@apify/consts";var Yt={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},ws=u(async()=>{let r=Vt.env[Ji.TOKEN];if(r)return r;let e=await F();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),tt=u(async(r={},e=Reflect.has(Vt.env,Ji.IS_AT_HOME))=>{let t=le();if(t&&!e)return new rl({localDataDirectory:t,...r});let o=await ws();return new ol({...ls(o),...r})},"getApifyStorageClient"),Gt=u(r=>{let e=Hi[`DEFAULT_${r}_ID`];return Vt.env[e]||il[e]},"getDefaultStorageId"),As=u(async r=>{Gi(r,Gi.string);let e=await tt(),t=Gt(Yt.KEY_VALUE_STORE),o=await e.keyValueStore(t).getRecord(r,{stream:!0});o&&await tl(o.value,Vt.stdout,{end:!1})},"outputRecordFromDefaultStore"),Ki=u(async()=>As(Vt.env[Hi.INPUT_KEY]||sl.INPUT),"outputInputFromDefaultStore");function nl(r){return{argTag:"string",required:r.required??!1,stdin:r.stdin??1,description:r.description,aliases:r.aliases,catchAll:r.catchAll??!1}}u(nl,"stringArg");var w={string:nl};var A={string:al,boolean:cl,integer:ll};function al(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:we(Ae(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(al,"stringFlag");function cl(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:we(Ae(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(cl,"booleanFlag");function ll(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:we(Ae(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(ll,"integerFlag");var mt=class extends y{static name="charge";static description="Charge for a specific event in the pay-per-event Actor run.";static args={eventName:w.string({description:"Name of the event to charge for",required:!0})};static flags={count:A.integer({description:"Number of events to charge",required:!1,default:1}),"idempotency-key":A.string({description:"Idempotency key for the charge request",required:!1}),"test-pay-per-event":A.boolean({description:"Test pay-per-event charging without actually charging",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){v({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){v({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await ws(),a=await Nt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[ul.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.");v({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})}};var pt=class extends y{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";async run(){await Ki()}};import{ACTOR_ENV_VARS as bs,APIFY_ENV_VARS as qi}from"@apify/consts";import{createHmacSignature as dl}from"@apify/utilities";var ft=class extends y{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[qi.IS_AT_HOME])){p({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let t=process.env[qi.API_PUBLIC_BASE_URL],o=process.env[bs.DEFAULT_KEY_VALUE_STORE_ID];if(!o){p({message:`Missing environment variable: ${bs.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let i=await(await tt()).keyValueStore(o).get(),n=new URL(`${t}/v2/key-value-stores/${o}/records/${e}`);if(!i){p({message:`Key-Value store with ID '${o}' was not found. Ensure the store exists and that the correct ID is set in ${bs.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let{urlSigningSecretKey:a}=i;a&&n.searchParams.append("signature",dl(a,e)),console.log(n.toString())}};var gt=class extends y{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;await As(e)}};var ht=class extends y{static name="push-data";static description=`Saves data to Actor's run default dataset.
41
-
42
- Accept input as:
43
- - JSON argument:
44
- $ apify actor push-data {"key": "value"}
45
- - Piped stdin:
46
- $ cat ./test.json | apify actor push-data`;static args={item:w.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,t=e||be;if(!t){p({message:"No item was provided."});return}let o=await tt(),s=Gt(Yt.DATASET),i;try{i=JSON.parse(t.toString("utf8"))}catch(n){throw new Error(`Failed to parse data as JSON string: ${n.message}`)}await o.dataset(s).pushItems(i)}};var yt=class extends y{static name="set-value";static description=`Sets or removes record into the default key-value store associated with the Actor run.
47
-
48
- It is possible to pass data using argument or stdin.
49
-
50
- Passing data using argument:
51
- $ apify actor set-value KEY my-value
52
-
53
- Passing data using stdin with pipe:
54
- $ cat ./my-text-file.txt | apify actor set-value KEY --contentType text/plain`;static args={key:w.string({required:!0,description:"Key of the record in key-value store."}),value:w.string({required:!1,description:`Record data, which can be one of the following values:
55
- - If empty, the record in the key-value store is deleted.
56
- - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
57
- - If options.contentType is set, value is taken as is.`})};static flags={contentType:A.string({char:"c",description:'Specifies a custom MIME content type of the record. By default "application/json" is used.',required:!1})};async run(){let{key:e,value:t}=this.args,{contentType:o="application/json; charset=utf-8"}=this.flags,s=t||process.stdin,n=(await tt()).keyValueStore(Gt(Yt.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var Cr=class extends y{static name="actor";static description="Manages runtime data operations inside of a running Actor.";static subcommands=[yt,ht,gt,ft,pt,mt];async run(){this.printHelp()}};import Ee from"chalk";import ml from"process";async function Ue({providedActorNameOrId:r,client:e}){let t=await F(),o=t.username||t.id,s=Fe(ml.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(Ue,"resolveActorContext");var wt=class extends y{static name="create";static description="Creates a new build of the Actor.";static flags={tag:A.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:A.string({description:"Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.",required:!1}),log:A.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:w.string({description:"Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{tag:e,version:t,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await C(),a=await Ue({providedActorNameOrId:i,client:n});if(!a.valid){p({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let c=await n.actor(a.id).get(),l=mr(c.versions,I=>I.buildTag??"latest")[e??"latest"],f=c.versions.find(I=>I.versionNumber===t),m,g=e;if(f){if(e&&(!l||!l.some(I=>I.versionNumber===t))){p({message:`The Actor Version "${t}" does not have the tag "${e}".`,stdout:!0});return}m=t,g=f.buildTag??"latest"}else if(l&&(m=l[0].versionNumber,g=e??"latest",l.length>1&&!t)){p({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
58
- Available versions for this tag: ${l.map(I=>Ee.yellow(I.versionNumber)).join(", ")}`,stdout:!0});return}if(!m){p({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let h=await n.actor(a.id).build(m,{tag:e});if(o){N(h);return}let b=[`${Ee.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${Ee.gray(h.actId)})`,` ${Ee.yellow("Version")}: ${m} (tagged with ${Ee.yellow(g)})`,"",`${Ee.greenBright("Build Started")} (ID: ${Ee.gray(h.id)})`,` ${Ee.yellow("Build Number")}: ${h.buildNumber} (will get tagged once finished)`,` ${Ee.yellow("Started")}: ${B.display(h.startedAt)}`,""],T=`https://console.apify.com/actors/${h.actId}/builds/${h.buildNumber}`,S=`${Ee.blue("View in Apify Console")}: ${T}`;if(R({message:b.join(`
59
- `),stdout:!0}),s){try{await Ie({job:h,apifyClient:n})}catch(I){p({message:`Failed to print log for build with ID "${h.id}": ${I.message}`,stdout:!0})}R({message:"",stdout:!0})}R({message:S,stdout:!0})}};var Ir=class extends wt{static name="build"};import Zi from"process";import{DownloadItemsFormat as yl}from"apify-client";import re from"chalk";import{access as pl,readFile as fl}from"fs/promises";import gl,{resolve as Wi}from"path";import $e from"process";import hl from"mime";function zi(r,e){let t,o;if(e)t=e,o="application/json";else{let s=Pt(r);s&&(hl.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(zi,"resolveInput");async function At(r,e,t){let o,s;if(!e&&!t){let i=be;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return p({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=n,s="stdin"}catch(n){return p({message:`Cannot parse JSON input from standard input.
60
- ${n.message}`}),$e.exitCode=5,!1}}if(e)switch(e[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),$e.exitCode=5,!1;default:{let i=await pl(Wi(r,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||gl.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return p({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),$e.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=a,s="input"}catch(a){return p({message:`Cannot parse JSON input.
61
- ${a.message}`}),$e.exitCode=5,!1}}}else if(t)switch(t[0]){case"-":return p({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),$e.exitCode=5,!1;default:{let i=Wi(r,t),n;try{let a=await fl(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return p({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=c,s=t}catch(a){n=a}if(n)try{let a=JSON.parse(t);if(Array.isArray(a))return p({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=a,s=t}catch{return p({message:`Cannot read input file at path "${i}".
62
- ${n.message}`}),$e.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}u(At,"getInputOverride");import Ss from"process";import Er from"chalk";import{ACTOR_JOB_STATUSES as Me}from"@apify/consts";var Xi=[Me.SUCCEEDED,Me.ABORTED,Me.FAILED,Me.TIMED_OUT];async function*bt(r,e){let t=Ss.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:d,printRunLogs:l}=e,f=i==="Actor"?"actor":"task",m=zi(t,a);c||(i==="Actor"?ge({message:`Calling ${i} ${o.userFriendlyId} (${Er.gray(o.id)})
63
- `}):o.title?ge({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${Er.gray(o.id)})
64
- `}):ge({message:`Calling ${i} ${o.userFriendlyId} (${Er.gray(o.id)})
65
- `}));let g;try{m&&i==="Actor"?g=await r[f](o.id).start(m.inputToUse,{...s,contentType:m.contentType}):g=await r[f](o.id).start(void 0,s)}catch(h){throw h.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):h}if(yield g,!c&&l)try{await Ie({job:g,timeoutMillis:n,apifyClient:r})==="timeouts"?console.error(`
66
- ${Er.gray("Timeout for printing logs was hit, there may be future logs.")}
67
- `):console.error()}catch(h){O({message:"Can not get log:"}),console.error(h)}if(g=await r.run(g.id).get(),d)for(;!Xi.includes(g.status)&&(g=await r.run(g.id).get(),!Xi.includes(g.status));)await new Promise(h=>{setTimeout(h,1e3)});c||(g.status===Me.SUCCEEDED?_({message:`${i} finished.`}):g.status===Me.RUNNING?O({message:`${i} is still running!`}):g.status===Me.ABORTED||g.status===Me.ABORTING?(O({message:`${i} was aborted!`}),Ss.exitCode=3):(p({message:`${i} failed!`}),Ss.exitCode=1)),yield g}u(bt,"runActorOrTaskOnCloud");var St=u(r=>({build:A.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:A.integer({char:"t",description:`Timeout for the ${r} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:A.integer({char:"m",description:`Amount of memory allocated for the ${r} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var je=class r extends y{static name="call";static description=`Executes Actor remotely using your authenticated account.
68
- Reads input from local key-value store by default.`;static flags={...St("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({char:"f",description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:A.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":A.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=Zi.cwd(),t=Fe(e)||{},o=await C(),s=await F(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){p({message:"You cannot use both the --json and --output-dataset flags when running this command."}),Zi.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await r.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={waitForFinish:2};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let l=await At(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let f=!1,m,g,h,b=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:l?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let T of b)if(m=T,!f&&(f=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${T.id}`,h=`https://console.apify.com/storage/datasets/${T.defaultDatasetId}`;let S=[`${re.yellow("Started")}: ${B.display(T.startedAt)}`];T.containerUrl&&S.push(`${re.yellow("Container URL")}: ${re.blue(T.containerUrl)}`);let I=m.buildNumber.split(".").slice(0,2).join("."),P=c.versions.find(G=>G.versionNumber===I),L=Object.entries(c.taggedBuilds??{}).find(([,G])=>G.buildNumber===T.buildNumber)?.[0],M=[`${re.yellow("Build")}:`,re.cyan(m.buildNumber)];L?M.push(`(${re.yellow(L)})`):M.push(`(${re.gray("N/A")})`),P&&M.push(`| ${re.gray("Actor version:")} ${re.cyan(P.versionNumber)} (${re.yellow(P.buildTag)})`),S.push(M.join(" ")),S.push(`${re.yellow("Timeout")}: ${m.options.timeoutSecs.toLocaleString("en-US")} seconds`),S.push(`${re.yellow("Memory")}: ${m.options.memoryMbytes} MB`),S.push(`${re.blue("View on Apify Console")}: ${g}`,""),R({message:S.join(`
69
- `),stdout:!this.flags.json})}if(this.flags.json){N(m);return}if(this.flags.silent||R({message:["",`${re.blue("Export results")}: ${h}`,`${re.blue("View on Apify Console")}: ${g}`].join(`
70
- `),stdout:!0}),this.flags.outputDataset){let T=m.defaultDatasetId,S,I=4;do{if(S=await o.dataset(T).get(),S?.itemCount)break;await new Promise(L=>{setTimeout(L,250)})}while(I--);let P=await o.dataset(T).downloadItems(yl.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 x from"chalk";import wl from"cli-table3";var Al={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},bl={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},Sl={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 vl={[-1]:void 0,0:Al,1:bl,2:Sl};function Tl(r){return Array.from({length:r},()=>"cyan")}u(Tl,"generateHeaderColors");var Cl=process.stdout.columns??100,$r=Symbol.for("@apify/cli:responsive-table:skip-column"),V=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=Tl(t.length),s=e===0||e===2,i=vl[e],n=[],a=[],c=[];for(let l of t)this.options.hiddenColumns?.includes(l)||this.rows.some(f=>f[l]===$r)||(n.push(this.options.columnAlignments?.[l]||"left"),r.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[l]?.label??l),c.push(this.options.breakpointOverrides?.small?.[l]?.valueFrom??l)):(a.push(l),c.push(l)));let d=new wl({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let l of this.rows){let f=c.map(m=>l[m]);d.push(f)}return d.toString()}static isSmallTerminal(){return Cl<100}};var _r="\u200B",Rr="\u200B\u200B",Qi=new V({allColumns:[_r,Rr],mandatoryColumns:[_r,Rr],columnAlignments:{[_r]:"left",[Rr]:"right"}}),Or=class extends y{static name="info";static description="Get information about an Actor.";static flags={readme:A.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:A.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:w.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:t,input:o,json:s}=this.flags,i=await C(),n=await Ue({providedActorNameOrId:e,client:i});if(!n.valid){p({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),c=await i.user(a.userId).get();a.actorMaker=c;for(let m of Object.values(a.taggedBuilds??{})){if(!m.buildId)continue;let g=await i.build(m.buildId).get();m.build=g}if(s){N(a);return}let d=a.taggedBuilds?.latest;if(t){if(!d){p({message:"No README found for this Actor.",stdout:!0});return}if(!d.build?.readme){p({message:"No README found for this Actor.",stdout:!0});return}R({message:d.build.readme,stdout:!0})}if(o){if(!d){p({message:"No input schema found for this Actor.",stdout:!0});return}if(!d.build?.inputSchema){p({message:"No input schema found for this Actor.",stdout:!0});return}R({message:d.build.inputSchema,stdout:!0})}let l=[`Information about Actor ${x.yellow(`${a.username}/${a.name}`)} (${x.gray(a.id)})`,""];a.title&&l.push(`${x.yellow("Title:")} ${x.bold(a.title)}`),a.description&&l.push(`${x.yellow("Description:")} ${a.description}`),l.push(`${x.yellow("Created at:")} ${x.cyan(B.display(a.createdAt))} ${x.gray("|")} ${x.yellow("Updated at:")} ${x.cyan(B.display(a.modifiedAt))}`),a.actorMaker&&(l.push("",`${x.yellow("Made by:")} ${x.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(l[l.length-1]+=` ${x.bgGray("Maintained by Apify")}`)),a.isPublic?l.push("",`${x.yellow("Actor is")} ${x.green("PUBLIC")}`):l.push("",`${x.yellow("Actor is")} ${x.cyan("PRIVATE")}`),a.isDeprecated&&l.push("",`${x.yellow("Actor is")} ${x.red("DEPRECATED")}`);let f=Reflect.get(a,"pricingInfos");if(f?.length){let m=f.at(-1);switch(m.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(l.push(`${x.yellow("Pricing information:")} ${x.bgGray(`$${m.pricePerUnitUsd}/month + usage`)}`),m.trialMinutes){let g=m.trialMinutes*60*1e3,h=Ft.format(g);l.push(` ${x.yellow("Trial duration:")} ${x.bold(h)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=m.pricePerUnitUsd*1e3;l.push(`${x.yellow("Pricing information:")} ${x.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{l.push(`${x.yellow("Pricing information:")} ${x.bgGray("Pay per event")}`);let g=Object.values(m.pricingPerEvent?.actorChargeEvents??{});for(let T of g)Qi.pushRow({[_r]:T.eventTitle,[Rr]:x.bold(`$${T.eventPriceUsd.toFixed(2)}`)});let b=Qi.render(0).split(`
71
- `);b.splice(1,1),l.push(b.join(`
72
- `));break}case"FREE":{l.push(`${x.yellow("Pricing information:")} ${x.bgGray("Pay for usage")}`);break}default:l.push(`${x.yellow("Pricing information:")} ${x.bgGray(`Unknown pricing model (${x.yellow(m.pricingModel)})`)}`)}}else l.push(`${x.yellow("Pricing information:")} ${x.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(l.push("",x.yellow("SEO information:")),a.seoTitle&&l.push(` ${x.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&l.push(` ${x.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){l.push("",x.yellow("Builds:"));let m=a.taggedBuilds.latest;m&&l.push(` ${x.yellow("-")} ${x.cyan(m.buildNumber)} ${x.gray("/")} ${x.yellow("latest")}`);for(let[g,h]of Object.entries(a.taggedBuilds))g!=="latest"&&l.push(` ${x.yellow("-")} ${x.cyan(h.buildNumber)} ${x.gray("/")} ${x.yellow(g)}`)}R({message:l.join(`
73
- `),stdout:!0})}};import{Time as Il}from"@sapphire/duration";import W from"chalk";import xe from"chalk";function ve(r){switch(r){case"READY":return xe.green("Ready");case"RUNNING":return xe.blue("Running");case"SUCCEEDED":return xe.green("Succeeded");case"FAILED":return xe.red("Failed");case"ABORTING":return xe.yellow("Aborting");case"ABORTED":return xe.red("Aborted");case"TIMING-OUT":return xe.yellow("Timing Out");case"TIMED-OUT":return xe.red("Timed Out");default:return xe.gray(r.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}u(ve,"prettyPrintStatus");var El={"TIMED-OUT":W.gray("after"),"TIMING-OUT":W.gray("after"),ABORTED:W.gray("after"),ABORTING:W.gray("after"),FAILED:W.gray("after"),READY:W.gray("for"),RUNNING:W.gray("for"),SUCCEEDED:W.gray("after")},$l=new V({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"}}}}),_l=new V({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"}}}}),xr=class extends y{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static flags={my:A.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:A.integer({description:"Number of Actors that will be skipped.",default:0}),limit:A.integer({description:"Number of Actors that will be listed.",default:20}),desc:A.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,my:s,json:i}=this.flags,n=await C(),a=await n.actors().list({limit:t,offset:o,desc:e,my:s});if(a.count===0){if(i){N(a);return}v({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 f=>{let m=await n.actor(f.id).get(),g=await n.actor(f.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...f,actor:m??null,lastRun:g.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){N(c);return}let d=s?_l:$l,l=c.items.reduce((f,m)=>{let g=`${m.username}/${m.name}`;return g.length>f?g.length:f},0)+2+6;for(let f of c.items){let m=f.stats.lastRunStartedAt?Dt.display(f.stats.lastRunStartedAt):"",g=f.lastRun?(()=>{if(f.lastRun.finishedAt)return se.format(f.lastRun.finishedAt.getTime()-f.lastRun.startedAt.getTime());let T=Date.now()-f.lastRun.startedAt.getTime();return`${se.format(T)}\u2026`})():"",h=f.actor?(()=>{let T=Object.entries(f.actor.taggedBuilds??{}).find(([S,I])=>I.buildNumber===f.actor.defaultRunOptions.build||S===f.actor.defaultRunOptions.build);return T?`${W.yellow(T[0])} / ${W.cyan(T[1].buildNumber??f.actor.defaultRunOptions.build)}`:W.gray("Unknown")})():W.gray("Unknown"),b=(()=>{if(f.lastRun){let S=[ve(f.lastRun.status)];if(g&&S.push(El[f.lastRun.status],W.cyan(g)),f.lastRun.finishedAt){let I=Date.now()-f.lastRun.finishedAt.getTime();I<Il.Week?S.push(`
74
- `,W.gray(`${se.format(I)} ago`)):S.push(`
75
- `,W.gray("On",Ei.display(f.lastRun.finishedAt)))}return S.join(" ")}return""})();d.pushRow({Name:`${f.title}
76
- ${W.gray(`${f.username}/${f.name}`)}`,Runs:V.isSmallTerminal()&&l>=56?$r:W.cyan(`${f.stats?.totalRuns??0}`),"Last run started at":m,"Last run":m,"Last run status":f.lastRun?ve(f.lastRun.status):"","Modified at":Dt.display(f.modifiedAt),Builds:f.actor?W.cyan(f.actor.stats.totalBuilds):W.gray("Unknown"),"Last run duration":V.isSmallTerminal()?$r:W.cyan(g),"Default build":h,_Small_LastRunText:b})}R({message:d.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 an,readdirSync as Hl,writeFileSync as cn}from"fs";import{dirname as Jl,join as Kl}from"path";import ln from"process";import ql from"adm-zip";import Wl from"axios";import un from"jju";import{gt as zl}from"semver";import Xl from"tiged";import{mkdir as Dl,rename as nn,writeFile as Fl}from"fs/promises";import{dirname as kl,join as Ul}from"path";import sn from"process";import{inspect as Ml}from"util";import{err as Ht,ok as Pr}from"@sapphire/result";import{createPrompt as Rl,isEnterKey as Ol,makeTheme as xl,useKeypress as Nl,usePrefix as Pl,useState as en}from"@inquirer/core";function vs(r,e){let t=e!==!1;return/^(y|yes)/i.test(r)?t=!0:/^(n|no)/i.test(r)&&(t=!1),t}u(vs,"getBooleanValue");function tn(r){return r?"Yes":"No"}u(tn,"boolToString");var rn=Rl((r,e)=>{let t=tn,[o,s]=en("idle"),[i,n]=en(""),a=xl(),c=Pl({status:o,theme:a});Nl((m,g)=>{if(Ol(m)){let h=vs(i,r.default);n(t(h)),s("done"),e(h);return}if(m.name==="tab"){let h=tn(!vs(i,r.default));g.clearLine(0),g.write(h),n(h);return}if(m.name==="y"||m.name==="n"){let h=vs(m.name,r.default);n(t(h)),s("done"),e(h);return}g.clearLine(0),g.write(i),n(g.line)});let d=i,l="";o==="done"?d=a.style.answer(i):l=` ${a.style.defaultAnswer(r.default===!1?"y/N":"Y/n")}`;let f=a.style.message(r.message,o);return`${c} ${f}${l} ${d}`});import Ll from"is-ci";var Ts="confirm",on=`no-${Ts}`;function _e(r,{errorMessageForStdin:e=`Please use the --${Ts}/--${on} flags to confirm the action.`}={}){return async(t,...o)=>{let{isTTY:s,hasData:i}=await Ar(),n=t;if(Ll||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${Ts}/--${on} flags to confirm the action.`);return n.providedConfirmFromStdin}return await r(t,...o)}}u(_e,"stdinCheckWrapper");var J=_e(async({message:r,default:e})=>await rn({message:r,default:e}));var jl=u(r=>Ul(r,or),"getDeprecatedLocalConfigPath"),Nr=new Map;async function Be({cwd:r=sn.cwd(),migrateConfig:e=!0,warnAboutOldConfig:t=!0}={cwd:sn.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=Nr.get(r);if(o)return E("useActorConfig",{cacheHit:!0,config:o}),Pr(o);let s=us(r),i=jl(r),n,a;try{n=Ce(s)}catch(d){return Ht({message:`Failed to read local config at path: '${s}':`,cause:d,exists:!1,config:{}})}try{a=Ce(i)}catch(d){return Ht({message:`Failed to read local config at path: '${i}':`,cause:d,exists:!1,config:{}})}if(n&&a&&t&&await Bl(i),!n&&!a)return Nr.set(r,{exists:!1,migrated:!1,config:{}}),Pr({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let d=await Yl(a,i,s);if(d.isErr())return Ht(d.unwrapErr());n=d.unwrap(),c=!0}return Nr.set(r,{exists:!0,migrated:c,config:n||a||{}}),E("useActorConfig",{cacheHit:!1,config:Nr.get(r)}),Pr({exists:!0,migrated:c,config:n||a||{}})}u(Be,"useActorConfig");async function Bl(r){if(!await J({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?'})){O({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 nn(r,`${r}.deprecated`),v({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(t){t instanceof Error?p({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
77
- ${t.message||t}`}):p({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
78
- ${Ml(t,{showHidden:!1})}`})}}u(Bl,"handleBothConfigVersionsFound");var Vl=["name","version","buildTag"];async function Yl(r,e,t){let o={...r};if(typeof o.version=="object"&&(o=Gl(o)),o={actorSpecification:rs,environmentVariables:r?.env||void 0,...Vl.reduce((i,n)=>(i[n]=r[n],i),{})},!await J({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 Ht({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 Dl(kl(t),{recursive:!0}),await Fl(t,JSON.stringify(o,null," "))}catch(i){let n=i;return Ht({message:`Failed to write the new "actor.json" file to path: '${t}'.
79
- ${n.message||n}`,exists:!0,config:o})}try{await nn(e,`${e}.deprecated`)}catch(i){let n=i;O({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
80
- ${n.message||n}`})}return v({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),Pr(o)}u(Yl,"handleMigrationFlow");function Gl(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(Gl,"updateLocalConfigStructure");var dn=u(async(r,e)=>{let{data:t}=await Wl.get(r,{responseType:"arraybuffer"}),o=new ql(Buffer.from(t,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),vt=class extends y{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static flags={version:A.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version",required:!1}),dir:A.string({description:"Directory where the Actor should be pulled to",required:!1})};static args={actorId:w.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=ln.cwd(),t=await Be({cwd:e});if(t.isErr()){p({message:t.unwrapErr().message}),ln.exitCode=5;return}let{config:o}=t.unwrap(),s=await F(),i=await C(),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 d;try{d=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!d)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:l,versions:f}=d;if(d.isSourceCodeHidden&&!d.versions.length)throw new Error("You cannot pull source code of this Actor because you do not have permission to do so.");let m=null;if(this.flags.version&&(m=f.find(h=>h.versionNumber===this.flags.version),!m))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);m||(m=f.reduce((h,b)=>zl(`${b.versionNumber}.0`,`${h.versionNumber}.0`)?b:h));let g=n?e:Kl(e,this.flags.dir??l);if(an(g,{recursive:!0}),!n&&Hl(g).length!==0){p({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}switch(m.sourceType){case"TARBALL":{await dn(m.tarballUrl,g);break}case"SOURCE_FILES":{let{sourceFiles:h}=m;for(let b of h){let T=Jl(b.name);if(an(`${g}/${T}`,{recursive:!0}),!b.folder){let S=b.format==="BASE64"?Buffer.from(b.content,"base64").toString():b.content;if(b.name===j){let I=un.parse(S);I.name=d.name,cn(`${g}/${b.name}`,un.update(S,I))}else cn(`${g}/${b.name}`,S)}}break}case"GIT_REPO":{let{gitRepoUrl:h}=m,[b,T]=h.split("#"),S,I;T&&([S,I]=T.split(":"));let P=b;I&&(P+=`/${I}`),S&&(P+=`#${S}`);let L=Xl(P);try{await L.clone(g)}catch(M){throw new Error(`Failed to pull Actor from ${h}. ${M.message}`)}break}case"GITHUB_GIST":{await dn(`${m.gitHubGistUrl}/archive/master.zip`,g);break}default:throw new Error(`Unknown source type: ${m.sourceType}`)}_({message:n?`Actor ${l} updated at ${g}/`:`Pulled to ${g}/`})}};import{readFileSync as eu,statSync as tu,unlinkSync as ru}from"fs";import{join as ou,resolve as su}from"path";import ot from"process";import iu from"is-ci";import nu from"open";import{fetchManifest as au}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as st,ACTOR_SOURCE_TYPES as Is,MAX_MULTIFILE_BYTES as bn}from"@apify/consts";import{readFileSync as Zl,writeFileSync as Ql}from"fs";var Cs="@",mn=100,pn=5e4,Lr=u(()=>{try{return JSON.parse(Zl(tr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),fn=u(r=>(et(tr()),Ql(tr(),JSON.stringify(r,null," ")),r),"writeSecretsFile"),gn=u((r,e)=>{let t=Lr();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>mn)throw new Error(`Secret name has to be string with maximum length ${mn}.`);if(typeof e!="string"||e.length>pn)throw new Error(`Secret value has to be string with maximum length ${pn}.`);return t[r]=e,fn(t)},"addSecret"),hn=u(r=>{let e=Lr();if(!e[r])throw new Error(`Secret with name ${r} doesn't exist.`);delete e[r],fn(e)},"removeSecret"),yn=u(r=>new RegExp(`^${Cs}.{1}`).test(r),"isSecretKey"),wn=u((r,e)=>{e=e||Lr();let t={};return Object.keys(r).forEach(o=>{if(yn(r[o])){let s=r[o].replace(new RegExp(`^${Cs}`),"");e[s]?t[o]=e[s]:O({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t[o]=r[o]}),t},"replaceSecretsValue"),An=u((r,e)=>{e=e||Lr();let t=[];return Object.keys(r).forEach(o=>{if(yn(r[o])){let s=r[o].replace(new RegExp(`^${Cs}`),"");e[s]?t.push({name:o,value:e[s],isSecret:!0}):O({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else t.push({name:o,value:r[o]})}),t},"transformEnvToEnvVars");var Es="temp_file.zip",cu={build:"latest",memoryMbytes:4096,timeoutSecs:3600},Sn="0.0",lu="latest",Tt=class extends y{static name="push";static description=`Deploys Actor to Apify platform using settings from '${j}'.
81
- Files under '${bn/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
82
- Use --force to override newer remote versions.`;static flags={version:A.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${j}' file.`,required:!1}),"build-tag":A.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${j}' file`,required:!1}),"wait-for-finish":A.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),"no-prompt":A.boolean({description:"Do not prompt for opening the Actor details in a browser. This will also not open the browser automatically.",default:!1,required:!1}),force:A.boolean({description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:A.string({description:"Directory where the Actor is located",required:!1})};static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to push (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will create or modify the Actor with the name specified in '${j}' file.`})};async run(){let e=su(ot.cwd(),this.flags.dir??"."),t=await Ai(e);if(!t.length){p({message:"You need to call this command from a folder that has an Actor in it!"}),ot.exitCode=4;return}if(![or,"actor.json",".actor/actor.json",".actor"].some(D=>t.some(te=>te===D||te.startsWith(D)))){p({message:["A valid Actor could not be found in the current directory. Please make sure you are in the correct directory.","You can also turn this directory into an Actor by running `apify init`."].join(`
83
- `)}),ot.exitCode=4;return}let o=await C(),s=await Be({cwd:e});if(s.isErr()){p({message:s.unwrapErr().message}),ot.exitCode=5;return}let{config:i}=s.unwrap(),n=await F(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",d,l,f=!1,m=this.flags.version||i?.version||Sn,g=this.flags.buildTag||i?.buildTag;!g&&m===Sn&&(g=lu);let h=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,b=this.args.actorId;if(b){if(l=await o.actor(b).get(),!l)throw new Error(`Cannot find Actor with ID '${b}' in your account.`);d=l.id}else{let D=n.username||n.id;if(l=await o.actor(`${D}/${i.name}`).get(),l)d=l.id;else{let{templates:te}=await au(),Le=te.find(Qt=>Qt.name===i.template)?.defaultRunOptions||cu,es={name:i.name,defaultRunOptions:Le,versions:[{versionNumber:m,buildTag:g,sourceType:Is.SOURCE_FILES,sourceFiles:[]}]};l=await o.actors().create(es),d=l.id,f=!0,v({message:`Created Actor with name ${i.name} on Apify.`})}}v({message:`Deploying Actor '${i.name}' to Apify.`});let T=await ai(t,e),S=o.actor(d),I,P,L;if(T<bn){let D=await S.get();if(!f){let te=t.reduce((Le,es)=>{let{mtimeMs:Qt,ctimeMs:qs}=tu(ou(e,es)),Ws=Qt>qs?Qt:qs;return Le>Ws?Le:Ws},0),fe=D?.modifiedAt.valueOf();if(!this.flags.force&&fe&&te<fe&&(i?.name||b))throw new Error(`Actor with identifier "${i?.name||b}" is already on the platform and was modified there since modified locally.
84
- Skipping push. Use --force to override.`)}P=await wi(t,e),I=Is.SOURCE_FILES}else{ge({message:"Zipping Actor files"}),await bi(Es,t,e);let D=await o.keyValueStores().getOrCreate(`actor-${d}-source`),te=`version-${m}.zip`,fe=eu(Es);await o.keyValueStore(D.id).setRecord({key:te,value:fe,contentType:"application/zip"}),ru(Es),L=`${o.baseUrl}/key-value-stores/${D.id}/records/${te}?disableRedirect=true`,I=Is.TARBALL}let M=await S.version(m).get(),G=i.environmentVariables?An(i.environmentVariables):void 0;if(M){let D={tarballUrl:L,sourceFiles:P,buildTag:g,sourceType:I,envVars:G};await S.version(m).update(D),ge({message:`Updated version ${m} for Actor ${l.name}.`})}else{let D={versionNumber:m,tarballUrl:L,sourceFiles:P,buildTag:g,sourceType:I,envVars:G};await S.versions().create({...D}),ge({message:`Created version ${m} for Actor ${l.name}.`})}ge({message:`Building Actor ${l.name}`});let K=await S.build(m,{useCache:!0,waitForFinish:2});try{await Ie({job:K,timeoutMillis:h,apifyClient:o})}catch(D){O({message:"Can not get log:"}),console.error(D)}K=await o.build(K.id).get(),zs({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${K.actId}#/builds/${K.buildNumber}`}),!iu&&!this.flags.noPrompt&&await J({message:"Do you want to open the Actor detail in your browser?"})&&await nu(`https://console.apify.com${c}/actors/${K.actId}`),K.status===st.SUCCEEDED?_({message:"Actor was deployed to Apify cloud and built there."}):K.status===st.READY?O({message:"Build is waiting for allocation."}):K.status===st.RUNNING?O({message:"Build is still running."}):K.status===st.ABORTED||K.status===st.ABORTING?(O({message:"Build was aborted!"}),ot.exitCode=3):K.status===st.TIMED_OUT||K.status===st.TIMING_OUT?(O({message:"Build timed out!"}),ot.exitCode=2):(p({message:"Build failed!"}),ot.exitCode=1)}};var Dr=class extends y{static name="rm";static description="Permanently removes an Actor from your account.";static args={actorId:w.string({description:"The Actor ID to delete.",required:!0})};async run(){let{actorId:e}=this.args,t=await C();if(!await t.actor(e).get()){p({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await J({message:"Are you sure you want to delete this Actor?"})){v({message:`Deletion of Actor "${e}" was canceled.`});return}try{await t.actor(e).delete(),_({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete Actor "${e}".
85
- ${n.message||n}`})}}};import Q from"chalk";var Fr=class extends y{static name="start";static description=`Starts Actor remotely and returns run details immediately.
86
- Uses authenticated account and local key-value store for input.`;static flags={...St("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${j}' file.`})};async run(){let e=process.cwd(),t=Fe(e)||{},o=await C(),s=await F(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await je.resolveActorId({client:o,localActorName:t.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let l=await At(e,this.flags.input,this.flags.inputFile);if(l===!1)return;let f=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:l?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),m;for await(let L of f)m=L;if(this.flags.json){N(m);return}let g=`https://console.apify.com/actors/${n}/runs/${m.id}`,h=`https://console.apify.com/storage/datasets/${m.defaultDatasetId}`,b=[`${Q.gray("Run:")} Calling Actor ${a} (${Q.gray(n)})`,"",`${Q.yellow("Started")}: ${B.display(m.startedAt)}`];m.containerUrl&&b.push(`${Q.yellow("Container URL")}: ${Q.blue(m.containerUrl)}`);let T=m.buildNumber.split(".").slice(0,2).join("."),S=c.versions.find(L=>L.versionNumber===T),I=Object.entries(c.taggedBuilds??{}).find(([,L])=>L.buildNumber===m.buildNumber)?.[0],P=[`${Q.yellow("Build")}:`,Q.cyan(m.buildNumber)];I?P.push(`(${Q.yellow(I)})`):P.push(`(${Q.gray("N/A")})`),S&&P.push(`| ${Q.gray("Actor version:")} ${Q.cyan(S.versionNumber)} (${Q.yellow(S.buildTag)})`),b.push(P.join(" ")),b.push(`${Q.yellow("Timeout")}: ${m.options.timeoutSecs.toLocaleString("en-US")} seconds`),b.push(`${Q.yellow("Memory")}: ${m.options.memoryMbytes} MB`),b.push("",`${Q.blue("Export results")}: ${h}`,`${Q.blue("View on Apify Console")}: ${g}`),R({message:b.join(`
87
- `),stdout:!0})}};var kr=class extends y{static name="actors";static description="Manages Actor creation, deployment, and execution on the Apify platform.";static subcommands=[Fr,Dr,Tt,vt,xr,Or,je,Ir];async run(){this.printHelp()}};import Z from"chalk";var uu=u(r=>r,"noColor");function z({bytes:r,shortBytes:e=!1,colorFunc:t=uu,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(z,"prettyPrintBytes");var Ur=class extends y{static name="info";static description="Prints information about a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){N(o);return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[g,h]of Object.entries(s.taggedBuilds))if(h.buildId===o.id){i=g;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",c=i?` (tagged as ${Z.yellow(i)})`:"",d=typeof n<"u"?` (exit code: ${Z.gray(n)})`:"",l=[`${Z.yellow("Actor")}: ${a} (${Z.gray(o.actId)})`,"",`${Z.yellow("Build Information")} (ID: ${Z.gray(o.id)})`,` ${Z.yellow("Build Number")}: ${o.buildNumber}${c}`,` ${Z.yellow("Status")}: ${ve(o.status)}${d}`,` ${Z.yellow("Started")}: ${B.display(o.startedAt)}`];if(o.finishedAt)l.push(` ${Z.yellow("Finished")}: ${B.display(o.finishedAt)} (took ${Z.gray(Ft.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();l.push(` ${Z.yellow("Finished")}: ${Z.gray(`Running for ${Ft.format(g)}`)}`)}o.stats?.computeUnits&&l.push(` ${Z.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let f=Reflect.get(o.stats??{},"imageSizeBytes");f&&l.push(` ${Z.yellow("Docker Image Size")}: ${z({bytes:f})}`),l.push(` ${Z.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),l.push("");let m=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;l.push(`${Z.blue("View in Apify Console")}: ${m}`),R({message:l.join(`
88
- `),stdout:!0})}};var Mr=class extends y{static name="log";static description="Prints the log of a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for build with ID "${e}":
89
- `});try{await Ie({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import ue from"chalk";var du=u(()=>new V({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),jr=class extends y{static name="ls";static description="Lists all builds of the Actor.";static flags={offset:A.integer({description:"Number of builds that will be skipped.",default:0}),limit:A.integer({description:"Number of builds that will be listed.",default:10}),desc:A.boolean({description:"Sort builds in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),c=await Ue({providedActorNameOrId:n,client:a});if(!c.valid){p({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let d=await a.actor(c.id).builds().list({desc:e,limit:t,offset:o}),l=await a.actor(c.id).get(),f=mr(d.items,h=>{let b=Reflect.get(h,"buildNumber"),[T,S]=b.split(".");return`${T}.${S}`}),m=Object.entries(l.taggedBuilds??{}).reduce((h,[b,T])=>(h[T.buildNumber]=b,h),{});if(i){for(let h of d.items){let b=Reflect.get(h,"buildNumber"),T=m[b];T&&Reflect.set(h,"buildTag",T)}N(d);return}R({message:`${ue.reset("Showing")} ${ue.yellow(d.items.length)} out of ${ue.yellow(d.total)} builds for Actor ${ue.yellow(c.userFriendlyId)} (${ue.gray(c.id)})
90
- `,stdout:!0});let g=Object.entries(f).sort((h,b)=>h[0].localeCompare(b[0]));for(let[h,b]of g){if(!b?.length){R({message:`No builds for version ${h}`,stdout:!0});continue}let T=l.versions.find(L=>L.versionNumber===h)?.buildTag,S=this.generateTableForActorVersion({buildsForVersion:b,buildTagToActorVersion:m}),I=T?` (latest build gets tagged with ${ue.yellow(T)})`:"",P=[ue.reset(`Builds for Actor Version ${ue.yellow(h)}${I}`),S.render(s?0:-1),""];R({message:P.join(`
91
- `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:t}){let o=du();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=t[i]?` (${ue.yellow(t[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=ue.gray(`${se.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=ue.gray(`Running for ${se.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:ue.gray(s.id),Status:ve(s.status),Took:a})}return o}};import mu from"@inquirer/input";var vn=_e(async({message:r,expectedValue:e,failureMessage:t})=>await mu({message:r,validate(s){return s===e?!0:t??"That is not the correct input!"}}));var Br=class extends y{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static args={buildId:w.string({description:"The build ID to delete.",required:!0})};async run(){let{buildId:e}=this.args,t=await C(),o=await t.build(e).get();if(!o){p({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await t.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[a,c]of Object.entries(s.taggedBuilds))if(e===c.buildId){i=a;break}}if(!await(i?vn:J)({message:`Are you sure you want to delete this Actor Build?${i?` If so, please type in "${i}":`:""}`,expectedValue:i??"",failureMessage:"Your provided value does not match the build tag."})){v({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await t.build(e).delete(),_({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let c=a;p({message:`Failed to delete build "${e}".
92
- ${c.message||c}`,stdout:!0})}}};var Vr=class extends y{static name="builds";static description="Manages Actor build processes and versioning.";static subcommands=[Br,jr,Mr,Ur,wt];async run(){this.printHelp()}};var Yr=class extends je{static name="call"};import pu from"assert";import{existsSync as Gr}from"fs";import{mkdir as fu,readFile as gu,symlink as hu,unlink as yu,writeFile as Tn}from"fs/promises";import{basename as wu,join as de}from"path";import Ve from"chalk";var Au=u(r=>de(r,".install-marker"),"pathToInstallMarker"),$s=u(r=>r.startsWith(process.env.HOME)?r.replace(process.env.HOME,"~"):r,"tildify"),Jt=class extends y{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:t,version:o}=X();if(e!=="bundle"){v({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}pu(t,"When CLI is installed via bundles, the install path must be set");let s=Au(t);if(Gr(s)){v({message:"Apify and Actor CLI are already fully configured! \u{1F44D}"});return}await this.symlinkToLocalBin(t),await this.promptAddToShell(),await Tn(s,o),E("[install] install marker written to",s),R({message:""}),_({message:"To get started, run:"}),R({message:Ve.white.bold(` apify --help
93
- actor --help`)})}async symlinkToLocalBin(e){let t=process.env.HOME;if(E("[install] user home directory",t),!t){E("[install] user home directory not found"),O({message:Ve.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=de(t,".local","bin");Gr(o)||await fu(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=de(e,i);if(!Gr(n)){E("[install] file not found for symlinking",i,n),O({message:Ve.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=de(o,i);await yu(a),await hu(n,a),E("[install] symlink created for item",i,a)}v({message:Ve.gray(`Symlinked apify, actor, and apify-cli to ${o}`)})}async promptAddToShell(){let e=process.env.PROVIDED_INSTALL_DIR;if(!e){O({message:Ve.gray("Install directory not found, cannot add to shell")});return}let t=process.env.FINAL_BIN_DIR;R({message:""});let o=await J({message:"Should the CLI handle adding itself to your shell automatically? (If you say no, you will receive the lines to add to your shell config file)",providedConfirmFromStdin:!1}),s=wu(process.env.SHELL??"sh"),i=`"${e.replaceAll('"','\\"')}"`,n=[],a="";switch(s){case"bash":{n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');let c=[de(process.env.HOME,".bashrc"),de(process.env.HOME,".bash_profile")];process.env.XDG_CONFIG_HOME&&c.push(de(process.env.XDG_CONFIG_HOME,".bashrc"),de(process.env.XDG_CONFIG_HOME,".bash_profile"),de(process.env.XDG_CONFIG_HOME,"bashrc"),de(process.env.XDG_CONFIG_HOME,"bash_profile"));for(let d of c)if(Gr(d)){a=d;break}break}case"zsh":n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a=de(process.env.HOME,".zshrc");break;case"fish":{n.push(`set --export APIFY_CLI_INSTALL ${i}`),n.push(`set --export PATH ${t} $PATH`),a=de(process.env.HOME,".config","fish","config.fish");break}default:n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a="~/.bashrc";break}if(R({message:""}),o&&a){let d=`${await gu(a,"utf-8")}
94
-
95
- # apify cli
96
- ${n.join(`
97
- `)}`;await Tn(a,d),v({message:Ve.gray(`Added "${$s(t)}" to $PATH in ${$s(a)}`)})}else v({message:[Ve.gray(`Manually add the following lines to your shell config file (${$s(a)} or similar):`),...n.map(c=>Ve.white.bold(` ${c}`))].join(`
98
- `)})}};import{spawn as _u}from"child_process";import{existsSync as Ru}from"fs";import{lstat as Ou,readdir as xu,writeFile as En}from"fs/promises";import{dirname as Nu,join as _s}from"path";import Rs from"chalk";import{gte as $n}from"semver";import{Result as Su}from"@sapphire/result";import{execa as vu}from"execa";import{isAbsolute as bu}from"path";function Ye(r){return r?r.startsWith('"')?r:bu(r)&&r.includes(" ")?`"${r}"`:r:null}u(Ye,"normalizeExecutablePath");var Tu=u(async(r,e,t)=>{let o=Ye(r);E("spawnPromised",{escapedCommand:o,args:e,opts:t});let s=vu(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 Su.fromAsync(s.catch(i=>{throw new Error(`${r} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function me({cmd:r,args:e=[],opts:t={},overrideCommand:o}){ge({message:`${o||r} ${e.join(" ")}`});let s=await Tu(r,e,t);if(s.isErr()){let i=s.unwrapErr();if(p({message:i.message}),i.cause)throw i.cause}}u(me,"execWithLog");import{execSync as Cn}from"child_process";import{existsSync as Cu,readFileSync as Iu}from"fs";var Ne=X();function Eu(){return Ne.platform==="linux"?Cu("/etc/alpine-release"):!1}u(Eu,"isInstalledOnMusl");function $u(){return Ne.platform==="darwin"&&Ne.arch==="x64"?!Cn("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Ne.platform==="linux"&&Ne.arch==="x64"?!Iu("/proc/cpuinfo","utf-8").includes("avx2"):Ne.platform==="windows"?Ne.arch==="arm64"?!0:Cn(`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($u,"isInstalledOnBaseline");async function In(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":Bt}});if(!o.ok)return E("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:r,tag:t}),null;let s=await o.json(),i=Eu(),n=$u(),a=s.assets.filter(c=>{let[d,l,f,m,g,h]=c.name.replace(e,"version").replace(".exe","").split("-");return f!==Ne.platform||m!==Ne.arch?!1:i?g==="musl":n?h==="baseline"||g==="baseline":!g&&!h});return E("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}u(In,"useCLIVersionAssets");var _n={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")},Hr="0.21.8",Rn="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",Kt=class extends y{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static hidden=!0;static aliases=["cv","check-version"];static flags={force:A.boolean({description:"Whether to skip checking the locally cached latest version of the CLI and fetch it from the internet instead.",required:!1,char:"f"}),version:A.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":A.boolean({description:"Whether the command was called automatically by the CLI for a version check.",hidden:!0,default:!1})};get cliName(){return this.entrypoint==="apify"?"Apify CLI":"Actor CLI"}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await Bi(this.flags.force),{installMethod:t}=X();if(!e.shouldUpdate||e.currentVersion===Xs){E("[upgrade] no update needed",{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||v({message:`${this.cliName} is up to date \u{1F44D}
99
- `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=_n[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 ${Rs.bgWhite(Rs.black(o))} to update! \u{1F44D}
100
- `].join(`
101
- `);O({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!$n(e,Hr)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Hr}.`});return}let t=await In(e);if(!t){p({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=t;if(!$n(s,Hr)){p({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Hr}.`});return}let i=X();if(i.installMethod==="bundle"){if(!o.length){p({message:["Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
102
- `)});return}let a=Nu(process.execPath);E("[upgrade] bundleDirectory",a);let c=await xu(a);if(!c.some(d=>d.startsWith("apify")||d.startsWith("actor"))){E("[upgrade] directoryEntries",c),p({message:[`Failed to find the currently installed ${this.cliName} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
103
- `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=_n[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){v({message:`Would run command: ${n.join(" ")}`});return}try{await me({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{p({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){_({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,t,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${_s(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${t}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),E("[upgrade] starting upgrade process with args",s),v({message:"Starting upgrade process..."});let n=_u("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{E("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{p({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let t=_s(e,"upgrade.ps1");if(Ru(t))return;let o=X(),s=await fetch(Rn,{headers:{"User-Agent":Bt}});s.ok||(p({message:["Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:",`- The system you are running on: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${Rn}`,`- The status code of the response: ${s.status}`].join(`
104
- `)}),process.exit(1));let i=await s.arrayBuffer();await En(t,Buffer.from(i)),E("[upgrade] downloaded upgrade script to",t)}async handleUnixUpgrade(e,t,o){let s=X();for(let i of o){let n=i.name.split("-")[0],a=_s(e,n);v({message:`Downloading ${n}...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":Bt}});if(!c.ok){let l=await c.text();E("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:l}),p({message:[`Failed to fetch the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${l}`].join(`
105
- `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){v({message:`Would write asset ${n} to ${a}`});continue}v({message:Rs.gray(`Writing ${n} to ${a}...`)});let d=await c.arrayBuffer();try{let l=await Ou(a).then(f=>f.mode).catch(()=>493);await En(a,Buffer.from(d),{mode:l|448}),E(`[upgrade ${n}] wrote asset to`,a)}catch(l){E("[upgrade] failed to write asset",{error:l}),p({message:[`Failed to write the ${n} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${t}`,`- The system you are running on: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${l.message}`].join(`
106
- `)})}}}};import{mkdir as cd,readdir as ld,stat as ud}from"fs/promises";import{join as It}from"path";import Qn from"process";import{gte as dd,minVersion as md}from"semver";import{fetchManifest as pd,manifestUrl as fd}from"@apify/actor-templates";import{createWriteStream as Du}from"fs";import{pipeline as Fu}from"stream/promises";import{Separator as Nn}from"@inquirer/core";import On from"chalk";import Pu from"@inquirer/select";var Ge=_e(async({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i})=>await Pu({message:r,choices:e,pageSize:t,loop:o,default:s,instructions:i}));import Lu from"@inquirer/input";var it=_e(async({message:r,validate:e,default:t})=>await Lu({message:r,validate:e,default:t}),{errorMessageForStdin:"Please provide a valid input based on the command options."});var xn=["JavaScript","TypeScript","Python"];async function Os(r){return r?(Lt(r),r):ku()}u(Os,"ensureValidActorName");async function Pn(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 Dn(t)}u(Pn,"getTemplateDefinition");async function Ln(r,e){let t=await e;if(t instanceof Error)throw t;try{let o=await nr(t.localReadmeSuffixUrl),s=Du(r,{flags:"a"});s.write(`
107
-
108
- `),await Fu(o,s)}catch(o){O({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}u(Ln,"enhanceReadmeWithLocalSuffix");async function Dn(r){let e=await Uu();for(;;){let t=await Mu(r,e);if(t){if(await ju(t))return t}else return Dn(r)}}u(Dn,"executePrompts");async function ku(){return await it({message:"Name of your new Actor:",validate:u(e=>{try{Lt(e)}catch(t){return t.message}return!0},"validate")})}u(ku,"promptActorName");async function Uu(){return await Ge({message:"Choose the programming language of your new Actor:",choices:xn,loop:!1,default:xn[0]})}u(Uu,"promptProgrammingLanguage");async function Mu(r,e){let t=[...r.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new Nn,{name:"Go back",value:!1}];return await Ge({message:"Choose a template for your new Actor. Detailed information about the template will be shown in the next step.",default:t[0],choices:t,loop:!1,pageSize:8})}u(Mu,"promptTemplateDefinition");async function ju(r){let e=[{name:"Install template",value:!0},new Nn,{name:"Go back",value:!1}],t=On.underline(r.label),o=On.dim(r.description),i=`Do you want to install the following template?${`
109
- ${t}:
110
- ${o}`}`;return await Ge({message:i,default:e[0],choices:e,loop:!1})}u(ju,"promptTemplateInstallation");import{platform as Bu}from"os";import{join as Fn}from"path";import Jr from"process";import{none as kn,some as Un}from"@sapphire/result";import{execa as Vu}from"execa";import Yu from"which";var He=new Map;async function Mn(r){try{let e=await Vu(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(Mn,"getPythonVersion");async function qt({cwd:r=Jr.cwd(),force:e=!1}={}){let t=He.get(r);if(t&&!e)return E("usePythonRuntime",{cacheHit:!0,cwd:r,runtime:t.unwrapOr(null)}),t;let o=Bu()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Jr.env.VIRTUAL_ENV?i=Fn(Jr.env.VIRTUAL_ENV,...s):i=Fn(r,".venv",...s),i=Ye(i);try{let a=await Mn(i);if(a)return He.set(r,Un({executablePath:i,version:a})),E("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:He.get(r)?.unwrap()}),He.get(r)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ye(await Yu(a)),d=await Mn(c);if(d)return He.set(r,Un({executablePath:c,version:d})),E("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:He.get(r)?.unwrap()}),He.get(r)}catch{}return He.set(r,kn),E("usePythonRuntime",{cacheHit:!1,cwd:r,runtime:null}),kn}u(qt,"usePythonRuntime");import{access as Ps,readFile as Xu}from"fs/promises";import{basename as Jn,dirname as Zu,join as H,resolve as Kn}from"path";import Qu from"process";import{ok as Ns}from"@sapphire/result";import{existsSync as jn,readdirSync as Hu}from"fs";import{join as Wr,resolve as Ju}from"path";import Ku from"configparser";import{readFileSync as Gu}from"fs";var Kr=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 qr=class{static{u(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=Gu(this.pathname,"utf8"),t=/class\s+(\w+)/g,o=[],s=t.exec(e);for(;s;)o.push(new Kr({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 jn(Wr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Ku,t=Ju(Wr(this.pathname,"scrapy.cfg"));if(!jn(t))throw new Error(`scrapy.cfg not found in "${t}".
111
- 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=Wr(this.pathname,o.replaceAll(".","/")),i=Hu(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&t.push(...new qr(Wr(s,n.name)).getSpiders())}return t}};import xs from"process";import{none as Bn,some as Vn}from"@sapphire/result";import{execa as Gn}from"execa";import Yn from"which";var zr=new Map,qu={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function Wu(r,e){try{let t=await Gn(r,e,{shell:!0,windowsHide:!0,verbose:xs.env.APIFY_CLI_DEBUG?"full":void 0});return t.stdout?t.stdout.trim().replace(/^v/,""):null}catch{return null}}u(Wu,"getRuntimeVersion");async function zu(r){let e=await Gn(r,["--version"],{shell:!0,windowsHide:!0,verbose:xs.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}u(zu,"getNpmVersion");async function Hn(r=xs.cwd()){let e=zr.get(r);if(e)return E("useJavaScriptRuntime",{cacheHit:!0,cwd:r,runtime:e.unwrapOr(null)}),e;for(let[t,o]of Object.entries(qu))try{let s=Ye(await Yn(t)),i=await Wu(s,o);if(i){let n={executablePath:s,version:i};if(t==="node"){let a=Ye(await Yn("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await zu(a),n.pmName="npm")}else n.runtimeShorthand=t,n.pmPath=s,n.pmVersion=i,n.pmName=t;return zr.set(r,Vn(n)),E("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:zr.get(r)?.unwrap()}),Vn(n)}}catch{}return zr.set(r,Bn),E("useJavaScriptRuntime",{cacheHit:!1,cwd:r,runtime:null}),Bn}u(Hn,"useJavaScriptRuntime");var qn=new Map;async function Ct({cwd:r=Qu.cwd()}={}){let e=qn.get(r);if(e)return E("useCwdProject",{cacheHit:!0,project:e}),Ns(e);let t={type:3},s=await u(async()=>{if(await td(r)){t.type=2;let c=await qt({cwd:r});t.runtime=c.unwrapOr(void 0);let d=new nt(r);if(d.loadScrapyCfg(),d.configuration.hasKey("apify","mainpy_location"))t.entrypoint={path:d.configuration.get("apify","mainpy_location")};else{let l=await Wn(r);l&&(t.entrypoint={path:l})}return}let n=await Wn(r);if(n){t.type=1;let c=await qt({cwd:r});t.entrypoint={path:n},t.runtime=c.unwrapOr(void 0);return}let a=await ed(r);if(a){t.type=0;let c=await Hn();t.runtime=c.unwrapOr(void 0),a.type==="file"?t.entrypoint={path:a.path}:a.type==="script"&&(t.entrypoint={script:a.script});return}return Ns(t)},"check")();return s?.isErr()?(E("useCwdProject",{cacheHit:!1,error:s}),s):(E("useCwdProject",{cacheHit:!1,project:t}),qn.set(r,t),Ns(t))}u(Ct,"useCwdProject");async function ed(r){let e=H(r,"package.json");try{let o=await Xu(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await Ps(Kn(r,s.main)),{path:Kn(r,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let t=[H(r,"index.js"),H(r,"index.mjs"),H(r,"index.cjs"),H(r,"main.js"),H(r,"main.mjs"),H(r,"main.cjs"),H(r,"src","index.js"),H(r,"src","index.mjs"),H(r,"src","index.cjs"),H(r,"src","main.js"),H(r,"src","main.mjs"),H(r,"src","main.cjs"),H(r,"dist","index.js"),H(r,"dist","index.mjs"),H(r,"dist","index.cjs"),H(r,"dist","main.js"),H(r,"dist","main.mjs"),H(r,"dist","main.cjs")];for(let o of t)try{return await Ps(o),{path:o,type:"file"}}catch{}return null}u(ed,"checkNodeProject");async function Wn(r){let e=Jn(r),t=[H(r,"src","__main__.py"),H(r,"__main__.py"),H(r,e,"__main__.py"),H(r,e.replaceAll("-","_").replaceAll(" ","_"),"__main__.py")];for(let o of t)try{return await Ps(o),Jn(Zu(o))}catch{}return null}u(Wn,"checkPythonProject");async function td(r){return nt.isApplicable(r)}u(td,"checkScrapyProject");import{existsSync as rd,writeFileSync as od}from"fs";import{join as Xr}from"path";import sd from"process";import id from"lodash.clonedeep";import{KEY_VALUE_STORE_KEYS as nd}from"@apify/consts";import{validateInputSchema as ad}from"@apify/input_schema";var zn=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],at=u(async({forcePath:r,cwd:e}={cwd:sd.cwd()})=>{if(r)return{inputSchema:Ce(r),inputSchemaPath:r};let t=Fe(e);if(typeof t?.input=="object")return{inputSchema:t.input,inputSchemaPath:null};if(typeof t?.input=="string"){let o=Xr(e,os,t.input);return{inputSchema:Ce(o),inputSchemaPath:o}}for(let o of zn){let s=Xr(e,o);if(rd(s))return{inputSchema:Ce(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:Xr(e,zn[0])}},"readInputSchema"),Zr=u(async r=>{let e={};try{let{inputSchema:t}=await at({cwd:r});if(t){let o=new ut({strict:!1});ad(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){O({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${t.message}`})}finally{let t=Te(),o=Xr(r,t,`${nd.INPUT}.json`);od(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),Xn=u(r=>{let e={};for(let[t,o]of Object.entries(r.properties))o.default!==void 0&&(e[t]=o.default);return e},"getDefaultsFromInputSchema"),Zn=u((r,e)=>{let t=id(r);t.required=[];for(let[o,s]of Object.entries(r.properties)){let i=r.required?.includes(o),n=s.default!==void 0;i&&!n&&(t.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete t.$schema,e.compile(t)},"getAjvValidator");var Qr=class extends y{static name="create";static description="Creates an Actor project from a template in a new directory.";static flags={template:A.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it.
112
- Visit ${fd} to find available template names.`,required:!1}),"skip-dependency-install":A.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":A.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":A.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1})};static args={actorName:w.string({required:!1,description:"Name of the Actor and its directory"})};async run(){let{actorName:e}=this.args,{template:t,skipDependencyInstall:o}=this.flags,{templateArchiveUrl:s}=this.flags,i=!1,n=pd().catch(h=>new Error(`Could not fetch template list from server. Cause: ${h?.message}`));e=await Os(e);let a=Qn.cwd(),c=It(a,e);for(;;){let h=await ud(c).catch(()=>null),b=h&&await ld(c).then(T=>T.length>0).catch(()=>!1);if(h?.isDirectory()&&b){p({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Os(),c=It(a,e);continue}h||await cd(c,{recursive:!0});break}let d=null;if(this.telemetryData.fromArchiveUrl=!!s,!s){let h=await Pn(t,n);({archiveUrl:s,messages:d}=h),this.telemetryData.templateId=h.id,this.telemetryData.templateName=h.name,this.telemetryData.templateLanguage=h.category,"skipOptionalDeps"in h&&(i=h.skipOptionalDeps)}this.flags.omitOptionalDeps&&(i=!0),await dr({url:s,pathTo:c});let l=Ce(It(c,j));await ar(Object.assign(l||er,{name:e}),c),await cr(c),await Zr(c);let f=It(c,"package.json"),m=It(c,"README.md");await Ln(m,n);let g=!1;o||await(await Ct({cwd:c})).inspectAsync(async b=>{let T=md(he);if(!b.runtime){switch(b.type){case 0:{O({message:`No Node.js detected! Please install Node.js ${T} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{O({message:`No Python detected! Please install Python ${Ze} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:S}=b;switch(b.type){case 0:{ur(S.version)||O({message:`You are running Node.js version ${S.version}, which is no longer supported. Please upgrade to Node.js version ${T} or later.`}),await ni(f,{name:e});let I=["install"];if(i)switch(S.pmName){case"npm":{dd(S.pmVersion,"7.0.0")?I.push("--omit=optional"):I.push("--no-optional");break}case"bun":{I.push("--omit=optional");break}case"deno":{I.push("--node-modules-dir");break}default:}await me({cmd:S.pmPath,args:I,opts:{cwd:c},overrideCommand:S.pmName}),g=!0;break}case 1:case 2:{if(!lr(S.version)){O({message:`Python Actors require Python 3.9 or higher, but you have Python ${S.version}!`}),O({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let I=It(c,".venv");v({message:`Python version ${S.version} detected.`}),v({message:`Creating a virtual environment in "${I}" and installing dependencies from "requirements.txt"...`}),Qn.env.VIRTUAL_ENV||(await me({cmd:S.executablePath,args:["-m","venv","--prompt",".",ri],opts:{cwd:c}}),S=(await qt({cwd:c,force:!0})).unwrap(),b.runtime=S),await me({cmd:S.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:c}}),await me({cmd:S.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:c}}),g=!0;break}default:}}),g?(_({message:`Actor '${e}' was created. To run it, run "cd ${e}" and "apify run".`}),v({message:'To run your code in the cloud, run "apify push" and deploy your code to Apify Console.'}),d?.postCreate&&v({message:d?.postCreate})):_({message:`Actor '${e}' was created. Please install its dependencies to be able to run it using "apify run".`})}};import ta from"chalk";async function ea(r,e,t){let o=await r[t](e).get().catch(()=>{});if(o)return{[t]:o,[`${t}Client`]:r[t](o.id)};let s=await F(),i=await r[t](`${s.username}/${e}`).get().catch(()=>{});return i?{[t]:i,[`${t}Client`]:r[t](i.id)}:null}u(ea,"tryToGetStorage");async function Re(r,e){return ea(r,e,"dataset")}u(Re,"tryToGetDataset");async function ee(r,e){return ea(r,e,"keyValueStore")}u(ee,"tryToGetKeyValueStore");var eo=class extends y{static name="create";static description="Creates a new dataset for storing structured data on your account.";static args={datasetName:w.string({description:"Optional name for the Dataset",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,t=await C();if(e&&await Re(t,e)){p({message:"A Dataset with this name already exists!"});return}let o=await t.datasets().getOrCreate(e);if(this.flags.json){N(o);return}_({message:`Dataset with ID ${ta.yellow(o.id)}${e?` (called ${ta.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as Je}from"apify-client";var ra={[Je.JSON]:"application/json",[Je.JSONL]:"application/jsonl",[Je.CSV]:"text/csv",[Je.HTML]:"text/html",[Je.RSS]:"application/rss+xml",[Je.XML]:"application/xml",[Je.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},to=class extends y{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static flags={limit:A.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:A.integer({description:"The offset in the dataset where to start getting items."}),format:A.string({description:"The format of the returned output. By default, it is set to 'json'",choices:Object.keys(ra),default:Je.JSON})};static args={datasetId:w.string({description:"The ID of the Dataset to export the items for",required:!0})};async run(){let{limit:e,offset:t,format:o}=this.flags,{datasetId:s}=this.args,i=await C(),n=await this.tryToGetDataset(i,s);if(!n){p({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let c=await a.downloadItems(o,{limit:e,offset:t}),d=ra[o]??"application/octet-stream";R({message:d}),process.stdout.write(c),process.stdout.write(`
113
- `)}async tryToGetDataset(e,t){let o=await e.dataset(t).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await F(),i=await e.dataset(`${s.username}/${t}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import U from"chalk";function ro(r){let e=Reflect.get(r,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}u(ro,"getUserPlanPricing");var oa=new V({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),oo=class extends y{static name="info";static description="Prints information about a specific dataset.";static args={storeId:w.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await Re(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(D=>D),s.actId?t.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?t.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await t.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){N({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let d=s.stats?.storageBytes||0,l=s.stats?.readCount||0,f=s.stats?.writeCount||0,m=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),h=[`${U.bold(l.toLocaleString("en-US"))} ${U.gray(this.pluralString(l,"read","reads"))}`,`${U.bold(f.toLocaleString("en-US"))} ${U.gray(this.pluralString(f,"write","writes"))}`],b=`Items: ${U.bold(m)} ${U.gray("clean")} / ${U.bold(g)} ${U.gray("total")}
114
- Operations: ${h.join(" / ")}`;if(i.plan){let D=ro(i.plan);if(D){let te=D.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),fe=te*24*30,Le=fe>1?`$${fe.toFixed(2)}`:`$${te.toFixed(3)}`;b+=`
115
- Storage size: ${z({bytes:d,shortBytes:!0,precision:1})} / ${U.gray(`${Le} per month`)}`}}else b+=`
116
- Storage size: ${z({bytes:d,shortBytes:!0,precision:1})}`;let T=[`Dataset ID: ${U.bgGray(s.id)}`,`Name: ${s.name?U.bgGray(s.name):U.bold(U.italic("Unnamed"))}`,`Created: ${U.bold(B.display(s.createdAt))}`,`Modified: ${U.bold(B.display(s.modifiedAt))}`].join(`
117
- `),S=U.bold("\u2014");s.actRunId&&(a?S=U.bgBlue(a.id):S=U.italic(U.gray("Run removed")));let I=U.bold("\u2014");n&&(I=U.blue(n.title||n.name));let P=U.bold("\u2014");c&&(P=U.blue(c.title||c.name));let L=[`Run: ${S}`,`Actor: ${I}`,`Task: ${P}`].join(`
118
- `);oa.pushRow({Row1:T,Row2:L});let G=oa.render(2).split(`
119
- `).map(D=>D.trim());G.shift();let K=[`${U.bold(s.name||U.italic("Unnamed"))}`,`${U.gray(s.name?`${i.username}/${s.name}`:s.id)} ${U.gray("Owned by")} ${U.blue(i.username)}`,"",G.join(`
120
- `),"",b].join(`
121
- `);R({message:K,stdout:!0})}};import sa from"chalk";var ia=new V({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),so=class extends y{static name="ls";static description="Prints all datasets on your account.";static flags={offset:A.integer({description:"Number of datasets that will be skipped.",default:0}),limit:A.integer({description:"Number of datasets that will be listed.",default:20}),desc:A.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:A.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await F(),c=await n.datasets().list({desc:e,offset:t,limit:o,unnamed:i});if(s){N(c);return}if(c.count===0){v({message:"You don't have any Datasets on your account",stdout:!0});return}for(let d of c.items){let l=Reflect.get(d.stats,"s3StorageBytes");ia.pushRow({"Dataset ID":d.id,Created:B.display(d.createdAt),Items:`${d.itemCount}`,Modified:B.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof l=="number"?z({bytes:l,shortBytes:!0,colorFunc:sa.gray,precision:0}):sa.gray("N/A")})}R({message:ia.render(1),stdout:!0})}};import io from"chalk";var no=class extends y{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static args={nameOrId:w.string({required:!0,description:"The dataset ID or name to push the objects to",ignoreStdin:!0}),item:w.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:t}=this.args,o=await C(),s=await Re(o,e);if(!s){p({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=t||be;if(!c){p({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(l){p({message:`Failed to parse data as JSON string: ${l.message}`});return}if(Array.isArray(a)&&a.length===0){p({message:"No items were provided."});return}let d=n.name?`Dataset named ${io.yellow(n.name)} (${io.gray("ID:")} ${io.yellow(n.id)})`:`Dataset with ID ${io.yellow(n.id)}`;try{await i.pushItems(a),_({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${d} successfully.`})}catch(l){let f=l;p({message:`Failed to push items into ${d}
122
- ${f.message||f}`})}}};import Ke from"chalk";var ao=class extends y{static name="rename";static description="Change dataset name or removes name with --unname flag.";static flags={unname:A.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:w.string({description:"The dataset ID or name to delete.",required:!0}),newName:w.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:t,nameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await Re(s,o);if(!i){p({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 ${Ke.yellow(n)} has been removed (was ${Ke.yellow(a)} previously).`:`The name of the dataset with ID ${Ke.yellow(n)} was changed from ${Ke.yellow(a)} to ${Ke.yellow(t)}.`:`The name of the dataset with ID ${Ke.yellow(n)} has been set to: ${Ke.yellow(t)}`;try{await i.datasetClient.update({name:e?null:t}),_({message:c,stdout:!0})}catch(d){let l=d;p({message:`Failed to rename dataset with ID ${Ke.yellow(n)}
123
- ${l.message||l}`})}}};import Ds from"chalk";var co=class extends y{static name="rm";static description="Permanently removes a dataset.";static args={datasetNameOrId:w.string({description:"The dataset ID or name to delete",required:!0})};async run(){let{datasetNameOrId:e}=this.args,t=await C(),o=await Re(t,e);if(!o){p({message:`Dataset with ID or name "${e}" not found.`});return}if(!await J({message:"Are you sure you want to delete this Dataset?"})){v({message:"Dataset deletion has been aborted."});return}let{id:i,name:n}=o.dataset;try{await o.datasetClient.delete(),_({message:`Dataset with ID ${Ds.yellow(i)}${n?` (called ${Ds.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;p({message:`Failed to delete dataset with ID ${Ds.yellow(i)}
124
- ${c.message||c}`})}}};var lo=class extends y{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[eo,to,so,oo,co,ao,no];async run(){this.printHelp()}};import{existsSync as Fs,mkdirSync as gd,readFileSync as hd,writeFileSync as yd}from"fs";import{dirname as wd}from"path";import Ad from"cors";import bd from"detect-indent";import ks from"express";import Sd from"open";import{cryptoRandomObjectId as vd}from"@apify/utilities";var aa="https://apify.github.io/input-schema-editor-react/",Td=new URL(aa).origin,na="v1",uo=class extends y{static name="edit-input-schema";static description="Lets you edit your input schema that would be used on the platform in a visual input schema editor.";static args={path:w.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used."})};static hidden=!0;static aliases=["eis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await at({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw new Error(`Editing an input schema directly embedded in '${j}' is not yet supported.`);O({message:`This command is still experimental and might break at any time. Use at your own risk.
125
- `}),v({message:`Editing input schema at "${t}"...`});let o,s=ks();s.use(Ad({origin:Td,allowedHeaders:["Content-Type","Authorization"]})),s.use((f,m,g)=>{m.set("Connection","close"),g()}),s.use(ks.json());let i=vd();s.use((f,m,g)=>{let{token:h}=f.query;if(!h){let b=f.get("Authorization");if(b){let[T,S,...I]=b.trim().split(/\s+/);T.toLowerCase()==="bearer"&&S&&I.length===0&&(h=S)}}h!==i?(m.status(401),m.send("Authorization failed")):g()});let n=ks.Router();s.use(`/api/${na}`,n);let a=" ",c=!0;n.get("/input-schema",(f,m)=>{let g;try{g=Fs(t)?hd(t,{encoding:"utf-8"}):`{}
126
- `,g.length>3&&(a=bd(g).indent||a),g&&(c=g[g.length-1]===`
127
- `),Fs(t)?v({message:`Input schema loaded from "${t}"`}):v({message:"Empty input schema initialized."})}catch(b){let T=`Reading input schema from disk failed with: ${b.message}`;p({message:T}),m.status(500),m.send(T);return}let h;try{h=JSON.parse(g||"{}")}catch(b){let T=`Parsing input schema failed with error: ${b.message}`;p({message:T}),m.status(500),m.send(T);return}m.send(h),v({message:"Input schema sent to editor."})}),n.post("/input-schema",(f,m)=>{try{v({message:"Got input schema from editor..."});let g=f.body,h=JSON.stringify(g,null,a);c&&(h+=`
128
- `);let b=wd(t);Fs(b)||gd(b,{recursive:!0}),yd(t,h,{encoding:"utf-8",flag:"w+"}),m.end(),v({message:"Input schema saved to disk."})}catch(g){let h=`Saving input schema failed with error: ${g.message}`;p({message:h}),m.status(500),m.send(h)}}),n.post("/exit",(f,m)=>{f.body.isWindowClosed?v({message:"Editor closed, finishing..."}):v({message:"Editing finished, you can close the editor."}),m.end(),o.close(()=>_({message:"Done."}))}),o=s.listen(0);let{port:d}=o.address();v({message:`Listening for messages from input schema editor on port ${d}...`});let l=`${aa}?localCliPort=${d}&localCliToken=${i}&localCliApiVersion=${na}`;v({message:`Opening input schema editor at "${l}"...`}),await Sd(l)}};import mo from"chalk";var Wt=class extends y{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:w.string({required:!1,description:"The command to get help for.",catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith("help")){let i=yr(this.entrypoint);console.log(i);return}let t=e.toLowerCase(),o=q.get(t);if(!o){let i=Sr(t),n=mo.gray(`Command ${mo.whiteBright(e)} not found`);i.length&&(n+=`
129
- `,n+=mo.gray(`Did you mean: ${i.map(a=>mo.whiteBright(a)).join(", ")}?`)),p({message:n});return}let s=gr(o);console.log(s)}};import ca from"chalk";var po=class extends y{static name="info";static description="Prints details about your currently authenticated Apify account.";async run(){await C();let e=await F();if(e){let t={username:e.username,userId:e.id};for(let o of Object.keys(t))console.log(`${ca.gray(o)}: ${ca.bold(t[o])}`)}}};import{basename as Ud}from"path";import Bs from"process";import{appendFileSync as Cd,copyFileSync as Id,createWriteStream as Ed,existsSync as Us,mkdirSync as $d,readFileSync as la,rmSync as _d,writeFileSync as Rd}from"fs";import{basename as Od,join as Ms,relative as ua,sep as js}from"path";import{fileURLToPath as xd}from"url";import Nd from"@root/walk";import Pd from"configparser";import Ld from"handlebars";import{fetchManifest as Dd,wrapperManifestUrl as Fd}from"@apify/actor-templates";var kd=[".dockerignore",".gitignore"],fo=xd(new URL("./templates/python-scrapy",import.meta.url));async function da(r,e,t={bindings:{}}){await Nd.walk(r,async(o,s,i)=>{if(s===r)return;let n=ua(r,s),a=n.split(js).map(d=>{if(d.startsWith("{")&&d.endsWith("}")){d=d.replace("{","").replace("}","");let l=t.bindings[d];if(!l)throw new Error(`Binding for ${d} not found.`);return l}return d}).join(js),c=Ms(e,a);if(i.isDirectory())return Us(c)||$d(c),da(s,c);n.includes(".template")?Rd(Ms(e,a.replace(".template","")),Ld.compile(la(s,"utf8"))(t.bindings)):Us(c)&&kd.includes(Od(a))?Cd(c,la(s)):Id(s,c)})}u(da,"merge");async function go({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 Ge({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((d,l)=>({name:`${d.class_name} (${d.pathname})`,value:l}))});function o(d){return`.${ua(r,d).split(js).slice(1).join(".").replace(".py","")}`}u(o,"translatePathToRelativeModuleName");let s={botName:Ii(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 Dd(Fd);v({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:d})=>d==="python-scrapy");Us(fo)&&_d(fo,{recursive:!0}),await dr({url:n,pathTo:fo}),v({message:"Wrapping the Scrapy project..."}),await da(fo,r,{bindings:s});let a=new Pd;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=Ed(Ms(r,"scrapy.cfg"),{flags:"a"});await new Promise(d=>{c.on("open",l=>{c.write(`
130
- `,()=>{a.write(l),d()})})}),_({message:"The Scrapy project has been wrapped successfully."})}u(go,"wrapScrapyProject");var ho=class extends y{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
131
- If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
132
- Creates the '${j}' file and the '${Xe}' directory in the current directory, but does not touch any other existing files or directories.
133
-
134
- WARNING: Overwrites existing '${Xe}' directory.`;static args={actorName:w.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:A.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts. Note that in some cases, the command may still ask for confirmation.',required:!1})};async run(){let{actorName:e}=this.args,t=Bs.cwd(),o=await Ct();o.isErr()&&(p({message:o.unwrapErr().message}),Bs.exit(1));let s=o.unwrap();if(s.type===2)return v({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper=Qs.SCRAPY,go({projectPath:t});if(!this.flags.yes&&s.type===3&&(O({message:"The current directory does not look like a Node.js or Python project."}),!await J({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let i=await Be({cwd:t});if(i.isOkAnd(n=>n.exists&&!n.migrated))O({message:`Skipping creation of '${j}', the file already exists in the current directory.`});else{if(i.isErr()){p({message:i.unwrapErr().message}),Bs.exitCode=5;return}if(!e){let a=i.isOkAnd(c=>c.exists)?i.unwrap().config.name:null;for(;!a;)try{let c=await it({message:"Actor name:",default:Ud(t)});Lt(c),a=c}catch(c){p({message:c.message})}e=a}let n={...er,...i.unwrap().config};await ar(Object.assign(n,{name:e}),t)}await cr(t),await Zr(t),_({message:"The Actor has been initialized in the current directory."})}};var yo=class extends y{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
135
-
136
- It adds the following features:
137
- - Automatic retry of failed requests
138
- - Automatic proxy rotation
139
- - Automatic user agent rotation
140
- ...
141
- `;static args={path:w.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await go({projectPath:this.args.path}),v({message:"Scrapy project wrapped successfully."})}};import ma from"chalk";var wo=class extends y{static name="create";static description="Creates a new key-value store on your account.";static args={"key-value store name":w.string({description:"Optional name for the key-value store",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,t=await C();if(e&&await ee(t,e)){p({message:"Cannot create a key-value store with the same name!"});return}let o=await t.keyValueStores().getOrCreate(e);if(this.flags.json){N(o);return}_({message:`Key-value store with ID ${ma.yellow(o.id)}${e?` (called ${ma.yellow(e)})`:""} was created.`,stdout:!0})}};import Md from"chalk";var Ao=class extends y{static name="delete-value";static description="Delete a value from a key-value store.";static args={"store id":w.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{storeId:e,itemKey:t}=this.args,o=await C(),s=await ee(o,e);if(!s){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(t)){p({message:`Item with key "${t}" not found in the key-value store.`});return}if(!await J({message:"Are you sure you want to delete this record?"})){v({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await i.deleteRecord(t),v({message:`Record with key "${Md.yellow(t)}" deleted from the key-value store.`,stdout:!0})}catch(c){let d=c;p({message:`Failed to delete record with key "${t}" from the key-value store.
142
- ${d.message||d}`})}}};var bo=class extends y{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static flags={"only-content-type":A.boolean({description:"Only return the content type of the specified key",default:!1})};static args={keyValueStoreId:w.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:o}=this.args,s=await C(),i=await ee(s,t);if(!i){p({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){p({message:`Item with key "${o}" not found in the key-value store.`});return}if(R({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:c}=a,d=[];for await(let f of c)d.push(f);let l=Buffer.concat(d).toString();try{let f=JSON.parse(l);R({message:JSON.stringify(f,null,2),stdout:!0})}catch{R({message:l,stdout:!0})}return}a.value.pipe(process.stdout)}};import k from"chalk";var pa=new V({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),So=class extends y{static name="info";static description="Shows information about a key-value store.";static args={storeId:w.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,t=await C(),o=await ee(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([t.user(s.userId).get().then(D=>D),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){N({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let d=s.stats?.storageBytes||0,l=s.stats?.readCount||0,f=s.stats?.writeCount||0,m=s.stats?.deleteCount||0,g=s.stats?.listCount||0,b=`Operations: ${[`${k.bold(l.toLocaleString("en-US"))} ${k.gray(this.pluralString(l,"read","reads"))}`,`${k.bold(f.toLocaleString("en-US"))} ${k.gray(this.pluralString(f,"write","writes"))}`,`${k.bold(m.toLocaleString("en-US"))} ${k.gray(this.pluralString(m,"delete","deletes"))}`,`${k.bold(g.toLocaleString("en-US"))} ${k.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let D=ro(i.plan);if(D){let te=D.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),fe=te*24*30,Le=fe>1?`$${fe.toFixed(2)}`:`$${te.toFixed(3)}`;b+=`
143
- Storage size: ${z({bytes:d,shortBytes:!0,precision:1})} / ${k.gray(`${Le} per month`)}`}}else b+=`
144
- Storage size: ${z({bytes:d,shortBytes:!0,precision:1})} / ${k.gray("$unknown per month")}`;let T=[`Store ID: ${k.bgGray(s.id)}`,`Name: ${s.name?k.bgGray(s.name):k.bold(k.italic("Unnamed"))}`,`Created: ${k.bold(B.display(s.createdAt))}`,`Modified: ${k.bold(B.display(s.modifiedAt))}`].join(`
145
- `),S=k.bold("\u2014");s.actRunId&&(a?S=k.bgBlue(a.id):S=k.italic(k.gray("Run removed")));let I=k.bold("\u2014");n&&(I=k.blue(n.title||n.name));let P=k.bold("\u2014");c&&(P=k.blue(c.title||c.name));let L=[`Run: ${S}`,`Actor: ${I}`,`Task: ${P}`].join(`
146
- `);pa.pushRow({Row1:T,Row2:L});let G=pa.render(2).split(`
147
- `).map(D=>D.trim());G.shift();let K=[`${k.bold(s.name||k.italic("Unnamed"))}`,`${k.gray(s.name?`${i.username}/${s.name}`:s.id)} ${k.gray("Owned by")} ${k.blue(i.username)}`,"",G.join(`
148
- `),"",b].join(`
149
- `);R({message:K,stdout:!0})}};var fa=new V({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),vo=class extends y{static name="keys";static description="Lists all keys in a key-value store.";static flags={limit:A.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":A.string({description:"The key to start the list from."})};static args={storeId:w.string({description:"The key-value store ID to list keys for.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:o}=this.flags,s=await C(),i=await ee(s,e);if(!i){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:t,exclusiveStartKey:o});if(this.flags.json){N(a);return}for(let c of a.items)fa.pushRow({Key:c.key,Size:z({bytes:c.size,shortBytes:!0,precision:0})});R({message:fa.render(1),stdout:!0})}};import ga from"chalk";var ha=new V({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),To=class extends y{static name="ls";static description="Lists all key-value stores on your account.";static flags={offset:A.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:A.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:A.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:A.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:t,limit:o,json:s,unnamed:i}=this.flags,n=await C(),a=await F(),c=await n.keyValueStores().list({desc:e,offset:t,limit:o,unnamed:i});if(s){N(c);return}if(c.count===0){v({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let d of c.items){let f=Reflect.get(d,"stats").s3StorageBytes;ha.pushRow({"Store ID":d.id,Created:B.display(d.createdAt),Modified:B.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof f=="number"?z({bytes:f,shortBytes:!0,colorFunc:ga.gray,precision:0}):ga.gray("N/A")})}R({message:ha.render(1),stdout:!0})}};import qe from"chalk";var Co=class extends y{static name="rename";static description="Renames a key-value store, or removes its unique name.";static flags={unname:A.boolean({description:"Removes the unique name of the key-value store"})};static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0}),newName:w.string({description:"The new name for the key-value store"})};async run(){let{unname:e}=this.flags,{newName:t,keyValueStoreNameOrId:o}=this.args;if(!t&&!e){p({message:"You must provide either a new name or the --unname flag."});return}if(t&&e){p({message:"You cannot provide a new name and the --unname flag."});return}let s=await C(),i=await ee(s,o);if(!i){p({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,c=a?e?`The name of the key-value store with ID ${qe.yellow(n)} has been removed (was ${qe.yellow(a)} previously).`:`The name of the key-value store with ID ${qe.yellow(n)} was changed from ${qe.yellow(a)} to ${qe.yellow(t)}.`:`The name of the key-value store with ID ${qe.yellow(n)} has been set to: ${qe.yellow(t)}`;try{await i.keyValueStoreClient.update({name:e?null:t}),_({message:c,stdout:!0})}catch(d){let l=d;p({message:`Failed to rename key-value store with ID ${qe.yellow(n)}
150
- ${l.message||l}`})}}};import Vs from"chalk";var Io=class extends y{static name="rm";static description="Permanently removes a key-value store.";static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0})};async run(){let{keyValueStoreNameOrId:e}=this.args,t=await C(),o=await ee(t,e);if(!o){p({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await J({message:"Are you sure you want to delete this Key-value store?"})){v({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),_({message:`Key-value store with ID ${Vs.yellow(i)}${n?` (called ${Vs.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;p({message:`Failed to delete key-value store with ID ${Vs.yellow(i)}
151
- ${c.message||c}`})}}};var Eo=class extends y{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static flags={"content-type":A.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:w.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0}),value:w.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:t,value:o}=this.args,{contentType:s}=this.flags,i=await C(),n=await ee(i,e);if(!n){p({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:t,value:o||process.stdin,contentType:s}),_({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(c){let d=c;p({message:`Failed to set value with key "${t}" in the key-value store.
152
- ${d.message||d}`})}}};var $o=class extends y{static name="key-value-stores";static description=`Manages persistent key-value storage.
153
-
154
- Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[wo,Ao,bo,So,vo,To,Co,Io,Eo];async run(){this.printHelp()}};import qd from"chalk";import Wd from"computer-name";import zd from"cors";import Gs from"express";import Xd from"open";import{cryptoRandomObjectId as Zd}from"@apify/utilities";import jd from"@inquirer/password";var ya=_e(async({message:r,mask:e})=>await jd({message:r,mask:e}));import{readFileSync as Bd,writeFileSync as Ys}from"fs";import{promisify as Vd}from"util";import Yd from"mixpanel";import{cryptoRandomObjectId as Gd}from"@apify/utilities";var wa=Yd.init(oi,{keepAlive:!1}),Hd='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". You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry.',Jd=Vd(wa.track.bind(wa)),Aa=u(()=>`CLI:${Gd()}`,"createLocalDistinctId"),ba=u(async()=>{try{return JSON.parse(Bd(De(),"utf-8")).distinctId}catch{let e=(await F()).id||Aa();return v({message:Hd}),et(De()),Ys(De(),JSON.stringify({distinctId:e},null," ")),e}},"getOrCreateLocalDistinctId"),Sa=u(()=>{try{et(De()),Ys(De(),JSON.stringify({distinctId:Aa()},null," "))}catch{}},"regenerateLocalDistinctId"),va=!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY),Kd=u(async({eventName:r,eventData:e})=>{if(va)try{let t=ba();await Jd(r,{distinct_id:t,app:"cli",...e})}catch{}},"maybeTrackTelemetry"),Ta=u(async r=>{if(va)try{let e=ba();et(De()),Ys(De(),JSON.stringify({distinctId:r},null," ")),await Kd({eventName:"$create_alias",eventData:{alias:e}})}catch{}},"useApifyIdentity");var Js="https://console.apify.com/settings/integrations",Qd=new URL(Js).origin,em=Js.includes("localhost")?"http://localhost:3333":void 0,Ca="v1",Hs=u(async r=>{let e=await Nt(r,em),t=await F();return e?(await Ta(t.id),_({message:`You are logged in to Apify as ${t.username||t.id}. ${qd.gray(`Your token is stored at ${ne()}.`)}`})):p({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),_o=class extends y{static name="login";static description=`Authenticates your Apify account and saves credentials to '${ne()}'.
155
- All other commands use these stored credentials.
156
-
157
- Run 'apify logout' to remove authentication.`;static flags={token:A.string({char:"t",description:"[Optional] Apify API token",required:!1}),method:A.string({char:"m",description:"[Optional] Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await Hs(e);return}let o=t;if(t||(o=await Ge({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=Gs();i.use(zd({origin:Qd,allowedHeaders:["Content-Type","Authorization"]})),i.use((l,f,m)=>{f.set("Connection","close"),m()}),i.use(Gs.json());let n=Zd();i.use((l,f,m)=>{let{token:g}=l.query;if(!g){let h=l.get("Authorization");if(h){let[b,T,...S]=h.trim().split(/\s+/);b.toLowerCase()==="bearer"&&T&&S.length===0&&(g=T)}}g!==n?(f.status(401),f.send("Authorization failed")):m()});let a=Gs.Router();i.use(`/api/${Ca}`,a),a.post("/login-token",async(l,f)=>{try{if(l.body.apiToken)await Hs(l.body.apiToken);else throw new Error("Request did not contain API token");f.end()}catch(m){let g=`Login to Apify failed with error: ${m.message}`;p({message:g}),f.status(500),f.send(g)}s.close()}),a.post("/exit",(l,f)=>{l.body.isWindowClosed?p({message:"Login to Apify failed, the console window was closed."}):l.body.actionCanceled?p({message:"Login to Apify failed, the action was canceled in the Apify Console."}):p({message:"Login to Apify failed."}),f.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),d=new URL(Js);d.searchParams.set("localCliCommand","login"),d.searchParams.set("localCliPort",`${c}`),d.searchParams.set("localCliToken",n),d.searchParams.set("localCliApiVersion",Ca);try{d.searchParams.set("localCliComputerName",encodeURIComponent(Wd()))}catch{}v({message:`Opening Apify Console at "${d.href}"...`}),await Xd(d.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await ya({message:"token:"});await Hs(s)}}};var Ro=class extends y{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${ne()}'.
158
- Run 'apify login' to authenticate again.`;async run(){await $t(ne()),Sa(),_({message:"You are logged out from your Apify account."})}};var Oo=class extends vt{static name="pull"};var xo=class extends Tt{static name="push"};var No=class extends y{static name="request-queues";static description="Manages URL queues for web scraping and automation tasks.";async run(){this.printHelp()}};import{existsSync as Ea,renameSync as im}from"fs";import{mkdir as Po,readFile as nm,stat as $a,writeFile as Xt}from"fs/promises";import{dirname as Lo,join as Do}from"path";import Pe from"process";import am from"mime";import{minVersion as cm}from"semver";import{APIFY_ENV_VARS as Fo}from"@apify/consts";import{validateInputSchema as lm,validateInputUsingValidator as _a}from"@apify/input_schema";import{none as zt,some as tm}from"@sapphire/result";import{execa as rm}from"execa";var Ks=u(r=>`
159
- (async () => {
160
- const [nodeModule, process, path, fs] = await Promise.all([
161
- import('node:module'),
162
- import('node:process'),
163
- import('node:path'),
164
- import('node:fs/promises'),
165
- ]);
166
-
167
- /* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
168
- const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
169
-
170
- const _require = nodeModule.createRequire(dirname);
171
-
172
- try {
173
- const modulePath = _require.resolve('${r}');
174
- const moduleDir = path.dirname(modulePath);
175
-
176
- const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
177
-
178
- if (!packageJson) {
179
- console.log('n/a');
180
- return;
181
- }
182
-
183
- const packageJsonObj = JSON.parse(packageJson);
184
- console.log(packageJsonObj.version);
185
- } catch {
186
- console.log('n/a');
187
- }
188
- })();
189
- `.replaceAll(`
190
- `," ").replaceAll(" "," "),"jsScript"),om=u(r=>`
191
- try:
192
- import ${r}
193
- print(${r}.__version__)
194
- except:
195
- print('n/a')
196
- `,"pyScript"),sm={node(r){return["-e",`"${Ks(r)}"`]},deno(r){return["eval",`"${Ks(r)}"`]},bun(r){return["--eval",`"${Ks(r)}"`]},python(r){return["-c",`"${om(r)}"`]}};async function Ia({moduleName:r,project:e}){if(!e.runtime)return E("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:r}),zt;let t;if(e.type===0)t=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)t="python";else return E("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:r}),zt;let o=sm[t]?.(r);if(!o)return E("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:r}),zt;try{let s=await rm(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?(E("useModuleVersion",{status:"no_version_found",project:e,moduleName:r}),zt):(E("useModuleVersion",{status:"success",project:e,moduleName:r,version:s.stdout.trim()}),tm(s.stdout.trim()))}catch(s){return E("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:r,error:s}),zt}}u(Ia,"useModuleVersion");var ko=class extends y{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
197
- Stores data in local '${Xe}' directory.
198
-
199
- NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static flags={purge:A.boolean({char:"p",description:"Whether to purge the default request queue, dataset and key-value store before the run starts.\nFor crawlee projects, this is the default behavior, and the flag is optional.\nUse `--no-purge` to keep the storage folder intact.",required:!1,default:!0,exclusive:["resurrect"]}),resurrect:A.boolean({description:"Whether to keep the default request queue, dataset and key-value store before the run starts.",required:!1,default:!1,exclusive:["purge"]}),entrypoint:A.string({description:["Optional entrypoint for running with injected environment variables.",`
200
- `,"For Python, it is the module name, or a path to a file.",`
201
- `,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};async run(){let e=Pe.cwd(),{proxy:t,id:o,token:s}=await F(),i=await Be({cwd:e});if(i.isErr()){let{message:M,cause:G}=i.unwrapErr();p({message:`${M}${G?`
202
- ${G.message}`:""}`}),Pe.exitCode=5;return}let{config:n}=i.unwrap(),a=le(),c=await Ct({cwd:e});if(c.isErr()){p({message:c.unwrapErr().message}),Pe.exitCode=5;return}let d=c.unwrap(),{type:l,entrypoint:f,runtime:m}=d;if(l===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!m){switch(l){case 0:p({message:`No Node.js detected! Please install Node.js ${he} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:p({message:`No Python detected! Please install Python ${Ze} (or higher) to be able to run Python Actors locally.`});break;default:p({message:`No runtime detected! Make sure you have Python ${Ze} (or higher) or Node.js ${he} (or higher) installed.`})}return}let g,h;if(this.flags.entrypoint){h=this.flags.entrypoint;let M=Do(e,this.flags.entrypoint),G=await $a(M).catch(()=>null);G?.isDirectory()?g=1:G?.isFile()?g=0:g=2}else if(f?.script)g=2,h=f.script;else if(f?.path)g=l!==0?1:0,h=f.path;else{p({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}Ea(ts)&&!Ea(a)&&(im(ts,a),O({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let b=await Ia({moduleName:"crawlee",project:d}),T="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(T="1",b.isNone()&&(await Promise.all([Si(),Ti(),vi()]),v({message:"All default local stores were purged."}))),this.flags.purge||!await Ci()&&!this.flags.resurrect&&O({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 S=await At(e,this.flags.input,this.flags.inputFile);if(S===!1)return;let I=await this.validateAndStoreInput(S),P={[Fo.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:T};if(t&&t.password&&(P[Fo.PROXY_PASSWORD]=t.password),o&&(P[Fo.USER_ID]=o),s&&(P[Fo.TOKEN]=s),n.environmentVariables){let M=wn(n.environmentVariables);Object.assign(P,M)}let L=Object.assign(P,Pe.env);o||O({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(l){case 0:{let M=cm(he);if(ur(m.version)?L.NODE_OPTIONS=L.NODE_OPTIONS?`${L.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":O({message:`You are running Node.js version ${m.version}, which is no longer supported. Please upgrade to Node.js version ${M} or later.`}),g===0||g===1)await me({cmd:m.executablePath,args:[h],opts:{env:L,cwd:e}});else{let G=await nm(Do(e,"package.json"),"utf8").catch(()=>"{}"),K=JSON.parse(G);if(!K.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(!K.scripts[h])throw new Error(`The script "${h}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!m.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 me({cmd:m.pmPath,args:["run",h],opts:{env:L,cwd:e},overrideCommand:m.pmName})}break}case 1:case 2:{if(!lr(m.version)){p({message:`Python Actors require Python 3.9 or higher, but you have Python ${m.version}!`}),p({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await me({cmd:m.executablePath,args:["-m",h],opts:{env:L,cwd:e}}):await me({cmd:m.executablePath,args:[h],opts:{env:L,cwd:e}});break}default:p({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(M){let{stderr:G}=M}finally{if(I)if(I.existingInput){let M=await $a(I.inputFilePath);if(Math.trunc(M.mtimeMs)-I.writtenAt>=5){O({message:`The "${I.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await Xt(I.inputFilePath,I.existingInput.body)}else await _t(I.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:t}=await at({cwd:Pe.cwd()});if(!t){if(!e)return null;let d=Pt(Pe.cwd()),l=Do(Pe.cwd(),Te(),d?.fileName??"INPUT.json");return await Po(Lo(l),{recursive:!0}),await Xt(l,JSON.stringify(e.input,null,2)),{existingInput:d,inputFilePath:l,writtenAt:Date.now()}}let o=new ut({strict:!1,unicodeRegExp:!1});lm(o,t);let s=Xn(t),i=Zn(t,o),n=Pt(Pe.cwd()),a=Do(Pe.cwd(),Te(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
203
- `;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
204
- `;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
205
- `:c=`The input in your storage is invalid. Please fix the following errors:
206
- `;break}if(e){let d={...s,...e.input},l=_a(i,t,d);if(l.length>0)throw new Error(`${c}${l.map(f=>` - ${f.message.replace("Field input.","Field ")}`).join(`
207
- `)}`);return await Po(Lo(a),{recursive:!0}),await Xt(a,JSON.stringify(d,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await Po(Lo(a),{recursive:!0}),await Xt(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(am.getExtension(n.contentType)==="json"){let d=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(d))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let l={...s,...d},f=_a(i,t,l);if(f.length>0)throw new Error(`${c}${f.map(m=>` - ${m.message.replace("Field input.","Field ")}`).join(`
208
- `)}`);return await Po(Lo(a),{recursive:!0}),await Xt(a,JSON.stringify(l,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as Uo}from"@apify/consts";var um=[Uo.READY,Uo.RUNNING],dm=[Uo.ABORTING,Uo.TIMING_OUT],Mo=class extends y{static name="abort";static description="Aborts an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to abort."})};static flags={force:A.boolean({description:"Whether to force the run to abort immediately, instead of gracefully.",default:!1,char:"f"})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!um.includes(o.status)){dm.includes(o.status)?p({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):p({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){N(s);return}this.flags.force?_({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):_({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to abort run "${e}".
209
- ${i.message||i}`,stdout:!0})}}};import $ from"chalk";var Zt=new V({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Ra={"Actor compute units":"ACTOR_COMPUTE_UNITS","Dataset reads":"DATASET_READS","Dataset writes":"DATASET_WRITES","Key-value store reads":"KEY_VALUE_STORE_READS","Key-value store writes":"KEY_VALUE_STORE_WRITES","Key-value store lists":"KEY_VALUE_STORE_LISTS","Request queue reads":"REQUEST_QUEUE_READS","Request queue writes":"REQUEST_QUEUE_WRITES","Data transfer internal":"DATA_TRANSFER_INTERNAL_GBYTES","Data transfer external":"DATA_TRANSFER_EXTERNAL_GBYTES","Proxy residential data transfer":"PROXY_RESIDENTIAL_TRANSFER_GBYTES","Proxy SERPs":"PROXY_SERPS"},jo=class extends y{static name="info";static description="Prints information about an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:A.boolean({char:"v",description:"Prints more in-depth information about the Actor run.",default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,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){N({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let d=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",l=[`${$.yellow("Actor")}: ${d} (${$.grey(o.actId)})`];n?l.push(`\u2514\u2500 ${$.yellow("Task")}: ${n.title??n.name} (${$.gray(o.actorTaskId)})`,""):o.actorTaskId?l.push(`\u2514\u2500 ${$.yellow("Task")}: unknown-task (${$.gray(o.actorTaskId)})`,""):l.push("");let f=` (exit code: ${$.gray(o.exitCode!==null?o.exitCode:"N/A")})`;l.push(`${$.yellow("Status")}: ${ve(o.status)}${f}`),o.statusMessage&&l.push(`\u2514\u2500 ${$.yellow("Status Message:")} ${o.statusMessage}`);let m=a?.itemCount??0;l.push(`${$.yellow("Results")}: ${$.cyan(m.toLocaleString("en-US"))}`),c?l.push(`${$.yellow("Requests")}: ${$.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${$.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):l.push(`${$.yellow("Requests")}: ${$.gray("unknown handled")}`);let g=this.flags.verbose?"":$.gray(` (run with ${$.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?l.push(`${$.yellow("Usage")}: ${$.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):l.push(`${$.yellow("Usage")}: $${$.gray("0.000")}${g}`),this.flags.verbose&&l.push(Zt.render(0)),l.push(""),l.push(`${$.yellow("Started")}: ${B.display(o.startedAt)}`),o.finishedAt)l.push(`${$.yellow("Finished")}: ${B.display(o.finishedAt)} (took ${$.gray(se.format(o.stats.durationMillis))})`);else{let S=Date.now()-o.startedAt.getTime();l.push(`${$.yellow("Finished")}: ${$.gray(`Running for ${se.format(S)}`)}`)}if(l.push(""),o.stats.resurrectCount?l.push(`${$.yellow("Resurrected")}: Yes, ${$.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):l.push(`${$.yellow("Resurrected")}: No`),o.containerUrl&&l.push(`${$.yellow("Container URL")}: ${$.blue(o.containerUrl)}`),l.push(`${$.yellow("Origin")}: ${o.meta.origin}`),s){let S=o.buildNumber.split(".").slice(0,2).join("."),I=s.versions.find(M=>M.versionNumber===S),P=Object.entries(s.taggedBuilds??{}).find(([,M])=>M.buildNumber===o.buildNumber)?.[0],L=[`${$.yellow("Build")}:`,$.cyan(o.buildNumber)];P?L.push(`(${$.yellow(P)})`):L.push(`(${$.gray("N/A")})`),I&&L.push(`| ${$.gray("Actor version:")} ${$.cyan(I.versionNumber)} (${$.yellow(I.buildTag)})`),l.push(L.join(" "))}else l.push(`${$.yellow("Build")}: ${$.cyan(o.buildNumber)}`);l.push(`${$.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),l.push(`${$.yellow("Memory")}: ${o.options.memoryMbytes} MB`),l.push(""),l.push(`${$.yellow("CPU")}: ${$.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${$.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),l.push(`${$.yellow("Memory")}: ${$.gray("Average:")} ${z({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${$.gray("Maximum:")} ${z({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),l.push("");let h=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,b=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,T=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;l.push(`${$.blue("Export results")}: ${b}`),l.push(`${$.blue("View saved items")}: ${T}`),l.push(`${$.blue("View in Apify Console")}: ${h}`),R({message:l.join(`
210
- `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:o}=e;if(!t||!o){for(let s of Object.keys(Ra))Zt.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Ra)){let n=t[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{Zt.pushRow({"":s,Unit:n.toFixed(4),"USD Amount":this.formatUsd(a)});break}case"DATA_TRANSFER_INTERNAL_GBYTES":case"DATA_TRANSFER_EXTERNAL_GBYTES":case"PROXY_RESIDENTIAL_TRANSFER_GBYTES":{Zt.pushRow({"":s,Unit:z({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:Zt.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var Bo=class extends y{static name="log";static description="Prints the log of a specific run.";static args={runId:w.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for run with ID "${e}":
211
- `,stdout:!0});try{await Ie({job:o,apifyClient:t})}catch(s){p({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import pe from"chalk";var Oa=new V({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"}}),Vo=class extends y{static name="ls";static description="Lists all runs of the Actor.";static flags={offset:A.integer({description:"Number of runs that will be skipped.",default:0}),limit:A.integer({description:"Number of runs that will be listed.",default:10}),desc:A.boolean({description:"Sort runs in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.string({description:"Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{desc:e,limit:t,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await C(),c=await Ue({providedActorNameOrId:n,client:a});if(!c.valid){p({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let d=await a.actor(c.id).runs().list({desc:e,limit:t,offset:o});if(i){N(d);return}if(!d.items.length){R({message:"There are no recent runs found for this Actor."});return}let l=[`${pe.reset("Showing")} ${pe.yellow(d.items.length)} out of ${pe.yellow(d.total)} runs for Actor ${pe.yellow(c.userFriendlyId)} (${pe.gray(c.id)})`],f=new Map(await Promise.all(d.items.map(async m=>a.dataset(m.defaultDatasetId).get().then(g=>[m.id,pe.yellow(g?.itemCount??0)],()=>[m.id,pe.gray("N/A")]))));for(let m of d.items){let g;if(m.finishedAt){let h=m.finishedAt.getTime()-m.startedAt.getTime();g=pe.gray(`${se.format(h,void 0,{left:""})}`)}else{let h=Date.now()-m.startedAt.getTime();g=pe.gray(`Running for ${se.format(h,void 0,{left:""})}`)}Oa.pushRow({ID:pe.gray(m.id),Status:ve(m.status),Results:f.get(m.id)||pe.gray("N/A"),Usage:pe.cyan(`$${(m.usageTotalUsd??0).toFixed(3)}`),"Started At":Dt.display(m.startedAt),Took:g,"Build No.":m.buildNumber,Origin:m.meta.origin??"UNKNOWN"})}l.push(Oa.render(s?0:1)),R({message:l.join(`
212
- `),stdout:!0})}};import{ACTOR_JOB_STATUSES as Yo}from"@apify/consts";var mm=[Yo.SUCCEEDED,Yo.FAILED,Yo.ABORTED,Yo.TIMED_OUT],Go=class extends y{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static args={runId:w.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!mm.includes(o.status)){p({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await t.run(e).resurrect();if(this.flags.json){N(s);return}_({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;p({message:`Failed to resurrect run "${e}".
213
- ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Ho}from"@apify/consts";var pm=[Ho.SUCCEEDED,Ho.FAILED,Ho.ABORTED,Ho.TIMED_OUT],Jo=class extends y{static name="rm";static description="Deletes an Actor Run.";static args={runId:w.string({description:"The run ID to delete.",required:!0})};async run(){let{runId:e}=this.args,t=await C(),o=await t.run(e).get();if(!o){p({message:`Run with ID "${e}" was not found on your account.`});return}if(!pm.includes(o.status)){p({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await J({message:"Are you sure you want to delete this Actor Run?"})){v({message:`Deletion of run "${e}" was canceled.`});return}try{await t.run(e).delete(),_({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;p({message:`Failed to delete run "${e}".
214
- ${n.message||n}`})}}};var Ko=class extends y{static name="runs";static description="Manages Actor run operations ";static subcommands=[Mo,jo,Bo,Vo,Go,Jo];async run(){this.printHelp()}};var qo=class extends y{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static args={name:w.string({required:!0,description:"Name of the secret"}),value:w.string({required:!0,description:"Value of the secret"})};async run(){let{name:e,value:t}=this.args;gn(e,t)}};var Wo=class extends y{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static args={name:w.string({required:!0,description:"Name of the secret"})};async run(){let{name:e}=this.args;hn(e)}};var zo=class extends y{static name="secrets";static description=`Manages secure environment variables for Actors.
215
-
216
- Example:
217
- $ apify secrets add mySecret TopSecretValue123
218
-
219
- The "mySecret" value can be used in an environment variable defined in '${j}' file by adding the "@"
220
- prefix:
221
-
222
- {
223
- "actorSpecification": 1,
224
- "name": "my_actor",
225
- "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" },
226
- "version": "0.1"
227
- }
228
-
229
- When the Actor is pushed to Apify cloud, the "SECRET_ENV_VAR" and its value is stored as a secret environment variable
230
- of the Actor.`;static subcommands=[qo,Wo];async run(){this.printHelp()}};import xa from"chalk";var Xo=class extends y{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
231
- Customize with --memory and --timeout flags.
232
- `;static flags=St("Task");static args={taskId:w.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await C(),t=await F(),o=t.username||t.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let c,d,l=bt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let f of l)c=`https://console.apify.com/actors/${f.actId}/runs/${f.id}`,d=`https://console.apify.com/storage/datasets/${f.defaultDatasetId}`;R({message:["",`${xa.blue("Export results")}: ${d}`,`${xa.blue("View on Apify Console")}: ${c}`].join(`
233
- `),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 Zo=class extends y{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[Xo];async run(){this.printHelp()}};import fm from"process";import{validateInputSchema as gm}from"@apify/input_schema";var Qo=class extends y{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
234
- 1. Object in '${j}' under "input" key
235
- 2. JSON file path in '${j}' "input" key
236
- 3. .actor/INPUT_SCHEMA.json
237
- 4. INPUT_SCHEMA.json
238
-
239
- Optionally specify custom schema path to validate.`;static args={path:w.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){let{inputSchema:e,inputSchemaPath:t}=await at({forcePath:this.args.path,cwd:fm.cwd()});if(!e)throw new Error(`Input schema has not been found at ${t}.`);t?v({message:`Validating input schema stored at ${t}`}):v({message:`Validating input schema embedded in '${j}'`});let o=new ut({strict:!1});gm(o,e),_({message:"Input schema is valid."})}};var HR=[Cr,kr,Vr,lo,$o,No,Ko,zo,Zo,Yr,Kt,Jt,Qr,uo,po,yo,ho,_o,Ro,Oo,xo,ko,Qo,Wt],JR=[yt,ht,gt,ft,pt,mt,Wt,Kt,Jt];export{ng as a,ag as b,HR as c,JR as d};
240
- //# sourceMappingURL=chunk-VTIADQJA.js.map