apify-cli 1.6.3-beta.24 → 1.6.3-beta.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -13,6 +13,34 @@ Apify CLI is the command-line tool for creating, developing, and deploying [Apif
|
|
|
13
13
|
- Manage secret environment variables used by your Actors
|
|
14
14
|
- Works with any programming language — Actors run as Docker containers on the platform
|
|
15
15
|
|
|
16
|
+
## Agent skill
|
|
17
|
+
|
|
18
|
+
This repo ships an [agent skill](./skills/apify/SKILL.md) that teaches AI coding agents (Claude Code, Cursor, etc.) how to work with the Apify CLI reliably. You can print the skill straight from the CLI — it always matches your installed version:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
apify help --skill
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
If you'd rather have the skill installed persistently, `apify help --skill` prints a valid `SKILL.md` that you can redirect into your agent's skills directory. The location depends on the agent:
|
|
25
|
+
|
|
26
|
+
### Claude Code
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
mkdir -p ~/.claude/skills/apify-cli
|
|
30
|
+
apify help --skill > ~/.claude/skills/apify-cli/SKILL.md
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Codex and other agents
|
|
34
|
+
|
|
35
|
+
Codex and most other agents follow the [Agent Skills open standard](https://developers.openai.com/codex/skills), which loads skills from `.agents/skills` (per repo) or `~/.agents/skills` (per user):
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
mkdir -p ~/.agents/skills/apify-cli
|
|
39
|
+
apify help --skill > ~/.agents/skills/apify-cli/SKILL.md
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
That copy is a snapshot; re-run it after upgrading the Apify CLI to refresh it.
|
|
43
|
+
|
|
16
44
|
## Quick start
|
|
17
45
|
|
|
18
46
|
1. **Install the CLI** (macOS / Linux):
|
|
@@ -29,15 +57,14 @@ Apify CLI is the command-line tool for creating, developing, and deploying [Apif
|
|
|
29
57
|
apify login
|
|
30
58
|
```
|
|
31
59
|
|
|
32
|
-
3. **
|
|
60
|
+
3. **Run an Actor** on the Apify cloud:
|
|
33
61
|
|
|
34
62
|
```bash
|
|
35
|
-
apify
|
|
36
|
-
cd my-actor
|
|
37
|
-
apify run
|
|
38
|
-
apify push
|
|
63
|
+
apify call apify/hello-world --output-dataset
|
|
39
64
|
```
|
|
40
65
|
|
|
66
|
+
This runs the public [`apify/hello-world`](https://apify.com/apify/hello-world) Actor and prints its results. To build your own Actor instead, run `apify create` and follow the interactive wizard.
|
|
67
|
+
|
|
41
68
|
## Installation
|
|
42
69
|
|
|
43
70
|
### macOS / Linux (bundle, recommended)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as te,rmSync as w,statSync as T,unlinkSync as ne,writeFileSync as E}from"node:fs";import D,{basename as re,dirname as O,isAbsolute as ie,join as k,relative as ae,resolve as A,sep as j}from"node:path";import oe from"string-width";import se from"strip-ansi";import{once as ce}from"node:events";import{homedir as le,platform as ue}from"node:os";import de from"ci-info";import{ACTOR_ENV_VARS as M,ACTOR_JOB_STATUSES as N,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as P,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{createHmacSignature as Ce,cryptoRandomObjectId as we}from"@apify/utilities";import{execSync as Te,spawn as Ee}from"node:child_process";import{access as De,lstat as Oe,mkdir as F,readFile as I,readdir as L,rename as ke,rm as Ae,stat as R,symlink as je,unlink as Me,writeFile as z}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as B}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as V}from"apify-client";import{ZipArchive as He}from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as H,ok as nt,some as rt}from"@sapphire/result";import it from"configparser";import at from"@inquirer/input";import ot from"is-ci";import{execa as st}from"execa";import ct from"which";import{calculateRunDynamicMemory as lt}from"@apify/actor-memory-expression";import{Separator as ut,createPrompt as dt,isEnterKey as ft,makeTheme as pt,useKeypress as mt,usePrefix as ht,useState as gt}from"@inquirer/core";import{MemoryStorage as _t}from"@crawlee/memory-storage";import{compile as vt}from"json-schema-to-typescript";import{cloneDeep as yt}from"es-toolkit";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import Tt from"cli-table3";import{downloadTemplate as Et}from"giget";import Dt from"jju";import Ot from"open";import{fetchManifest as kt,manifestUrl as At,wrapperManifestUrl as jt}from"@apify/actor-templates";import Mt from"computer-name";import Nt from"cors";import Pt from"express";import Ft from"@inquirer/password";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.6.3-beta.
|
|
1
|
+
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import{inspect as a,parseArgs as s,promisify as c}from"node:util";import{gt as l,gte as u,minVersion as f,satisfies as p}from"semver";import{appendFileSync as m,constants as h,copyFileSync as g,createWriteStream as _,existsSync as v,fstat as y,mkdirSync as b,openSync as x,readFileSync as S,readdirSync as C,realpathSync as ee,renameSync as te,rmSync as w,statSync as T,unlinkSync as ne,writeFileSync as E}from"node:fs";import D,{basename as re,dirname as O,isAbsolute as ie,join as k,relative as ae,resolve as A,sep as j}from"node:path";import oe from"string-width";import se from"strip-ansi";import{once as ce}from"node:events";import{homedir as le,platform as ue}from"node:os";import de from"ci-info";import{ACTOR_ENV_VARS as M,ACTOR_JOB_STATUSES as N,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as P,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{createHmacSignature as Ce,cryptoRandomObjectId as we}from"@apify/utilities";import{execSync as Te,spawn as Ee}from"node:child_process";import{access as De,lstat as Oe,mkdir as F,readFile as I,readdir as L,rename as ke,rm as Ae,stat as R,symlink as je,unlink as Me,writeFile as z}from"node:fs/promises";import{get as Ne}from"node:https";import{finished as Pe,pipeline as Fe}from"node:stream/promises";import{DurationFormatter as Ie,Time as Le,TimeTypes as B}from"@sapphire/duration";import{Timestamp as Re}from"@sapphire/timestamp";import ze from"adm-zip";import Be from"ajv/dist/2019.js";import{ApifyClient as Ve,DownloadItemsFormat as V}from"apify-client";import{ZipArchive as He}from"archiver";import Ue,{AxiosHeaders as We}from"axios";import Ge from"escape-string-regexp";import Ke from"ignore";import{getEncoding as qe}from"istextorbinary";import Je,{Mime as Ye}from"mime";import Xe from"mime/types/other.js";import Ze from"mime/types/standard.js";import{glob as Qe}from"tinyglobby";import{rimraf as $e}from"rimraf";import{Result as et,err as tt,none as H,ok as nt,some as rt}from"@sapphire/result";import it from"configparser";import at from"@inquirer/input";import ot from"is-ci";import{execa as st}from"execa";import ct from"which";import{calculateRunDynamicMemory as lt}from"@apify/actor-memory-expression";import{Separator as ut,createPrompt as dt,isEnterKey as ft,makeTheme as pt,useKeypress as mt,usePrefix as ht,useState as gt}from"@inquirer/core";import{MemoryStorage as _t}from"@crawlee/memory-storage";import{compile as vt}from"json-schema-to-typescript";import{cloneDeep as yt}from"es-toolkit";import{validateInputSchema as bt,validateInputUsingValidator as xt}from"@apify/input_schema";import{getDatasetSchemaValidator as St,getKeyValueStoreSchemaValidator as Ct,getOutputSchemaValidator as wt}from"@apify/json_schemas";import Tt from"cli-table3";import{downloadTemplate as Et}from"giget";import Dt from"jju";import Ot from"open";import{fetchManifest as kt,manifestUrl as At,wrapperManifestUrl as jt}from"@apify/actor-templates";import Mt from"computer-name";import Nt from"cors";import Pt from"express";import Ft from"@inquirer/password";import It from"@inquirer/select";import Lt from"node:assert";import{ReadStream as Rt}from"node:tty";import zt from"detect-indent";import{fileURLToPath as Bt}from"node:url";import Vt from"@root/walk";import Ht from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Ut=null;function useCLIMetadata(){if(Ut)return Ut;let e=detectInstallMethod(),t=getRuntimeInfo();return Ut={version:`1.6.3-beta.25`,hash:`25fe45c0a79a3e10256f0eb478738e86666f533a`,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform===`win32`?`windows`:process.platform,runtime:t,extraRuntimeData:t.nodeVersion?`(emulating node ${t.nodeVersion})`:``,installMethod:e,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime.runtime}-${t.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:``}, installed via ${this.installMethod}`},get isBeta(){return this.version.includes(`beta`)||this.version===`0.0.0`}},e===`bundle`&&(Ut.installPath=O(process.execPath)),Ut}let Wt;function getMaxLineWidth(){if(Wt)return Wt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Wt=e;else if(!process.stdout.isTTY)Wt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Wt=e<1?80:e<40?40:e}return Wt}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
|
|
2
2
|
`)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=n(i(this.command.description,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushExamples(e){let{examples:r}=this.command;if(r?.length){e.push(t.bold(`EXAMPLES`));for(let a of r){if(a.description){let r=n(i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
|
|
3
3
|
`).map(e=>`# ${e}`).join(`
|
|
4
4
|
`),2);e.push(t.dim(r))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=n(i(this.command.interactiveNote||`This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.`,getMaxLineWidth()-2,{trim:!1}),2);e.push(r),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){oe(e.join(` `).split(`
|
|
@@ -148,8 +148,8 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
|
|
|
148
148
|
`}),info({message:`Editing input schema at "${t}"...`});let n,r=Pt();r.use(Nt({origin:Nr,allowedHeaders:[`Content-Type`,`Authorization`]})),r.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),r.use(Pt.json());let i=we();r.use((e,t,n)=>{let{token:r}=e.query;if(!r){let t=e.get(`Authorization`);if(t){let[e,n,...i]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&i.length===0&&(r=n)}}r===i?n():(t.status(401),t.send(`Authorization failed`))});let a=Pt.Router();r.use(`/api/v1`,a);let s=` `,c=!0;a.get(`/input-schema`,(e,n)=>{let r;try{r=v(t)?S(t,{encoding:`utf-8`}):`{}
|
|
149
149
|
`,r.length>3&&(s=zt(r).indent||s),r&&(c=r[r.length-1]===`
|
|
150
150
|
`),v(t)?info({message:`Input schema loaded from "${t}"`}):info({message:`Empty input schema initialized.`})}catch(e){let t=`Reading input schema from disk failed with: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}let i;try{i=JSON.parse(r||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(i),info({message:`Input schema sent to editor.`})}),a.post(`/input-schema`,(e,n)=>{try{info({message:`Got input schema from editor...`});let r=e.body,i=JSON.stringify(r,null,s);c&&(i+=`
|
|
151
|
-
`);let a=O(t);v(a)||b(a,{recursive:!0}),E(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${Mr}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Ot(u)}},HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.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 e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
|
|
152
|
-
`,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const
|
|
151
|
+
`);let a=O(t);v(a)||b(a,{recursive:!0}),E(t,i,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}}),a.post(`/exit`,(e,t)=>{e.body.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),n.close(()=>success({message:`Done.`}))}),n=r.listen(0);let{port:l}=n.address();info({message:`Listening for messages from input schema editor on port ${l}...`});let u=`${Mr}?localCliPort=${l}&localCliToken=${i}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${u}"...`}),await Ot(u)}};const Pr=k(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=O(Bt(import.meta.url));for(;;){let t=k(e,Pr);if(v(t))return S(t,`utf-8`);let n=O(e);if(n===e)return null;e=n}}var HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Z.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:Y.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=J.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
|
|
152
|
+
`,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();if(e){let n={username:e.username,userId:e.id};for(let e of Object.keys(n))console.log(`${t.gray(e)}: ${t.bold(n[e])}`)}}};const Fr=[`.dockerignore`,`.gitignore`],Ir=Bt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Vt.walk(e,async(r,i,a)=>{if(i===e)return;let s=ae(e,i),c=s.split(j).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(j),l=k(t,c);if(a.isDirectory())return v(l)||b(l),merge(i,l);s.includes(`.template`)?E(k(t,c.replace(`.template`,``)),Ht.compile(S(i,`utf8`))(n.bindings)):v(l)&&Fr.includes(re(c))?m(l,S(i)):g(i,l)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await br({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${ae(e,t).split(j).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await kt(jt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);v(Ir)&&w(Ir,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:Ir}),info({message:`Wrapping the Scrapy project...`}),await merge(Ir,e,{bindings:r});let s=new it;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=_(k(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
|
|
153
153
|
`,()=>{s.write(t),e()})})}),success({message:`The Scrapy project has been wrapped successfully.`})}var WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
|
|
154
154
|
|
|
155
155
|
It adds the following features:
|
|
@@ -159,17 +159,17 @@ It adds the following features:
|
|
|
159
159
|
...
|
|
160
160
|
`;static args={path:Z.string({required:!1,description:`Optional path to your scrapy project. If not provided, the current directory is used.`})};static hidden=!0;async run(){await wrapScrapyProject({projectPath:this.args.path}),info({message:`Scrapy project wrapped successfully.`})}},InitCommand=class extends ApifyCommand{static name=`init`;static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
|
|
161
161
|
If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
|
|
162
|
-
Creates the '${W}' file and the '${en}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${en}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=re(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${W}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await Fn({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...tn,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n)){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(!await X({message:`Are you sure you want to delete this record?`,providedConfirmFromStdin:r||void 0})){info({message:`Key-value store record deletion aborted.`,stdout:!0});return}try{await a.deleteRecord(n),info({message:`Record with key "${t.yellow(n)}" deleted from the key-value store.`,stdout:!0})}catch(e){let t=e;error({message:`Failed to delete record with key "${n}" from the key-value store.\n ${t.message||t}`})}}},KeyValueStoresGetValueCommand=class extends ApifyCommand{static name=`get-value`;static description=`Retrieves stored value for specified key. Use --only-content-type to check MIME type.`;static examples=[{description:`Read a record value and print it to stdout.`,command:`apify key-value-stores get-value <storeId> INPUT`},{description:`Print only the record content-type.`,command:`apify key-value-stores get-value <storeId> INPUT --only-content-type`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value`;static flags={"only-content-type":Y.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Z.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:n}=this.args,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),t);if(!r){error({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.getRecord(n,{stream:!0});if(!a){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(simpleLog({message:a.contentType??`application/octet-stream`}),e){a.value.destroy();return}if(a.contentType?.includes(`application/json`)){let{value:e}=a,t=[];for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();try{let e=JSON.parse(n);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:n,stdout:!0})}return}a.value.pipe(process.stdout)}};const
|
|
162
|
+
Creates the '${W}' file and the '${en}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${en}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd(),r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=re(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=sanitizeActorName(e.includes(`.`)?e.split(`.`).pop():e)}if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,providedConfirmFromStdin:this.flags.yes})))return;let s=await useActorConfig({cwd:n});if(s.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${W}', the file already exists in the current directory.`});else{if(s.isErr()){error({message:s.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=s.isOkAnd(e=>e.exists)?s.unwrap().config.name:null;for(;!e;)try{let t=await Fn({message:`Actor name:`,default:a});validateActorName(t),e=t}catch(e){error({message:e.message})}t=e}let r={...tn,...s.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);if(this.flags.json){printJsonToStdout(r);return}success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n)){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(!await X({message:`Are you sure you want to delete this record?`,providedConfirmFromStdin:r||void 0})){info({message:`Key-value store record deletion aborted.`,stdout:!0});return}try{await a.deleteRecord(n),info({message:`Record with key "${t.yellow(n)}" deleted from the key-value store.`,stdout:!0})}catch(e){let t=e;error({message:`Failed to delete record with key "${n}" from the key-value store.\n ${t.message||t}`})}}},KeyValueStoresGetValueCommand=class extends ApifyCommand{static name=`get-value`;static description=`Retrieves stored value for specified key. Use --only-content-type to check MIME type.`;static examples=[{description:`Read a record value and print it to stdout.`,command:`apify key-value-stores get-value <storeId> INPUT`},{description:`Print only the record content-type.`,command:`apify key-value-stores get-value <storeId> INPUT --only-content-type`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value`;static flags={"only-content-type":Y.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Z.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:n}=this.args,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),t);if(!r){error({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.getRecord(n,{stream:!0});if(!a){error({message:`Item with key "${n}" not found in the key-value store.`});return}if(simpleLog({message:a.contentType??`application/octet-stream`}),e){a.value.destroy();return}if(a.contentType?.includes(`application/json`)){let{value:e}=a,t=[];for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();try{let e=JSON.parse(n);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:n,stdout:!0})}return}a.value.pipe(process.stdout)}};const Lr=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var KeyValueStoresInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Shows information about a key-value store.`;static examples=[{description:`Show metadata about a key-value store.`,command:`apify key-value-stores info <storeId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info`;static args={storeId:Z.string({description:`The key-value store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetKeyValueStore(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=i.stats?.deleteCount||0,h=i.stats?.listCount||0,g=`Operations: ${[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`,`${t.bold(m.toLocaleString(`en-US`))} ${t.gray(this.pluralString(m,`delete`,`deletes`))}`,`${t.bold(h.toLocaleString(`en-US`))} ${t.gray(this.pluralString(h,`list`,`lists`))}`].join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`$unknown per month`)}`;let _=[`Store ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(G.display(i.createdAt))}`,`Modified: ${t.bold(G.display(i.modifiedAt))}`].join(`
|
|
163
163
|
`),v=t.bold(`—`);i.actRunId&&(v=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let y=t.bold(`—`);s&&(y=t.blue(s.title||s.name));let b=t.bold(`—`);l&&(b=t.blue(l.title||l.name));let x=[`Run: ${v}`,`Actor: ${y}`,`Task: ${b}`].join(`
|
|
164
|
-
`);
|
|
164
|
+
`);Lr.pushRow({Row1:_,Row2:x});let S=Lr.render(2).split(`
|
|
165
165
|
`).map(e=>e.trim());S.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,S.join(`
|
|
166
166
|
`),``,g].join(`
|
|
167
|
-
`),stdout:!0})}};const
|
|
167
|
+
`),stdout:!0})}};const Rr=new Q({allColumns:[`Key`,`Size`],mandatoryColumns:[`Key`,`Size`]});var KeyValueStoresKeysCommand=class extends ApifyCommand{static name=`keys`;static description=`Lists all keys in a key-value store.`;static examples=[{description:`List the first 20 keys in a key-value store.`,command:`apify key-value-stores keys <storeId>`},{description:`Paginate keys past an exclusive start key.`,command:`apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys`;static flags={limit:Y.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":Y.string({description:`The key to start the list from.`})};static args={storeId:Z.string({description:`The key-value store ID to list keys for.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.listKeys({limit:t,exclusiveStartKey:n});if(this.flags.json){printJsonToStdout(a);return}for(let e of a.items)Rr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Rr.render(1),stdout:!0})}};const zr=new Q({allColumns:[`Store ID`,`Name`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Store ID`,`Name`,`Size`]});var KeyValueStoresLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all key-value stores on your account.`;static examples=[{description:`List your key-value stores.`,command:`apify key-value-stores ls`},{description:`List the next page of stores, sorted descending.`,command:`apify key-value-stores ls --limit 50 --offset 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls`;static flags={offset:Y.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:Y.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists key-value stores that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getLocalUserInfo(),l=await s.keyValueStores().list({desc:e,offset:n,limit:r,unnamed:a});if(i){printJsonToStdout(l);return}if(l.count===0){info({message:`You don't have any key-value stores on your account`,stdout:!0});return}for(let e of l.items){let n=Reflect.get(e,`stats`).s3StorageBytes;zr.pushRow({"Store ID":e.id,Created:G.display(e.createdAt),Modified:G.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:zr.render(1),stdout:!0})}},KeyValueStoresRenameCommand=class extends ApifyCommand{static name=`rename`;static description=`Renames a key-value store, or removes its unique name.`;static examples=[{description:`Rename a key-value store.`,command:`apify key-value-stores rename old-name new-name`},{description:`Remove the name from a key-value store.`,command:`apify key-value-stores rename my-store --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the key-value store.`})};async run(){let{unname:e}=this.flags,{newName:n,keyValueStoreNameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),r);if(!i){error({message:`Key-value store with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.keyValueStore,c=s?e?`The name of the key-value store with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the key-value store with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the key-value store with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.keyValueStoreClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename key-value store with ID ${t.yellow(a)}\n ${n.message||n}`})}}},KeyValueStoresRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a key-value store (prompts for confirmation).`,command:`apify key-value-stores rm my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm`;static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Key-value store?`,providedConfirmFromStdin:n||void 0})){info({message:`Key-value store deletion has been aborted.`});return}let{id:i,name:a}=r.keyValueStore;try{await r.keyValueStoreClient.delete(),success({message:`Key-value store with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete key-value store with ID ${t.yellow(i)}\n ${n.message||n}`})}}},KeyValueStoresSetValueCommand=class extends ApifyCommand{static name=`set-value`;static description=`Stores value with specified key. Set content-type with --content-type flag.`;static examples=[{description:`Store a JSON value under a key.`,command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:`Store a plain-text file read from stdin.`,command:`cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value`;static flags={"content-type":Y.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Z.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0}),value:Z.string({description:`The value to set.`})};async run(){let{storeId:e,itemKey:t,value:n}=this.args,{contentType:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;try{await a.setRecord({key:t,value:n||process.stdin,contentType:r}),success({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to set value with key "${t}" in the key-value store.\n ${n.message||n}`})}}},KeyValueStoresIndexCommand=class extends ApifyCommand{static name=`key-value-stores`;static description=`Manage Apify key-value stores — create, list, rename, delete stores, and get/set/delete individual records.
|
|
168
168
|
|
|
169
169
|
Alias: kvs.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores`;static hiddenAliases=[`kvs`];static subcommands=[KeyValueStoresCreateCommand,KeyValueStoresDeleteValueCommand,KeyValueStoresGetValueCommand,KeyValueStoresInfoCommand,KeyValueStoresKeysCommand,KeyValueStoresLsCommand,KeyValueStoresRenameCommand,KeyValueStoresRmCommand,KeyValueStoresSetValueCommand];async run(){this.printHelp()}},LoginCommand=class extends AuthLoginCommand{static name=`login`},LogoutCommand=class extends AuthLogoutCommand{static name=`logout`};async function confirmOverwrite({filePath:e,entryKey:t,yes:n}){return X({message:`A server entry named '${t}' already exists in ${tildify(e)}. Overwrite it?`,default:!1,providedConfirmFromStdin:n||void 0,errorMessageForStdin:`An '${t}' entry already exists in ${tildify(e)}. Re-run with --yes to overwrite.`})}async function mergeServerEntry({filePath:t,topLevelKey:n,entryKey:r,serverEntry:i,yes:a}){let s=v(t)?await I(t,`utf-8`):``,c=s.trim(),l;if(c){let e;try{e=Dt.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
|
|
170
|
-
`)[0]:`invalid JSON`;throw Error(`Cannot install: ${tildify(t)} is not valid JSON (${n}). Fix the file manually and re-run.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Cannot install: ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let c=e[n];if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw Error(`Cannot install: '${n}' in ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let u=c??{};if(Object.prototype.hasOwnProperty.call(u,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;u[r]=i,e[n]=u,l=Dt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Dt.stringify(e,{mode:`json`,indent:2})}\n`}await F(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await z(u,l,`utf-8`),await ke(u,t)}catch(e){throw await Ae(u,{force:!0}),e}return!0}function buildMcpUrl(e,t){if(!t)return e;let n=t.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`);if(!n)return e;let r=new URL(e);return r.searchParams.set(`tools`,n),r.toString()}function maskToken(e){return e.length<=14?`***`:`${e.slice(0,10)}...${e.slice(-4)}`}function maskSecret(e,t){return t?e.split(t).join(maskToken(t)):e}const
|
|
171
|
-
`)})}function isExecaError(e){return typeof e==`object`&&!!e&&`shortMessage`in e&&`command`in e}function describeExecaError(e,t){return isExecaError(e)?e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage??e.message:`${t} exited with code ${e.exitCode}`:e instanceof Error?e.message:String(e)}async function runCliInstall({binary:t,clientLabel:n,token:r,args:i,maskedCommand:a,missingMessage:s}){if(!await ct(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await st(t,i,{stdio:[`ignore`,`ignore`,`pipe`]})}catch(i){let a=isExecaError(i)?String(i.stderr??``).trim():``;return error({message:maskSecret(`Failed to add the MCP server via ${n}: ${a?`${describeExecaError(i,t)}\n${a}`:describeExecaError(i,t)}`,r)}),e.exitCode=1,!1}return!0}function fileClient({label:t,segments:n,entry:r}){return async({url:i,token:a,yes:s})=>{let c=userHomeDir();if(!c){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let l=k(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:
|
|
172
|
-
`);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},
|
|
170
|
+
`)[0]:`invalid JSON`;throw Error(`Cannot install: ${tildify(t)} is not valid JSON (${n}). Fix the file manually and re-run.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Cannot install: ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let c=e[n];if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw Error(`Cannot install: '${n}' in ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let u=c??{};if(Object.prototype.hasOwnProperty.call(u,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;u[r]=i,e[n]=u,l=Dt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Dt.stringify(e,{mode:`json`,indent:2})}\n`}await F(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await z(u,l,`utf-8`),await ke(u,t)}catch(e){throw await Ae(u,{force:!0}),e}return!0}function buildMcpUrl(e,t){if(!t)return e;let n=t.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`);if(!n)return e;let r=new URL(e);return r.searchParams.set(`tools`,n),r.toString()}function maskToken(e){return e.length<=14?`***`:`${e.slice(0,10)}...${e.slice(-4)}`}function maskSecret(e,t){return t?e.split(t).join(maskToken(t)):e}const Br=`apify`,bearer=e=>({Authorization:`Bearer ${e}`});function printResult(e){success({message:`Apify MCP server configured for ${e.clientLabel}.`});let n=[``,` ${t.yellow(`Server URL:`)} ${e.serverUrl}`,` ${t.yellow(`Auth:`)} ${e.authDescription}`];e.configPath&&n.push(` ${t.yellow(`Config:`)} ${tildify(e.configPath)}`),e.nextSteps&&n.push(``,e.nextSteps),simpleLog({message:n.join(`
|
|
171
|
+
`)})}function isExecaError(e){return typeof e==`object`&&!!e&&`shortMessage`in e&&`command`in e}function describeExecaError(e,t){return isExecaError(e)?e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage??e.message:`${t} exited with code ${e.exitCode}`:e instanceof Error?e.message:String(e)}async function runCliInstall({binary:t,clientLabel:n,token:r,args:i,maskedCommand:a,missingMessage:s}){if(!await ct(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await st(t,i,{stdio:[`ignore`,`ignore`,`pipe`]})}catch(i){let a=isExecaError(i)?String(i.stderr??``).trim():``;return error({message:maskSecret(`Failed to add the MCP server via ${n}: ${a?`${describeExecaError(i,t)}\n${a}`:describeExecaError(i,t)}`,r)}),e.exitCode=1,!1}return!0}function fileClient({label:t,segments:n,entry:r}){return async({url:i,token:a,yes:s})=>{let c=userHomeDir();if(!c){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let l=k(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:Br,serverEntry:r(i,a),yes:s})&&printResult({clientLabel:t,serverUrl:i,authDescription:`Bearer ${maskToken(a)}`,configPath:l})}}const claudeCodeHandler=async({url:e,token:t})=>{let command=t=>`claude mcp add --transport http --scope user ${Br} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Br,e,`--header`,`Authorization: Bearer ${t}`],maskedCommand:command(maskToken(t)),missingMessage:`The 'claude' CLI was not found on PATH. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) and re-run, or add the server manually:\n\n ${command(`<your-token>`)}`})&&printResult({clientLabel:`Claude Code`,serverUrl:e,authDescription:`Bearer ${maskToken(t)} (stored by Claude Code)`})};function vscodeHandler(e,t){return async({url:n,token:r})=>{let serverJson=e=>JSON.stringify({name:Br,type:`http`,url:n,headers:{Authorization:e}});await runCliInstall({binary:e,clientLabel:t,token:r,args:[`--add-mcp`,serverJson(`Bearer ${r}`)],maskedCommand:`${e} --add-mcp '${serverJson(`Bearer ${maskToken(r)}`)}'`,missingMessage:`The '${e}' CLI was not found on PATH. Install ${t} and re-run, or add the server manually:\n\n ${e} --add-mcp '${serverJson(`Bearer <your-token>`)}'`})&&printResult({clientLabel:t,serverUrl:n,authDescription:`Bearer ${maskToken(r)} (stored by ${t})`})}}const codexHandler=async({url:n})=>{let r=userHomeDir();if(!r){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let i=k(r,`.codex`,`config.toml`),a=[`mcp`,`add`,Br,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Br}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
|
|
172
|
+
`);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},Vr={"claude-code":claudeCodeHandler,cursor:fileClient({label:`Cursor`,segments:[`.cursor`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t)})}),vscode:vscodeHandler(`code`,`VS Code`),"vscode-insiders":vscodeHandler(`code-insiders`,`VS Code Insiders`),codex:codexHandler,kiro:fileClient({label:`Kiro`,segments:[`.kiro`,`settings`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t),disabled:!1,autoApprove:[]})}),antigravity:fileClient({label:`Antigravity`,segments:[`.gemini`,`antigravity`,`mcp_config.json`],entry:(e,t)=>({serverUrl:e,headers:bearer(t)})})},Hr=Object.keys(Vr);function isSupportedClient(e){return e in Vr}const Ur=new Set([`codex`]);function clientNeedsToken(e){return!Ur.has(e)}function getClientHandler(e){return Vr[e]}async function resolveApifyToken(t){if(t)return t;if(e.env.APIFY_TOKEN)return e.env.APIFY_TOKEN;let n=await getLocalUserInfo();return n.token?n.token:(error({message:`You are not logged in to Apify. Run 'apify login' first, or pass --token <api-token>.`}),e.exitCode=1,null)}var MCPInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Configure a local MCP client to use the Apify MCP server. Writes or merges a server entry named 'apify' into the client's config file, or runs the client's own 'mcp add' command when available.`;static group=`MCP`;static interactive=!0;static interactiveNote=`Prompts before overwriting an existing JSON config entry (cursor, kiro, antigravity). Pass --yes to overwrite without prompting. For clients delegated to their own CLI (claude-code, vscode, vscode-insiders, codex), overwrite behavior is controlled by that CLI.`;static examples=[{description:`Add Apify to Claude Code using the stored API token.`,command:`apify mcp install claude-code`},{description:`Add Apify to Cursor.`,command:`apify mcp install cursor`},{description:`Add only the 'search-actors' tool and the 'apify/rag-web-browser' Actor to VS Code.`,command:`apify mcp install vscode --tools search-actors,apify/rag-web-browser`},{description:`Add Apify to Codex CLI with an explicit token (non-interactive).`,command:`apify mcp install codex --token apify_api_xxxxx --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp-install`;static args={client:Z.string({required:!0,description:`Target MCP client. One of: ${Hr.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry without prompting.`),token:Y.string({char:`t`,description:`Apify API token to embed in the config. Defaults to the token from 'apify login'.`}),url:Y.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:Y.string({description:`Comma-separated tool IDs or Actor full names to expose. Forwarded as a '?tools=' query parameter.`})};async run(){let{client:t}=this.args,{token:n,url:r,tools:i,yes:a}=this.flags;if(!isSupportedClient(t)){error({message:`Unknown MCP client '${t}'. Supported clients: ${Hr.join(`, `)}.`}),e.exitCode=5;return}let s=``;if(clientNeedsToken(t)){let e=await resolveApifyToken(n);if(!e)return;s=e}await getClientHandler(t)({url:buildMcpUrl(r,i),token:s,yes:a})}},MCPIndexCommand=class extends ApifyCommand{static name=`mcp`;static description=`Configure the Apify MCP server in your AI client: Claude Code, Cursor, VS Code, Codex CLI, Kiro, or Antigravity.`;static group=`MCP`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp`;static subcommands=[MCPInstallCommand];async run(){this.printHelp()}},TopLevelPullCommand=class extends ActorsPullCommand{static name=`pull`},ToplevelPushCommand=class extends ActorsPushCommand{static name=`push`},RequestQueuesIndexCommand=class extends ApifyCommand{static name=`request-queues`;static description=`Manage Apify request queues. No subcommands are available yet.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-request-queues`;async run(){this.printHelp()}};const jsScript=e=>`
|
|
173
173
|
(async () => {
|
|
174
174
|
const [nodeModule, process, path, fs] = await Promise.all([
|
|
175
175
|
import('node:module'),
|
|
@@ -207,7 +207,7 @@ try:
|
|
|
207
207
|
print(${e}.__version__)
|
|
208
208
|
except:
|
|
209
209
|
print('n/a')
|
|
210
|
-
`,
|
|
210
|
+
`,Wr={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:e,project:t}){if(!t.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:t,moduleName:e}),H;let n;if(t.type===0)n=t.runtime.runtimeShorthand||`node`;else if(t.type===1||t.type===2)n=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:t,moduleName:e}),H;let r=Wr[n]?.(e);if(!r)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:t,moduleName:e}),H;try{let n=await st(t.runtime.executablePath,r,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:t,moduleName:e}),H):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:t,moduleName:e,version:n.stdout.trim()}),rt(n.stdout.trim()))}catch(n){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:t,moduleName:e,error:n}),H}}var RunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes Actor locally with simulated Apify environment variables.
|
|
211
211
|
Stores data in local '${en}' directory.\n\nNOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static group=`Local Actor Development`;static examples=[{description:`Run the Actor in the current directory with the stored input.`,command:`apify run`},{description:`Run and purge the default storage first (dataset, request queue, key-value store).`,command:`apify run --purge`},{description:`Run with inline JSON input (overrides the stored INPUT).`,command:`apify run --input '{"startUrls":[{"url":"https://example.com"}]}'`},{description:`Run with input from a file.`,command:`apify run --input-file ./input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-run`;static flags={purge:Y.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
|
|
212
212
|
For crawlee projects, this is the default behavior, and the flag is optional.
|
|
213
213
|
Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:Y.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:Y.string({description:[`Optional entrypoint for running with injected environment variables.`,`
|
|
@@ -217,11 +217,11 @@ Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,ex
|
|
|
217
217
|
`;break;default:u=t?`The input provided through the ${t.source} file is invalid. Please fix the following errors:\n`:`The input in your storage is invalid. Please fix the following errors:
|
|
218
218
|
`;break}if(t){let e={...a,...t.input},i=xt(s,r,e);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
|
|
219
219
|
`)}`);let c=`${Sn}${n}`,f=k(O(l),`${c}.json`);return await F(O(l),{recursive:!0}),await z(f,JSON.stringify(e,null,2)),{tempInputKey:c,tempInputFilePath:f}}if(!c)return await F(O(l),{recursive:!0}),await z(l,JSON.stringify(a,null,2)),{existingInput:c,inputFilePath:l,writtenAt:Date.now()};if(Je.getExtension(c.contentType)===`json`){let e=JSON.parse(c.body.toString(`utf-8`));if(Array.isArray(e))throw Error(`The input in your storage is invalid. It should be an object, not an array.`);let t={...a,...e},i=xt(s,r,t);if(i.length>0)throw Error(`${u}${i.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
|
|
220
|
-
`)}`);let f=`${Sn}${n}`,p=k(O(l),`${f}.json`);return await z(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const
|
|
221
|
-
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(
|
|
222
|
-
`),stdout:!0})}};const
|
|
220
|
+
`)}`);let f=`${Sn}${n}`,p=k(O(l),`${f}.json`);return await z(p,JSON.stringify(t,null,2)),{tempInputKey:f,tempInputFilePath:p}}return null}};const Gr=[N.READY,N.RUNNING],Kr=[N.ABORTING,N.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{static name=`abort`;static description=`Aborts an Actor run.`;static examples=[{description:`Abort a running Actor gracefully (up to 30s drain).`,command:`apify runs abort <runId>`},{description:`Force-abort a running Actor immediately.`,command:`apify runs abort <runId> --force`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-abort`;static args={runId:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.boolean({description:`Whether to force the run to abort immediately, instead of gracefully.`,default:!1,char:`f`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Gr.includes(n.status)){Kr.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const qr=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),Jr={"Actor compute units":`ACTOR_COMPUTE_UNITS`,"Dataset reads":`DATASET_READS`,"Dataset writes":`DATASET_WRITES`,"Key-value store reads":`KEY_VALUE_STORE_READS`,"Key-value store writes":`KEY_VALUE_STORE_WRITES`,"Key-value store lists":`KEY_VALUE_STORE_LISTS`,"Request queue reads":`REQUEST_QUEUE_READS`,"Request queue writes":`REQUEST_QUEUE_WRITES`,"Data transfer internal":`DATA_TRANSFER_INTERNAL_GBYTES`,"Data transfer external":`DATA_TRANSFER_EXTERNAL_GBYTES`,"Proxy residential data transfer":`PROXY_RESIDENTIAL_TRANSFER_GBYTES`,"Proxy SERPs":`PROXY_SERPS`};var RunsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about an Actor run.`;static examples=[{description:`Show a summary of a run.`,command:`apify runs info <runId>`},{description:`Show verbose details including usage breakdown.`,command:`apify runs info <runId> --verbose`},{description:`Emit the full run object as JSON.`,command:`apify runs info <runId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-info`;static args={runId:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.boolean({char:`v`,description:`Prints more in-depth information about the Actor run.`,default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(qr.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${G.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(K.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${K.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=`https://console.apify.com/actors/${r.actId}/runs/${r.id}`,_=`https://console.apify.com/storage/datasets/${r.defaultDatasetId}`,v=`https://console.apify.com/storage/key-value-stores/${r.defaultKeyValueStoreId}`;f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
|
|
221
|
+
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n){for(let e of Object.keys(Jr))qr.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});return}for(let[e,r]of Object.entries(Jr)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:qr.pushRow({"":e,Unit:i.toFixed(4),"USD Amount":this.formatUsd(a)});break;case`DATA_TRANSFER_INTERNAL_GBYTES`:case`DATA_TRANSFER_EXTERNAL_GBYTES`:case`PROXY_RESIDENTIAL_TRANSFER_GBYTES`:qr.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:qr.pushRow({"":e,Unit:i.toLocaleString(`en-US`),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}},RunsLogCommand=class extends ApifyCommand{static name=`log`;static description=`Prints the log of a specific run.`;static examples=[{description:`Print the log of a specific run to stdout.`,command:`apify runs log <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-log`;static args={runId:Z.string({required:!0,description:`The run ID to get the log from.`})};async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}info({message:`Log for run with ID "${e}":\n`,stdout:!0});try{await outputJobLog({job:n,apifyClient:t})}catch(t){error({message:`Failed to get log for run with ID "${e}": ${t.message}`})}}};const Yr=new Q({allColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`,`Build No.`,`Origin`],mandatoryColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`],columnAlignments:{Results:`right`,Usage:`right`,Took:`right`,"Build No.":`right`}});var RunsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all runs of the Actor.`;static examples=[{description:`List runs of the Actor in the current directory.`,command:`apify runs ls`},{description:`List runs of a specific Actor.`,command:`apify runs ls apify/hello-world`},{description:`List the 50 most recent runs in descending order.`,command:`apify runs ls --limit 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-ls`;static flags={offset:Y.integer({description:`Number of runs that will be skipped.`,default:0}),limit:Y.integer({description:`Number of runs that will be listed.`,default:10}),desc:Y.boolean({description:`Sort runs in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.string({description:`Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await c.actor(l.id).runs().list({desc:e,limit:n,offset:r});if(a){printJsonToStdout(u);return}if(!u.items.length){simpleLog({message:`There are no recent runs found for this Actor.`});return}let f=[`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} runs for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})`],p=new Map(await Promise.all(u.items.map(async e=>c.dataset(e.defaultDatasetId).get().then(n=>[e.id,t.yellow(n?.itemCount??0)],()=>[e.id,t.gray(`N/A`)]))));for(let e of u.items){let n;if(e.finishedAt){let r=e.finishedAt.getTime()-e.startedAt.getTime();n=t.gray(`${K.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${K.format(r,void 0,{left:``})}`)}Yr.pushRow({ID:t.gray(e.id),Status:prettyPrintStatus(e.status),Results:p.get(e.id)||t.gray(`N/A`),Usage:t.cyan(`$${(e.usageTotalUsd??0).toFixed(3)}`),"Started At":Dn.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Yr.render(+!i)),simpleLog({message:f.join(`
|
|
222
|
+
`),stdout:!0})}};const Xr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{static name=`resurrect`;static description=`Resurrects an aborted or finished Actor Run.`;static examples=[{description:`Resurrect a finished or aborted run.`,command:`apify runs resurrect <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-resurrect`;static args={runId:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n){error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!Xr.includes(n.status)){error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Zr=[N.SUCCEEDED,N.FAILED,N.ABORTED,N.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Deletes an Actor Run.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a finished or aborted run (prompts for confirmation).`,command:`apify runs rm <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-rm`;static args={runId:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}if(!Zr.includes(r.status)){error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await X({message:`Are you sure you want to delete this Actor Run?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of run "${e}" was canceled.`});return}try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsWaitCommand=class extends ApifyCommand{static name=`wait`;static description=`Waits for an Actor run to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
|
|
223
223
|
Returns exit code 0 only when the run SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a run to finish and return a non-zero exit code on failure.`,command:`apify runs wait <runId>`},{description:`Wait for a run and emit a structured JSON result.`,command:`apify runs wait <runId> --json`},{description:`Give up waiting after 5 minutes. Reports the real current status and exits with code 6 if the run is still running.`,command:`apify runs wait <runId> --timeout 300`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-wait`;static enableJsonFlag=!0;static args={runId:Z.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`How often to poll the platform, in seconds. Defaults to 2.`,required:!1})};async run(){let{runId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:`run`,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleRunUrl(l.actId,l.id),f=l.status===`SUCCEEDED`,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},`run`),m=`Gave up waiting after ${n}s; run is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`runs.wait`,timedOutWaiting:c,run:{id:l.id,status:l.status,exitCode:l.exitCode??null,url:u},...f?{}:{error:{phase:`run`,message:c?m:`Actor run did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Run`,value:l.status},{label:`Run ID`,value:l.id},{label:`Actor ID`,value:l.actId}];l.buildNumber&&g.push({label:`Build number`,value:l.buildNumber}),typeof l.exitCode==`number`&&g.push({label:`Exit code`,value:String(l.exitCode)});let _=[{label:`Run URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify run result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Run ended with status ${l.status}.`}),e.exitCode=p}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
|
|
224
|
-
Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const
|
|
224
|
+
Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Qr=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e){printJsonToStdout({keys:r});return}if(r.length===0){info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});return}for(let e of r)Qr.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Qr.render(1),stdout:!0})}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${W}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
225
225
|
Customize with --memory and --timeout flags.
|
|
226
226
|
`;static examples=[{description:`Run a task by name.`,command:`apify task run my-task`},{description:`Run a task by full ID with custom memory and timeout.`,command:`apify task run username/my-task --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-run`;static flags=SharedRunOnCloudFlags(`Task`);static enableJsonFlag=!0;static args={taskId:Z.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let e=await getLoggedClientOrThrow(),t=await getLocalUserInfo(),n=t.username||t.id,{id:r,userFriendlyId:i,title:a}=await this.resolveTaskId(e,n),s={waitForFinish:2};this.flags.build&&(s.build=this.flags.build),this.flags.timeout&&(s.timeout=this.flags.timeout),this.flags.memory&&(s.memory=this.flags.memory);let c,l=runActorOrTaskOnCloud(e,{actorOrTaskData:{id:r,userFriendlyId:i,title:a},runOptions:s,type:`Task`,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of l)c=e;await finalizeRun({apifyClient:e,run:c,operation:`task-run`,json:this.flags.json})}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run saved Apify tasks (named Actor configurations). Only 'task run' is available; create and manage tasks in Apify Console.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task`;static subcommands=[TaskRunCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{static name=`disable`;static description=`Disables telemetry.`;static examples=[{description:`Opt out of anonymous telemetry.`,command:`apify telemetry disable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{static name=`enable`;static description=`Enables telemetry.`;static examples=[{description:`Opt in to anonymous telemetry.`,command:`apify telemetry enable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{static name=`telemetry`;static description=`Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.`;static group=`Utilities`;static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;static subcommands=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
|
|
227
227
|
|
|
@@ -231,5 +231,5 @@ When no path is provided, validates all schemas found in '${W}':
|
|
|
231
231
|
- Input schema (from "input" key or default locations)
|
|
232
232
|
- Dataset schema (from "storages.dataset")
|
|
233
233
|
- Output schema (from "output")
|
|
234
|
-
- Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),bt(new wn({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const
|
|
235
|
-
//# sourceMappingURL=_register-
|
|
234
|
+
- Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${W}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});e&&(n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`}),bt(new wn({strict:!1}),e),success({message:`Input schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${W}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${W}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const $r=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],ei=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,$r as n,processVersionCheck as r,ei as t};
|
|
235
|
+
//# sourceMappingURL=_register-DqVo7fm7.js.map
|