apify-cli 1.6.3-beta.14 → 1.6.3-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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 oe,sep as se}from"node:path";import ce from"string-width";import le from"strip-ansi";import{once as ue}from"node:events";import{homedir as de,platform as fe}from"node:os";import pe from"ci-info";import{ACTOR_ENV_VARS as A,ACTOR_JOB_STATUSES as j,ACTOR_JOB_TERMINAL_STATUSES as me,ACTOR_NAME as he,ACTOR_SOURCE_TYPES as ge,APIFY_ENV_VARS as M,KEY_VALUE_STORE_KEYS as _e,LOCAL_ACTOR_ENV_VARS as ve,LOCAL_STORAGE_SUBDIRS as ye,MAX_MULTIFILE_BYTES as be,META_ORIGINS as xe,SOURCE_FILE_FORMATS as Se}from"@apify/consts";import{jaroWinkler as Ce}from"@skyra/jaro-winkler";import we from"js-levenshtein";import{createHmacSignature as Te,cryptoRandomObjectId as Ee}from"@apify/utilities";import{execSync as De,spawn as Oe}from"node:child_process";import{access as ke,lstat as Ae,mkdir as N,readFile as P,readdir as F,rename as je,rm as Me,stat as I,symlink as Ne,unlink as Pe,writeFile as L}from"node:fs/promises";import{get as Fe}from"node:https";import{finished as Ie,pipeline as Le}from"node:stream/promises";import{DurationFormatter as Re,Time as ze,TimeTypes as R}from"@sapphire/duration";import{Timestamp as Be}from"@sapphire/timestamp";import Ve from"adm-zip";import He from"ajv/dist/2019.js";import{ApifyClient as Ue,DownloadItemsFormat as z}from"apify-client";import{ZipArchive as We}from"archiver";import Ge,{AxiosHeaders as Ke}from"axios";import qe from"escape-string-regexp";import Je from"ignore";import{getEncoding as Ye}from"istextorbinary";import Xe,{Mime as Ze}from"mime";import Qe from"mime/types/other.js";import $e from"mime/types/standard.js";import{glob as et}from"tinyglobby";import{rimraf as tt}from"rimraf";import{Result as nt,err as rt,none as B,ok as V,some as it}from"@sapphire/result";import at from"configparser";import ot from"@inquirer/input";import st from"is-ci";import{execa as ct}from"execa";import lt from"which";import{calculateRunDynamicMemory as ut}from"@apify/actor-memory-expression";import{Separator as dt,createPrompt as ft,isEnterKey as pt,makeTheme as mt,useKeypress as ht,usePrefix as gt,useState as _t}from"@inquirer/core";import{MemoryStorage as vt}from"@crawlee/memory-storage";import{compile as yt}from"json-schema-to-typescript";import{cloneDeep as H}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 Et from"jju";import Dt from"tiged";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 link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let 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.14`,hash:`d9b60dce5ad49f6a72abbbb4e2f497b573865f2b`,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(`
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 oe,sep as se}from"node:path";import ce from"string-width";import le from"strip-ansi";import{once as ue}from"node:events";import{homedir as de,platform as fe}from"node:os";import pe from"ci-info";import{ACTOR_ENV_VARS as A,ACTOR_JOB_STATUSES as j,ACTOR_JOB_TERMINAL_STATUSES as me,ACTOR_NAME as he,ACTOR_SOURCE_TYPES as ge,APIFY_ENV_VARS as M,KEY_VALUE_STORE_KEYS as _e,LOCAL_ACTOR_ENV_VARS as ve,LOCAL_STORAGE_SUBDIRS as ye,MAX_MULTIFILE_BYTES as be,META_ORIGINS as xe,SOURCE_FILE_FORMATS as Se}from"@apify/consts";import{jaroWinkler as Ce}from"@skyra/jaro-winkler";import we from"js-levenshtein";import{createHmacSignature as Te,cryptoRandomObjectId as Ee}from"@apify/utilities";import{execSync as De,spawn as Oe}from"node:child_process";import{access as ke,lstat as Ae,mkdir as N,readFile as P,readdir as F,rename as je,rm as Me,stat as I,symlink as Ne,unlink as Pe,writeFile as L}from"node:fs/promises";import{get as Fe}from"node:https";import{finished as Ie,pipeline as Le}from"node:stream/promises";import{DurationFormatter as Re,Time as ze,TimeTypes as R}from"@sapphire/duration";import{Timestamp as Be}from"@sapphire/timestamp";import Ve from"adm-zip";import He from"ajv/dist/2019.js";import{ApifyClient as Ue,DownloadItemsFormat as z}from"apify-client";import{ZipArchive as We}from"archiver";import Ge,{AxiosHeaders as Ke}from"axios";import qe from"escape-string-regexp";import Je from"ignore";import{getEncoding as Ye}from"istextorbinary";import Xe,{Mime as Ze}from"mime";import Qe from"mime/types/other.js";import $e from"mime/types/standard.js";import{glob as et}from"tinyglobby";import{rimraf as tt}from"rimraf";import{Result as nt,err as rt,none as B,ok as V,some as it}from"@sapphire/result";import at from"configparser";import ot from"@inquirer/input";import st from"is-ci";import{execa as ct}from"execa";import lt from"which";import{calculateRunDynamicMemory as ut}from"@apify/actor-memory-expression";import{Separator as dt,createPrompt as ft,isEnterKey as pt,makeTheme as mt,useKeypress as ht,usePrefix as gt,useState as _t}from"@inquirer/core";import{MemoryStorage as vt}from"@crawlee/memory-storage";import{compile as yt}from"json-schema-to-typescript";import{cloneDeep as H}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 link(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.blue(e.message),e.url]})}function detectInstallMethod(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let 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.15`,hash:`6cdcc1125b0aab0aa385202f32c4d44862261fcb`,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}){ce(e.join(` `).split(`
@@ -91,7 +91,7 @@ Reads input from local key-value store by default.`;static group=`Apify Console`
91
91
  `));break}case`FREE`:u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:{let n=e.pricingModel;u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(n)})`)}`)}}}else u.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);if((c.seoTitle||c.seoDescription)&&(u.push(``,t.yellow(`SEO information:`)),c.seoTitle&&u.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&u.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`)),c.taggedBuilds){u.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&u.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&u.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:u.join(`
92
92
  `),stdout:!0})}};function prettyPrintStatus(e){switch(e){case`READY`:return t.green(`Ready`);case`RUNNING`:return t.blue(`Running`);case`SUCCEEDED`:return t.green(`Succeeded`);case`FAILED`:return t.red(`Failed`);case`ABORTING`:return t.yellow(`Aborting`);case`ABORTED`:return t.red(`Aborted`);case`TIMING-OUT`:return t.yellow(`Timing Out`);case`TIMED-OUT`:return t.red(`Timed Out`);default:return t.gray(e.split(`-`).map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(` `))}}const ir={"TIMED-OUT":t.gray(`after`),"TIMING-OUT":t.gray(`after`),ABORTED:t.gray(`after`),ABORTING:t.gray(`after`),FAILED:t.gray(`after`),READY:t.gray(`for`),RUNNING:t.gray(`for`),SUCCEEDED:t.gray(`after`)},ar=new Q({allColumns:[`Name`,`Runs`,`Last run started at`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run status`,`Last run duration`],columnAlignments:{Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},hiddenColumns:[`_Small_LastRunText`],breakpointOverrides:{small:{"Last run status":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}}),or=new Q({allColumns:[`Name`,`Modified at`,`Builds`,`Default build`,`Runs`,`Last run`,`Last run status`,`Last run duration`,`_Small_LastRunText`],mandatoryColumns:[`Name`,`Runs`,`Last run`,`Last run duration`],hiddenColumns:[`_Small_LastRunText`],columnAlignments:{Builds:`right`,Runs:`right`,"Last run duration":`right`,Name:`left`,"Last run status":`center`},breakpointOverrides:{small:{"Last run":{label:`Last run`,valueFrom:`_Small_LastRunText`}}}});var ActorsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints a list of recently executed Actors or Actors you own.`;static examples=[{description:`List Actors you recently interacted with.`,command:`apify actors ls`},{description:`List Actors you own, newest first.`,command:`apify actors ls --my --desc`},{description:`List the next page of 50 Actors.`,command:`apify actors ls --limit 50 --offset 50`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-ls`;static flags={my:Y.boolean({description:`Whether to list Actors made by the logged in user.`,default:!1}),offset:Y.integer({description:`Number of Actors that will be skipped.`,default:0}),limit:Y.integer({description:`Number of Actors that will be listed.`,default:20}),desc:Y.boolean({description:`Sort Actors in descending order.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,my:i,json:a}=this.flags,s=await getLoggedClientOrThrow(),c=await s.actors().list({limit:n,offset:r,desc:e,my:i});if(c.count===0){if(a){printJsonToStdout(c);return}info({message:i?`You don't have any Actors yet!`:`There are no recent Actors used by you.`,stdout:!0});return}let l={...c,items:await Promise.all(c.items.map(async e=>{let t=await s.actor(e.id).get(),n=await s.actor(e.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...e,actor:t??null,lastRun:n.items[0]??null}}))};if(l.items=i?this.sortByModifiedAt(l.items):this.sortByLastRun(l.items),a){printJsonToStdout(l);return}let u=i?or:ar,f=l.items.reduce((e,t)=>{let n=`${t.username}/${t.name}`;return n.length>e?n.length:e},0)+2+6;for(let e of l.items){let n=e.stats.lastRunStartedAt?Dn.display(e.stats.lastRunStartedAt):``,r=e.lastRun?(()=>{if(e.lastRun.finishedAt)return K.format(e.lastRun.finishedAt.getTime()-e.lastRun.startedAt.getTime());let t=Date.now()-e.lastRun.startedAt.getTime();return`${K.format(t)}…`})():``,i=e.actor?(()=>{let n=Object.entries(e.actor.taggedBuilds??{}).find(([t,n])=>n.buildNumber===e.actor.defaultRunOptions.build||t===e.actor.defaultRunOptions.build);return n?`${t.yellow(n[0])} / ${t.cyan(n[1].buildNumber??e.actor.defaultRunOptions.build)}`:t.gray(`Unknown`)})():t.gray(`Unknown`),a=(()=>{if(e.lastRun){let n=[prettyPrintStatus(e.lastRun.status)];if(r&&n.push(ir[e.lastRun.status],t.cyan(r)),e.lastRun.finishedAt){let r=Date.now()-e.lastRun.finishedAt.getTime();r<ze.Week?n.push(`
93
93
  `,t.gray(`${K.format(r)} ago`)):n.push(`
94
- `,t.gray(`On`,On.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?tr:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":Dn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?tr:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await Ge.get(e,{responseType:`arraybuffer`}),r=new Ve(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:k(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${O(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Et.parse(e);n.name=f.name,E(`${g}/${t.name}`,Et.update(e,n))}else E(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h,[t,n]=e.split(`#`),r,i;n&&([r,i]=n.split(`:`));let a=t;i&&(a+=`/${i}`),r&&(a+=`#${r}`);let s=Dt(a);try{await s.clone(g)}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const sr=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>sr)throw Error(`Secret value has to be string with maximum length ${sr}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
94
+ `,t.gray(`On`,On.display(e.lastRun.finishedAt)))}return n.join(` `)}return``})();u.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Runs:Q.isSmallTerminal()&&f>=56?tr:t.cyan(`${e.stats?.totalRuns??0}`),"Last run started at":n,"Last run":n,"Last run status":e.lastRun?prettyPrintStatus(e.lastRun.status):``,"Modified at":Dn.display(e.modifiedAt),Builds:e.actor?t.cyan(e.actor.stats.totalBuilds):t.gray(`Unknown`),"Last run duration":Q.isSmallTerminal()?tr:t.cyan(r),"Default build":i,_Small_LastRunText:a})}simpleLog({message:u.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((e,t)=>{let n=new Date(e.modifiedAt);return new Date(t.modifiedAt).getTime()-n.getTime()})}sortByLastRun(e){return e.sort((e,t)=>{let n=new Date(e.stats?.lastRunStartedAt??`1970-01-01T00:00Z`);return new Date(t.stats?.lastRunStartedAt??`1970-01-01T00:00Z`).getTime()-n.getTime()})}};const extractGitHubZip=async(e,t)=>{let{data:n}=await Ge.get(e,{responseType:`arraybuffer`}),r=new Ve(Buffer.from(n,`binary`));r.extractEntryTo(r.getEntries()[0].entryName,t,!1)};var ActorsPullCommand=class extends ApifyCommand{static name=`pull`;static description=`Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.`;static group=`Local Actor Development`;static examples=[{description:`Pull the Actor linked to the current directory from the Apify platform.`,command:`apify pull`},{description:`Pull a specific Actor by its full name into a target directory.`,command:`apify pull apify/hello-world --dir ./hello-world`},{description:`Pull a specific version of an Actor.`,command:`apify pull apify/hello-world --version 1.2`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-pull`;static flags={version:Y.string({char:`v`,description:`Actor version number which will be pulled, e.g. 1.2. Default: the highest version.`,required:!1}),dir:Y.string({description:`Directory where the Actor should be pulled to.`,required:!1})};static args={actorId:Z.string({required:!1,description:`Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.`})};async run(){let t=e.cwd(),n=await useActorConfig({cwd:t});if(n.isErr()){error({message:n.unwrapErr().message}),e.exitCode=5;return}let{config:r}=n.unwrap(),i=await getLocalUserInfo(),a=await getLoggedClientOrThrow(),s=!this.args.actorId,c=i.username||i.id,u=this.args?.actorId||r?.id||(r?.name?`${c}/${r.name}`:void 0);if(!u)throw Error(`Cannot find Actor in this directory.`);let f;try{f=await a.actor(u).get()}catch{throw Error(`Cannot find Actor with ID/name '${u}' in your account.`)}if(!f)throw Error(`Cannot find Actor with ID/name '${u}' in your account.`);let{name:p,versions:m}=f,throwMissingSourceCodeAccessError=()=>{throw Error(`You cannot pull source code of this Actor because you do not have permission to do so.`)};if(!f.versions.length)throw Error(`Actor ${u} has no versions.`);let h=null;if(this.flags.version&&(h=m.find(e=>e.versionNumber===this.flags.version),!h))throw Error(`Cannot find version ${this.flags.version} of Actor ${u}.`);h||=m.reduce((e,t)=>l(`${t.versionNumber}.0`,`${e.versionNumber}.0`)?t:e);let g=s?t:k(t,this.flags.dir??p);if(b(g,{recursive:!0}),!s&&C(g).length!==0){error({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}let{sourceType:_}=h;switch(_){case`TARBALL`:h.tarballUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(h.tarballUrl,g);break;case`SOURCE_FILES`:{h.sourceFiles||throwMissingSourceCodeAccessError();let{sourceFiles:e}=h;for(let t of e)if(b(`${g}/${O(t.name)}`,{recursive:!0}),!t.folder){let e=t.format===`BASE64`?Buffer.from(t.content,`base64`).toString():t.content;if(t.name===W){let n=Dt.parse(e);n.name=f.name,E(`${g}/${t.name}`,Dt.update(e,n))}else E(`${g}/${t.name}`,e)}break}case`GIT_REPO`:{h.gitRepoUrl||throwMissingSourceCodeAccessError();let{gitRepoUrl:e}=h;try{await Et(`git:${e}`,{dir:g})}catch(t){throw Error(`Failed to pull Actor from ${e}. ${t.message}`)}break}case`GITHUB_GIST`:h.gitHubGistUrl||throwMissingSourceCodeAccessError(),await extractGitHubZip(`${h.gitHubGistUrl}/archive/master.zip`,g);break;default:throw Error(`Unknown source type: ${_}`)}success({message:s?`Actor ${p} updated at ${g}/`:`Pulled to ${g}/`})}};const sr=5e4,getSecretsFile=()=>{try{return JSON.parse(S(SECRETS_FILE_PATH(),`utf-8`))||{}}catch{return{}}},writeSecretsFile=e=>(ensureApifyDirectory(SECRETS_FILE_PATH()),E(SECRETS_FILE_PATH(),JSON.stringify(e,null,` `)),e),addSecret=(e,t)=>{let n=getSecretsFile();if(n[e])throw Error(`Secret with name ${e} already exists. Call "apify secrets rm ${e}" to remove it.`);if(typeof e!=`string`||e.length>100)throw Error(`Secret name has to be string with maximum length 100.`);if(typeof t!=`string`||t.length>sr)throw Error(`Secret value has to be string with maximum length ${sr}.`);return n[e]=t,writeSecretsFile(n)},removeSecret=e=>{let t=getSecretsFile();if(!t[e])throw Error(`Secret with name ${e} doesn't exist.`);delete t[e],writeSecretsFile(t)},isSecretKey=e=>RegExp(`^@.{1}`).test(e),replaceSecretsValue=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r={},i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r[n]=t[a]:i.push(a)}else r[n]=e[n]}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
95
95
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
96
96
  If you want to skip missing secrets, run the command with the --allow-missing-secrets flag.`)}return r},transformEnvToEnvVars=(e,t,{allowMissing:n=!1}={})=>{t||=getSecretsFile();let r=[],i=[];if(Object.keys(e).forEach(n=>{if(isSecretKey(e[n])){let a=e[n].replace(RegExp(`^@`),``);t[a]?r.push({name:n,value:t[a],isSecret:!0}):i.push(a)}else r.push({name:n,value:e[n]})}),i.length>0){let e=i.map(e=>` - ${e}`).join(`
97
97
  `);if(n)for(let e of i)warning({message:`Value for ${e} not found in local secrets. Set it by calling "apify secrets add ${e} [SECRET_VALUE]"`});else throw Error(`The following secrets are missing:\n${e}\n\nSet them by calling "apify secrets add <SECRET_NAME> <SECRET_VALUE>" for each missing secret.
@@ -159,8 +159,8 @@ Creates the '${W}' file and the '${en}' directory in the current directory, but
159
159
  `),``,g].join(`
160
160
  `),stdout:!0})}};const Pr=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)Pr.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Pr.render(1),stdout:!0})}};const Fr=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;Fr.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:Fr.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.
161
161
 
162
- 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 P(t,`utf-8`):``,c=s.trim(),l;if(c){let e;try{e=Et.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
163
- `)[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=Et.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Et.stringify(e,{mode:`json`,indent:2})}\n`}await N(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await L(u,l,`utf-8`),await je(u,t)}catch(e){throw await Me(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 Ir=`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(`
162
+ 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 P(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(`
163
+ `)[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 N(O(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await L(u,l,`utf-8`),await je(u,t)}catch(e){throw await Me(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 Ir=`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(`
164
164
  `)})}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 lt(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await ct(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:Ir,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 ${Ir} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Ir,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:Ir,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`,Ir,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Ir}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
165
165
  `);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>`})},Lr={"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)})})},Rr=Object.keys(Lr);function isSupportedClient(e){return e in Lr}const zr=new Set([`codex`]);function clientNeedsToken(e){return!zr.has(e)}function getClientHandler(e){return Lr[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: ${Rr.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: ${Rr.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=>`
166
166
  (async () => {
@@ -225,4 +225,4 @@ When no path is provided, validates all schemas found in '${W}':
225
225
  - Dataset schema (from "storages.dataset")
226
226
  - Output schema (from "output")
227
227
  - 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 Yr=[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],Xr=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Yr as n,processVersionCheck as r,Xr as t};
228
- //# sourceMappingURL=_register-C5enDfU3.js.map
228
+ //# sourceMappingURL=_register-B4I2fpwj.js.map