apify-cli 1.6.3-beta.20 → 1.6.3-beta.22
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 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.
|
|
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.22`,hash:`bb5b454eb550cde0a59b6996e3f2a112bca03f1d`,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(`
|
|
@@ -24,7 +24,7 @@ import e from"node:process";import t from"chalk";import n from"indent-string";im
|
|
|
24
24
|
`)}}}static buildMessageFromFlagData(e){let n=[`Flag ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`];return e.ambiguousFlag?(n.push(`is ambiguous (meaning the provided value could be interpreted as a flag too).`),e.ambiguousMessage?n.push(`\n${e.ambiguousMessage.split(`
|
|
25
25
|
`).map(e=>` ${e}`).join(`
|
|
26
26
|
`)}`):n.push(`To solve this, provide the flag like this: --${e.name}=<value>`)):e.expectsValue?n.push(`expects a value`):n.push(`does not take an argument`),n.map(e=>t.gray(e)).join(` `)}static into(e,t){if(e instanceof CommandError)return e;if(e instanceof Error&&`code`in e){let n=e;switch(n.code){case`ERR_PARSE_ARGS_INVALID_OPTION_VALUE`:return new CommandError({code:0,message:n.message,command:t});case`ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`:return new CommandError({code:1,message:n.message,command:t});case`ERR_PARSE_ARGS_UNKNOWN_OPTION`:return new CommandError({code:2,message:n.message,command:t});default:return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}}return new CommandError({code:9,message:`Unknown error: ${e instanceof Error?e.message:String(e)}`,command:t})}};function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Zt=c(y);let Qt;async function useStdin(){if(Qt)return Qt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Zt(0).then(t=>{if(cliDebugPrint(`useStdin`,{stat:t,isRegularFile:t.isFile(),isDirectory:t.isDirectory(),isBlockDevice:t.isBlockDevice(),isCharDevice:t.isCharacterDevice(),isSymbolicLink:t.isSymbolicLink(),isFIFO:t.isFIFO(),isSocket:t.isSocket()}),e.platform===`win32`){if((t.mode&h.S_IFIFO)===h.S_IFIFO)return 100;if(t.isFile())return 50}return t.isFIFO()||t.isFile()||(t.isSocket()?50:!1)}).catch(()=>!1);return cliDebugPrint(`useStdin`,{hasData:n.hasData,waitDelay:n.waitDelay,isTTY:n.isTTY,pipedIn:r,readableEnded:t.readableEnded}),(!t.isTTY||r!==!1&&(t.isTTY!==void 0||!t.readableEnded))&&(n.hasData=!0),typeof r==`number`&&(n.waitDelay=r),Qt=n,n}async function readStdin(){let e=await useStdin(),{hasData:t,waitDelay:n,stream:r}=e;if(!t)return;let i=[],a=new AbortController,s=null;n&&(s=setTimeout(()=>{a.abort()},n).unref()),r.on(`data`,e=>{i.push(e),s&&=(clearTimeout(s),null)});try{await ce(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var $t={node:`>=20`};const en=`storage`,tn={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},nn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=k(le(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?k(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>k(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),rn=`.actor`,W=k(rn,`actor.json`),an=$t.node,on=de.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,sn={"X-Apify-Request-Origin":de.isCI?ye.CI:ye.CLI,...on&&{"X-Apify-Github-Actions-Run-Url":on}},cn=`3.9.0`;function migrateStateV0ToV1$1(e){if(e.version&&e.version>=1)return!1;let t=e;if(t.latestNpmVersionCheckedAt){let n=new Date(t.latestNpmVersionCheckedAt).getTime(),r=t.latestNpmVersion;cliDebugPrint(`LocalStateV0ToV1`,`Migrating state from v0 to v1`,{oldState:e,newState:{versionCheck:{lastChecked:n,lastVersion:r}}}),updateLocalState({version:1},e=>{e.versionCheck={lastChecked:n,lastVersion:r}})}return!0}const ln={version:1};function useLocalState(){let e=STATE_FILE_PATH();if(!v(e))return ln;let t=JSON.parse(S(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n),b(O(STATE_FILE_PATH()),{recursive:!0}),E(STATE_FILE_PATH(),JSON.stringify(n,null,` `))}const un=useCLIMetadata(),dn=`Apify CLI/${un.version} (https://github.com/apify/apify-cli)`,fn=[`https://1.1.1.1`,`https://8.8.8.8`];async function isOnline(e=500){let t=new AbortController,n=setTimeout(()=>{t.abort()},e),r=await Promise.any(fn.map(async e=>fetch(e,{signal:t.signal,headers:{"User-Agent":dn},keepalive:!1}))).catch(()=>null);return clearTimeout(n),r?r.ok?(cliDebugPrint(`isOnline`,{state:`online`,site:r.url}),!0):(cliDebugPrint(`isOnline`,{state:`offline`}),!1):(cliDebugPrint(`isOnline`,{state:`timeout`}),!1)}async function getLatestVersion(e){let t=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/latest`,{headers:{"User-Agent":dn}});if(!t.ok)return cliDebugPrint(`useCLIVersionCheck`,`Failed to fetch latest version`,{statusCode:t.status,body:await t.text()}),warning({message:`Failed to fetch latest version of Apify CLI, using the cached version instead.`}),null;let n=(await t.json()).tag_name.replace(/^v/,``);return cliDebugPrint(`useCLIVersionCheck`,`Fetched latest version`,{version:n}),updateLocalState(e,e=>{e.versionCheck={lastChecked:Date.now(),lastVersion:n}}),n}function shouldSkipVersionCheck(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&![`0`,`false`].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}async function useCLIVersionCheck(e=!1){let t=useLocalState(),n=!t.versionCheck||Date.now()-t.versionCheck.lastChecked>864e5,r=e||n&&await isOnline(),i=r?await getLatestVersion(t):t.versionCheck?.lastVersion;if(!i)return{currentVersion:un.version,latestVersion:`unknown`,shouldUpdate:!1,cacheHit:!1};let a=l(i,un.version);return{currentVersion:un.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...J.entries()].sort(([e],[t])=>e.localeCompare(t)),n=e.toLowerCase();return t.map(([e,t])=>{let r=e.toLowerCase(),i=e.split(` `),a=i[i.length-1].toLowerCase(),s=t.aliases?.includes(a)||t.hiddenAliases?.includes(a)||!1,c=Se(n,r),l=xe(n,r),u=c<=2||l>=.975;return u?(cliDebugPrint(`useCommandSuggestions`,{inputString:n,lowercased:r,matches:u,levenshtein:c,jaroWinkler:l}),s?{string:`${r} (alias for ${t.name})`,distance:l}:{string:`${r}`,distance:l}):null}).filter(e=>e!==null).sort((e,t)=>t.distance-e.distance).map(e=>e.string)}const pn=await readStdin(),mn=useCLIMetadata(),hn=`Apify CLI/${mn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){mn.installMethod!==`bundle`&&(p(e.version,an)||(error({message:`${t} CLI requires Node.js version ${an}. Your current version is ${e.version}.`}),e.exit(1)))}function printCLIVersionAndExitIfFlagUsed(t){t.values.version===!0&&t.positionals.length===0&&(console.log(mn.fullVersionString),e.exit(0))}function printHelpAndExitIfFlagUsedOrNoCommandPassed(t,n){(t.values.help===!0&&t.positionals.length===0||t.positionals.length===0)&&(console.log(renderMainHelpMenu(n)),e.exit(0))}function handleCommandNotFound(n){let r=useCommandSuggestions(String(n)),i=t.gray(`Command ${t.whiteBright(n)} not found`);r.length&&(i+=`
|
|
27
|
-
`,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i}),e.exit(1)}async function runVersionCheck(e,t){let n=J.get(`upgrade`);if([n.name,...n.aliases??[]].some(e=>t===e)){cliDebugPrint(`[VersionCheckMiddleware]`,`upgrade command detected, skipping version check`);return}if(shouldSkipVersionCheck()){cliDebugPrint(`[VersionCheckMiddleware]`,`skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set`);return}await internalRunCommand(e,n,{flags_internalAutomaticCall:!0})}async function runCLI(t){cliDebugPrint(`CLIMetadata`,{...mn,fullVersionString:mn.fullVersionString,argv:e.argv,cwd:e.cwd(),execPath:e.execPath});let n=e.argv.slice(2);cliDebugPrint(`ProcessArgv`,n);let r=s({allowPositionals:!0,strict:!1,options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`}},args:n});printCLIVersionAndExitIfFlagUsed(r),printHelpAndExitIfFlagUsedOrNoCommandPassed(r,t),await runVersionCheck(t,r.positionals[0]),cliDebugPrint(`TopLevelOptions`,r);let i=r.positionals[0],a=-1;if(J.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=J.get(`${i} ${r.positionals[1]}`);e&&!e.args&&(a=2)}}if(a!==-1){let e=r.positionals[a],t=n.indexOf(e);t!==-1&&n.splice(t,1),!n.includes(`--help`)&&!n.includes(`-h`)&&n.push(`--help`),r.positionals.splice(a,1),r.values.help=!0}let c=r.positionals[1],l=!1,u=J.get(i);if(!u)return handleCommandNotFound(i);let f=u;if(u.subcommands?.length){if(!c)return u.printHelp();l=!0,f=J.get(`${i} ${c}`)}if(!f)return handleCommandNotFound(`${i} ${c}`);let p=[...n],m=p.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,m),p.splice(m,1),l){let e=p.indexOf(c);cliDebugPrint(`SubcommandNameIndex`,e),p.splice(e,1)}cliDebugPrint(`RebuiltArgs`,p),cliDebugPrint(`CommandToRun`,f);let h=new f(t,l?`${u.name} ${c}`:u.name,i,l?c:void 0),g=h._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,g);try{let e=s({...g,args:p});await h._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:U.into(t,f).getPrettyMessage()}),e.exit(1)}}const gn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of gn)if(process.env[e])return t}function detectCi(){return de.isCI?{isCi:!0,ciProvider:de.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await I(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await z(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(j).reduce((e,t)=>(e=k(e,t),v(e)||b(e),e),e)},rimrafPromised=async e=>{await $e(e)},deleteFile=async e=>{(await R(e)).isFile()&&await Me(e)};function ensureApifyDirectory(e){b(O(e),{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>R(k(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),_n=`token`,vn=`proxy-password`;let yn,bn,xn;async function loadKeyringModule(){
|
|
27
|
+
`,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i}),e.exit(1)}async function runVersionCheck(e,t){let n=J.get(`upgrade`);if([n.name,...n.aliases??[]].some(e=>t===e)){cliDebugPrint(`[VersionCheckMiddleware]`,`upgrade command detected, skipping version check`);return}if(shouldSkipVersionCheck()){cliDebugPrint(`[VersionCheckMiddleware]`,`skipping version check because APIFY_CLI_SKIP_UPDATE_CHECK is set`);return}await internalRunCommand(e,n,{flags_internalAutomaticCall:!0})}async function runCLI(t){cliDebugPrint(`CLIMetadata`,{...mn,fullVersionString:mn.fullVersionString,argv:e.argv,cwd:e.cwd(),execPath:e.execPath});let n=e.argv.slice(2);cliDebugPrint(`ProcessArgv`,n);let r=s({allowPositionals:!0,strict:!1,options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`}},args:n});printCLIVersionAndExitIfFlagUsed(r),printHelpAndExitIfFlagUsedOrNoCommandPassed(r,t),await runVersionCheck(t,r.positionals[0]),cliDebugPrint(`TopLevelOptions`,r);let i=r.positionals[0],a=-1;if(J.get(i)?.subcommands?.length){if(r.positionals[1]?.toLowerCase()===`help`)a=1;else if(r.positionals[2]?.toLowerCase()===`help`){let e=J.get(`${i} ${r.positionals[1]}`);e&&!e.args&&(a=2)}}if(a!==-1){let e=r.positionals[a],t=n.indexOf(e);t!==-1&&n.splice(t,1),!n.includes(`--help`)&&!n.includes(`-h`)&&n.push(`--help`),r.positionals.splice(a,1),r.values.help=!0}let c=r.positionals[1],l=!1,u=J.get(i);if(!u)return handleCommandNotFound(i);let f=u;if(u.subcommands?.length){if(!c)return u.printHelp();l=!0,f=J.get(`${i} ${c}`)}if(!f)return handleCommandNotFound(`${i} ${c}`);let p=[...n],m=p.indexOf(i);if(cliDebugPrint(`CommandNameIndex`,m),p.splice(m,1),l){let e=p.indexOf(c);cliDebugPrint(`SubcommandNameIndex`,e),p.splice(e,1)}cliDebugPrint(`RebuiltArgs`,p),cliDebugPrint(`CommandToRun`,f);let h=new f(t,l?`${u.name} ${c}`:u.name,i,l?c:void 0),g=h._buildParseArgsOption();cliDebugPrint(`ParserOptionsForCommand`,g);try{let e=s({...g,args:p});await h._run(e),cliDebugPrint(`CommandArgsResult`,e)}catch(t){error({message:U.into(t,f).getPrettyMessage()}),e.exit(1)}}const gn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of gn)if(process.env[e])return t}function detectCi(){return de.isCI?{isCi:!0,ciProvider:de.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await I(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await z(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(j).reduce((e,t)=>(e=k(e,t),v(e)||b(e),e),e)},rimrafPromised=async e=>{await $e(e)},deleteFile=async e=>{(await R(e)).isFile()&&await Me(e)};function ensureApifyDirectory(e){b(O(e),{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>R(k(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),_n=`token`,vn=`proxy-password`;let yn,bn,xn;async function loadKeyringModule(){return yn===void 0&&(yn=await importKeyringModule()),yn}async function importKeyringModule(){if(useCLIMetadata().installMethod===`bundle`)try{let e=await import(`__APIFY_KEYRING_NATIVE_SUBPACKAGE__`),t=e.Entry??e.default?.Entry;return t?{Entry:t}:null}catch(e){return cliDebugPrint(`credentials`,`failed to load bundled keyring`,e),null}try{return await import(`@napi-rs/keyring`)}catch(e){return cliDebugPrint(`credentials`,`failed to load @napi-rs/keyring`,e),null}}async function getBackend(){return bn||(bn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`||readAuthFile().secretsBackend===`file`?`file`:await loadKeyringModule()?`keyring`:`file`)(),bn)}function downgradeBackendToFile(){bn=Promise.resolve(`file`)}function readAuthFile(){if(!v(AUTH_FILE_PATH()))return{};try{let e=S(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e)}catch{return{}}}function writeAuthFile(e){ensureApifyDirectory(AUTH_FILE_PATH()),E(AUTH_FILE_PATH(),JSON.stringify(e,null,` `),{mode:384})}async function getKeyringEntry(e){let t=await loadKeyringModule();return t?new t.Entry(`com.apify.cli`,e):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);if(!t)return;t.deletePassword()}catch(t){cliDebugPrint(`credentials`,`failed to delete ${e} from keyring`,t)}}async function getToken(){return await getBackend()===`keyring`?readKeyring(_n):readAuthFile().token}async function getProxyPassword(){return await getBackend()===`keyring`?readKeyring(vn):readAuthFile().proxy?.password}async function setToken(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(_n):readAuthFile().token)===e)return;if(n===`keyring`)try{await writeKeyring(_n,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.token=e,r.secretsBackend=`file`,writeAuthFile(r)}async function setProxyPassword(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(vn):readAuthFile().proxy?.password)===e)return;if(n===`keyring`)try{await writeKeyring(vn,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.proxy={...r.proxy,password:e},r.secretsBackend=`file`,writeAuthFile(r)}async function clearKeyringSecrets(){await deleteKeyring(_n),await deleteKeyring(vn)}async function ensureMigrated(){return xn||(xn=(async()=>{try{let e=readAuthFile();if(e.secretsBackend||!e.token&&!e.proxy?.password)return;if(await getBackend()===`file`){e.secretsBackend=`file`,writeAuthFile(e);return}try{e.token&&await writeKeyring(_n,e.token),e.proxy?.password&&await writeKeyring(vn,e.proxy.password)}catch(t){cliDebugPrint(`credentials`,`keyring write failed during migration; falling back to file`,t),downgradeBackendToFile(),e.secretsBackend=`file`,writeAuthFile(e);return}delete e.token,e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy),e.secretsBackend=`keyring`,writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),xn)}const Sn=`__CLI_`;function resolveInputKey(){return process.env[M.INPUT_KEY]||process.env[P.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${Ge(e)}(?:\\.[^.]+)?$)`)}const Cn=Ke,wn=Be,httpsGet=async e=>new Promise((t,n)=>{Ne(e,e=>{e.statusCode===301||e.statusCode===302?(t(httpsGet(e.headers.location)),e.destroy()):t(e)}).on(`error`,n)}),getLocalStorageDir=()=>{let t=P.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=M.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.keyValueStores,r)},getLocalDatasetPath=t=>{let n=M.DEFAULT_DATASET_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.datasets,r)},getLocalRequestQueuePath=t=>{let n=M.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||ge[n];return k(getLocalStorageDir(),_e.requestQueues,r)},getLocalUserInfo=async()=>{await ensureMigrated();let e={};try{let t=await I(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{}if(await getBackend()===`keyring`){let t=await getToken();t&&(e.token=t);let n=await getProxyPassword();n&&(e.proxy={...e.proxy,password:n})}let t=!!(e.username||e.id);if(!(t||e.token))return{};if(!t)throw Error(`Stale credentials found without user metadata. Please run "apify login" again.`);return e};async function getLoggedClientOrThrow(){let t=await getLoggedClient();if(!t)throw e.exitCode=1,Error(`You are not logged in with your Apify account. Call "apify login" to fix that.`);return t}const resolveToken=async e=>e||(await ensureMigrated(),getToken()),getApifyClientOptions=async(t,n)=>({token:await resolveToken(t),baseUrl:n||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new We;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){let n=new Ve(await getApifyClientOptions(await resolveToken(e),t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}n.token&&await setToken(n.token,{skipIfUnchanged:!0});let i=r.proxy?.password;i&&await setProxyPassword(i,{skipIfUnchanged:!0}),ensureApifyDirectory(AUTH_FILE_PATH());let a=(()=>{try{return JSON.parse(S(AUTH_FILE_PATH(),`utf-8`))}catch{return{}}})(),s=await getBackend(),c={...a,...r,secretsBackend:s};if(s===`keyring`&&(delete c.token,c.proxy&&typeof c.proxy==`object`)){let{password:e,...t}=c.proxy;Object.keys(t).length>0?c.proxy=t:delete c.proxy}return E(AUTH_FILE_PATH(),JSON.stringify(c,null,` `),{mode:384}),n}const getLocalConfigPath=e=>k(e,W),getJsonFileContent=e=>{if(v(e))return JSON.parse(S(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=k(n||e.cwd(),W);await F(O(r),{recursive:!0}),E(r,JSON.stringify(t,null,` `))},Tn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=k(e,`.gitignore`),r=``;v(n)&&(r=S(n,{encoding:`utf-8`}));let i=[];for(let e of Tn)RegExp(`^${Ge(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),E(n,`\n${i.join(`
|
|
28
28
|
`)}\n`,{flag:`a`})):E(n,`${i.join(`
|
|
29
29
|
`)}\n`,{flag:`w`}))},En=new Ye(Ze,Xe).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=En.getType(e);return n?n.startsWith(`text/`)||n.includes(`javascript`)||n.includes(`json`)||n.includes(`xml`)||n.includes(`application/node`)||n.includes(`application/toml`)||n.includes(`application/x-sh`)||n.includes(`application/x-httpd-php`)?be.TEXT:be.BASE64:qe(t)===`binary`?be.BASE64:be.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=S(k(t,e)),r=getSourceFileFormat(e,n);return{name:e,format:r,content:r===be.TEXT?n.toString(`utf8`):n.toString(`base64`)}}),getGitignoreFallbackFilter=async e=>{let t=await Qe(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=O(r),i=await I(k(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:Cn().add(i)})}let r=O(e);for(;r!==O(r)&&!v(k(r,`.git`));){let t=k(r,`.gitignore`);if(v(t))try{let i=await I(t,`utf-8`),a=ae(r,e);n.push({dir:``,ig:Cn().add(i),ancestorPrefix:a})}catch{}r=O(r)}return n.length===0?e=>e:e=>e.filter(e=>{for(let{dir:t,ig:r,ancestorPrefix:i}of n){let n;if(n=t?e.startsWith(`${t}/`)?e.slice(t.length+1):null:i?`${i}/${e}`:e,n!==null&&r.ignores(n))return!1}return!0})},parseActorIgnore=async e=>{let t=k(e,`.actorignore`);if(!v(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await I(t,`utf-8`)).split(`
|
|
30
30
|
`),r=[],i=[];for(let e of n){let t=e.trim();!t||t.startsWith(`#`)||(t.startsWith(`!`)?i.push(t.slice(1)):r.push(t))}return{excludeFilter:r.length>0?e=>{let t=Cn().add(r);return e.filter(e=>!t.ignores(e))}:null,forceIncludePatterns:i}},getActorLocalFilePaths=async t=>{let n=t??e.cwd(),r=[`.git/**`,`apify_storage`,`node_modules`,`storage`,`crawlee_storage`],{excludeFilter:i,forceIncludePatterns:a}=await parseActorIgnore(n),gitIgnoreFilter=null;try{let e=Te(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
|
|
@@ -113,7 +113,7 @@ For runtime operations inside a running Actor (push-data, get-input, set-value..
|
|
|
113
113
|
Did you mean:`,stdout:!1});for(let t of e)simpleLog({message:` ${formatEndpointLine(t)}`,stdout:!1})}simpleLog({message:`\n${vr}`,stdout:!1})}var ApiCommand=class extends ApifyCommand{cachedEndpoints=null;static name=`api`;static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
|
|
114
114
|
The endpoint can be a relative path (e.g. "acts", "v2/acts", or "/v2/acts"); the "v2/" prefix is added automatically if omitted.
|
|
115
115
|
|
|
116
|
-
Use --list-endpoints to see all available API endpoints.`;static examples=[{description:`Make a GET request to an API endpoint (defaults to GET).`,command:`apify api users/me`},{description:`Pass the HTTP method as a positional argument before the endpoint.`,command:`apify api GET /v2/actor-runs`},{description:`Create a resource by POSTing a JSON body.`,command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:`Pass query parameters as a JSON object.`,command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:`Send one or more custom headers as a JSON object.`,command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:`List all available Apify API endpoints.`,command:`apify api --list-endpoints`},{description:`Search for endpoints matching a query.`,command:`apify api --list-endpoints --search "actor run"`},{description:`Print a reference for an endpoint (methods, summary, path params).`,command:`apify api --describe actor-runs/{runId}`}];static docsUrl=`https://docs.apify.com/api/v2`;static args={methodOrEndpoint:Z.string({required:!1,description:`The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").`}),endpoint:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:mr}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.string({char:`H`,description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1,exclusive:[`describe`]}),search:Y.string({char:`s`,description:`Filter results returned by --list-endpoints. The query is case-insensitive and split into tokens by spaces. For an endpoint to be returned, every token must appear in that endpoint's method, path, or summary.`,required:!1,exclusive:[`describe`]}),describe:Y.string({description:`Print a reference for an endpoint path: its HTTP methods, summary, and path parameters. Leading slashes and a version prefix in the path are optional. For example, "actor-runs/{runId}" and "/v2/actor-runs/{runId}" are both accepted.`,required:!1,exclusive:[`list-endpoints`,`search`]})};async run(){if(this.flags.search&&!this.flags.listEndpoints)throw Error(`The --search flag can only be used together with --list-endpoints.`);if(this.flags.describe){await this.describeEndpoint(this.flags.describe);return}if(this.flags.listEndpoints){await this.printEndpoints(this.flags.search);return}let t=this.flags.method?.toUpperCase(),n,r=this.args.methodOrEndpoint;if(r&&mr.includes(r.toUpperCase())){let e=r.toUpperCase();if(t&&t!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${t}". Please specify the method only once.`);n=e,r=this.args.endpoint}else n=t;if(n??=`GET`,!r){this.printHelp();return}let i=parseParams(this.flags.params),a=parseHeaders(this.flags.header);if(this.flags.body){if(hr.has(n))throw Error(`HTTP ${n} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let s=await getLoggedClientOrThrow(),c=s.token,l=normalizePath(r),u=`${s.baseUrl}/${l}`;if(i){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}${i}`}let f={...sn,Authorization:`Bearer ${c}`};this.flags.body&&(f[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(a)){for(let t of Object.keys(f))t.toLowerCase()===e.toLowerCase()&&delete f[t];f[e]=t}let p=await fetch(u,{method:n,headers:f,body:this.flags.body||void 0}),m=await p.text();if(!p.ok){if(e.exitCode=1,error({message:`${p.status} ${p.statusText}`}),m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}p.status===404&&await this.print404Suggestions(l);return}if(m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}}async getEndpoints(){return this.cachedEndpoints??=await fetchEndpoints(),this.cachedEndpoints}async printEndpoints(e){let t=await this.getEndpoints();if(e&&(t=filterEndpoints(t,e),t.length===0)){simpleLog({message:`No endpoints matched the query "${e}".`,stdout:!1});return}for(let e of t)console.log(formatEndpointLine(e))}async describeEndpoint(e){let n=normalizePath(e),r=await this.getEndpoints(),i=r.filter(e=>normalizePath(e.path)===n);if(i.length>0){let e=extractPathParams(i[0].path);console.log(t.bold(i[0].path)),console.log(``);for(let e of i){let n=_r[e.method]||t.white;console.log(` ${n(e.method.padEnd(7))} ${e.summary||t.gray(`(no summary)`)}`)}if(e.length>0){console.log(``),console.log(t.bold(`Path parameters:`));for(let n of e)console.log(` ${t.yellow(`{${n}}`)}`)}console.log(``),console.log(t.gray(`Docs: https://docs.apify.com/api/v2`));return}simpleLog({message:`No endpoint found for "${e}".`,stdout:!1}),printSuggestions(findClosestEndpoints(r,n))}async print404Suggestions(e){try{printSuggestions(findClosestEndpoints(await this.getEndpoints(),e))}catch{simpleLog({message:`\n${vr}`,stdout:!1})}}};async function fetchEndpoints(){let e;try{e=await fetch(gr)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))mr.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}function normalizePath(e){let t=e;return t.startsWith(`/`)&&(t=t.slice(1)),t=t.replace(/^v2\//i,``),t}function filterEndpoints(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?e:e.filter(e=>{let t=`${e.method} ${e.path} ${e.summary}`.toLowerCase();return n.every(e=>t.includes(e))})}function extractPathParams(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(e=>e.slice(1,-1)):[]}function findClosestEndpoints(e,t,n=5){let r=t.toLowerCase(),i=r.split(`/`).filter(Boolean),a=new Map;for(let t of e){if(a.has(t.path))continue;let e=normalizePath(t.path).toLowerCase(),n=0;(e.includes(r)||r.includes(e))&&(n+=10);let s=e.split(`/`).filter(Boolean),c=Math.min(i.length,s.length);for(let e=0;e<c;e++)s[e]===i[e]?n+=2:s[e].startsWith(`{`)&&(n+=1);i.length===s.length&&(n+=1),n>0&&a.set(t.path,n)}let s=[...a.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,n).map(([e])=>e),c=new Set(s),l=new Map;for(let t of e)if(c.has(t.path)){let e=l.get(t.path)||[];e.push(t),l.set(t.path,e)}return s.flatMap(e=>l.get(e)||[])}const yr=stdinCheckWrapper(async({message:e,mask:t})=>await Ft({message:e,mask:t??`*`})),br=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await It({message:e,choices:t,pageSize:n,loop:r,default:i})),xr=`https://console.apify.com/settings/integrations`,Sr=new URL(xr).origin,Cr=xr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async n=>{let r=await getLoggedClient(n,Cr),i=await getLocalUserInfo();if(r){await updateUserId(i.id);let n=await getBackend(),r;r=n===`keyring`?`your OS keyring`:e.env.APIFY_DISABLE_KEYRING===`1`?`${AUTH_FILE_PATH()} (OS keyring disabled via APIFY_DISABLE_KEYRING)
|
|
116
|
+
Use --list-endpoints to see all available API endpoints.`;static examples=[{description:`Make a GET request to an API endpoint (defaults to GET).`,command:`apify api users/me`},{description:`Pass the HTTP method as a positional argument before the endpoint.`,command:`apify api GET /v2/actor-runs`},{description:`Create a resource by POSTing a JSON body.`,command:`apify api POST acts -d '{"name":"my-actor"}'`},{description:`Pass query parameters as a JSON object.`,command:`apify api actor-runs -p '{"limit":1,"desc":true}'`},{description:`Send one or more custom headers as a JSON object.`,command:`apify api acts -H '{"X-Foo":"bar","X-Baz":"qux"}'`},{description:`List all available Apify API endpoints.`,command:`apify api --list-endpoints`},{description:`Search for endpoints matching a query.`,command:`apify api --list-endpoints --search "actor run"`},{description:`Print a reference for an endpoint (methods, summary, path params).`,command:`apify api --describe actor-runs/{runId}`}];static docsUrl=`https://docs.apify.com/api/v2`;static args={methodOrEndpoint:Z.string({required:!1,description:`The API endpoint path (e.g. "acts", "v2/acts", "/v2/users/me"), or an HTTP method followed by the endpoint (e.g. "GET /v2/users/me").`}),endpoint:Z.string({required:!1,description:`The API endpoint path when the first argument is an HTTP method.`})};static flags={method:Y.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:mr}),body:Y.string({char:`d`,description:`The request body (JSON string). Use "-" to read from stdin.`,required:!1,stdin:2}),header:Y.string({char:`H`,description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers. The flag can only be used once; use the JSON form for multiple headers.`,required:!1}),params:Y.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"limit": 1, "desc": true}'.`,required:!1}),"list-endpoints":Y.boolean({char:`l`,description:`List all available Apify API endpoints.`,default:!1,exclusive:[`describe`]}),search:Y.string({char:`s`,description:`Filter results returned by --list-endpoints. The query is case-insensitive and split into tokens by spaces. For an endpoint to be returned, every token must appear in that endpoint's method, path, or summary.`,required:!1,exclusive:[`describe`]}),describe:Y.string({description:`Print a reference for an endpoint path: its HTTP methods, summary, and path parameters. Leading slashes and a version prefix in the path are optional. For example, "actor-runs/{runId}" and "/v2/actor-runs/{runId}" are both accepted.`,required:!1,exclusive:[`list-endpoints`,`search`]})};async run(){if(this.flags.search&&!this.flags.listEndpoints)throw Error(`The --search flag can only be used together with --list-endpoints.`);if(this.flags.describe){await this.describeEndpoint(this.flags.describe);return}if(this.flags.listEndpoints){await this.printEndpoints(this.flags.search);return}let t=this.flags.method?.toUpperCase(),n,r=this.args.methodOrEndpoint;if(r&&mr.includes(r.toUpperCase())){let e=r.toUpperCase();if(t&&t!==e)throw Error(`Conflicting HTTP methods: positional "${e}" vs --method "${t}". Please specify the method only once.`);n=e,r=this.args.endpoint}else n=t;if(n??=`GET`,!r){this.printHelp();return}let i=parseParams(this.flags.params),a=parseHeaders(this.flags.header);if(this.flags.body){if(hr.has(n))throw Error(`HTTP ${n} requests cannot have a request body. Use a different method (e.g. POST, PUT, PATCH) or omit --body.`);try{JSON.parse(this.flags.body)}catch{throw Error(`Invalid JSON in --body flag. Please provide a valid JSON string.`)}}let s=await getLoggedClientOrThrow(),c=s.token,l=normalizePath(r),u=`${s.baseUrl}/${l}`;if(i){let e=u.includes(`?`)?`&`:`?`;u=`${u}${e}${i}`}let f={...sn,Authorization:`Bearer ${c}`};this.flags.body&&(f[`Content-Type`]=`application/json`);for(let[e,t]of Object.entries(a)){for(let t of Object.keys(f))t.toLowerCase()===e.toLowerCase()&&delete f[t];f[e]=t}let p=await fetch(u,{method:n,headers:f,body:this.flags.body||void 0}),m=await p.text();if(!p.ok){if(e.exitCode=1,error({message:`${p.status} ${p.statusText}`}),m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}p.status===404&&await this.print404Suggestions(l);return}if(m)try{let e=JSON.parse(m);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:m,stdout:!0})}}async getEndpoints(){return this.cachedEndpoints??=await fetchEndpoints(),this.cachedEndpoints}async printEndpoints(e){let t=await this.getEndpoints();if(e&&(t=filterEndpoints(t,e),t.length===0)){simpleLog({message:`No endpoints matched the query "${e}".`,stdout:!1});return}for(let e of t)console.log(formatEndpointLine(e))}async describeEndpoint(e){let n=normalizePath(e),r=await this.getEndpoints(),i=r.filter(e=>normalizePath(e.path)===n);if(i.length>0){let e=extractPathParams(i[0].path);console.log(t.bold(i[0].path)),console.log(``);for(let e of i){let n=_r[e.method]||t.white;console.log(` ${n(e.method.padEnd(7))} ${e.summary||t.gray(`(no summary)`)}`)}if(e.length>0){console.log(``),console.log(t.bold(`Path parameters:`));for(let n of e)console.log(` ${t.yellow(`{${n}}`)}`)}console.log(``),console.log(t.gray(`Docs: https://docs.apify.com/api/v2`));return}simpleLog({message:`No endpoint found for "${e}".`,stdout:!1}),printSuggestions(findClosestEndpoints(r,n))}async print404Suggestions(e){try{printSuggestions(findClosestEndpoints(await this.getEndpoints(),e))}catch{simpleLog({message:`\n${vr}`,stdout:!1})}}};async function fetchEndpoints(){let e;try{e=await fetch(gr)}catch(e){throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.message}`)}if(!e.ok)throw Error(`Failed to download the Apify OpenAPI spec from ${gr}: ${e.status} ${e.statusText}`);let t=await e.json(),n=[];for(let[e,r]of Object.entries(t.paths))for(let[t,i]of Object.entries(r))mr.includes(t.toUpperCase())&&n.push({method:t.toUpperCase(),path:e,summary:i.summary||``});return n.sort((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)),n}function normalizePath(e){let t=e;return t.startsWith(`/`)&&(t=t.slice(1)),t=t.replace(/^v2\//i,``),t}function filterEndpoints(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);return n.length===0?e:e.filter(e=>{let t=`${e.method} ${e.path} ${e.summary}`.toLowerCase();return n.every(e=>t.includes(e))})}function extractPathParams(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(e=>e.slice(1,-1)):[]}function findClosestEndpoints(e,t,n=5){let r=t.toLowerCase(),i=r.split(`/`).filter(Boolean),a=new Map;for(let t of e){if(a.has(t.path))continue;let e=normalizePath(t.path).toLowerCase(),n=0;(e.includes(r)||r.includes(e))&&(n+=10);let s=e.split(`/`).filter(Boolean),c=Math.min(i.length,s.length);for(let e=0;e<c;e++)s[e]===i[e]?n+=2:s[e].startsWith(`{`)&&(n+=1);i.length===s.length&&(n+=1),n>0&&a.set(t.path,n)}let s=[...a.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,n).map(([e])=>e),c=new Set(s),l=new Map;for(let t of e)if(c.has(t.path)){let e=l.get(t.path)||[];e.push(t),l.set(t.path,e)}return s.flatMap(e=>l.get(e)||[])}const yr=stdinCheckWrapper(async({message:e,mask:t})=>await Ft({message:e,mask:t??`*`})),br=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await It({message:e,choices:t,pageSize:n,loop:r,default:i})),xr=`https://console.apify.com/settings/integrations`,Sr=new URL(xr).origin,Cr=xr.includes(`localhost`)?`http://localhost:3333`:void 0,tryToLogin=async n=>{let r=await getLoggedClient(n,Cr),i=await getLocalUserInfo();if(r){await updateUserId(i.id);let n=await getBackend(),r;r=n===`keyring`?`your OS keyring`:e.env.APIFY_DISABLE_KEYRING===`1`?`${AUTH_FILE_PATH()} (OS keyring disabled via APIFY_DISABLE_KEYRING)`:`${AUTH_FILE_PATH()} (OS keyring unavailable; set APIFY_DISABLE_KEYRING=1 to silence)`,success({message:`You are logged in to Apify as ${i.username||i.id}. ${t.gray(`Your token is stored in ${r}.`)}`})}else error({message:`Login to Apify failed, the provided API token is not valid.`});return r};var AuthLoginCommand=class extends ApifyCommand{static name=`login`;static description=`Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\nAll other commands use these stored credentials.
|
|
117
117
|
|
|
118
118
|
Run 'apify logout' to remove authentication.`;static group=`Authentication`;static interactive=!0;static interactiveNote=`Prompts for an API token if not provided. To run non-interactively, pass --token <api-token>.`;static examples=[{description:`Log in interactively (prompts to choose a method, then completes the flow accordingly).`,command:`apify login`},{description:`Log in non-interactively with an API token.`,command:`apify login --token apify_api_xxxxx`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-login`;static flags={token:Y.string({char:`t`,description:`Apify API token.`,required:!1}),method:Y.string({char:`m`,description:`Method of logging in to Apify.`,choices:[`console`,`manual`],required:!1})};async run(){let{token:e,method:t}=this.flags;if(e){await tryToLogin(e);return}let n=t;if(t||(n=await br({message:`Choose how you want to log in to Apify`,choices:[{value:`console`,name:`Through Apify Console in your default browser`,short:`Through Apify Console`},{value:`manual`,name:`Enter API token manually`,short:`Manually`}],loop:!0})),n===`console`){let e,t=Pt();t.use(Nt({origin:Sr,allowedHeaders:[`Content-Type`,`Authorization`]})),t.use((e,t,n)=>{t.set(`Connection`,`close`),n()}),t.use(Pt.json());let n=we();t.use((e,t,r)=>{let{token:i}=e.query;if(!i){let t=e.get(`Authorization`);if(t){let[e,n,...r]=t.trim().split(/\s+/);e.toLowerCase()===`bearer`&&n&&r.length===0&&(i=n)}}i===n?r():(t.status(401),t.send(`Authorization failed`))});let r=Pt.Router();t.use(`/api/v1`,r),r.post(`/login-token`,async(t,n)=>{try{if(t.body.apiToken)await tryToLogin(t.body.apiToken);else throw Error(`Request did not contain API token`);n.end()}catch(e){let t=`Login to Apify failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}e.close()}),r.post(`/exit`,(t,n)=>{t.body.isWindowClosed?error({message:`Login to Apify failed, the console window was closed.`}):t.body.actionCanceled?error({message:`Login to Apify failed, the action was canceled in the Apify Console.`}):error({message:`Login to Apify failed.`}),n.end(),e.close()}),e=t.listen(0);let{port:i}=e.address(),a=new URL(xr);a.searchParams.set(`localCliCommand`,`login`),a.searchParams.set(`localCliPort`,`${i}`),a.searchParams.set(`localCliToken`,n),a.searchParams.set(`localCliApiVersion`,`v1`);try{a.searchParams.set(`localCliComputerName`,encodeURIComponent(Mt()))}catch{}info({message:`Opening Apify Console at "${a.href}"...`}),await Ot(a.href)}else console.log(`Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations`),await tryToLogin(await yr({message:`token:`}))}},AuthLogoutCommand=class extends ApifyCommand{static name=`logout`;static description=`Removes authentication by deleting your API token and account information from '${tildify(AUTH_FILE_PATH())}'.\nRun 'apify login' to authenticate again.`;static group=`Authentication`;static examples=[{description:`Remove the stored Apify credentials.`,command:`apify logout`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-logout`;async run(){await clearKeyringSecrets(),await rimrafPromised(AUTH_FILE_PATH()),await updateUserId(null),success({message:`You are logged out from your Apify account.`})}},AuthTokenCommand=class extends ApifyCommand{static name=`token`;static description=`Prints the current API token for the Apify CLI.`;static examples=[{description:`Print the stored API token to stdout (use with care — it is a secret).`,command:`apify auth token`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-token`;async run(){await getLoggedClientOrThrow();let e=await getLocalUserInfo();e.token&&simpleLog({message:e.token,stdout:!0})}},AuthIndexCommand=class extends ApifyCommand{static name=`auth`;static description="Log in, log out, and inspect your stored Apify API token. Also available as `apify login` / `apify logout`.";static group=`Authentication`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth`;static subcommands=[AuthLoginCommand,AuthLogoutCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{static name=`add-tag`;static description=`Adds a tag to a specific Actor build.`;static examples=[{description:`Tag a successful build as "latest".`,command:`apify builds add-tag --build <buildId> --tag latest`},{description:`Tag a build with a custom name like "beta".`,command:`apify builds add-tag --build <buildId> --tag beta`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-add-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to tag.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to add to the build.`,required:!0})};async run(){let{build:e,tag:n}=this.flags,r=await getLoggedClientOrThrow(),i=await r.build(e).get();if(!i){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(i.status!==`SUCCEEDED`){error({message:`Build with ID "${e}" has status "${i.status}". Only successful builds can be tagged.`,stdout:!0});return}let a=await r.actor(i.actId).get();if(!a){error({message:`Actor with ID "${i.actId}" was not found.`,stdout:!0});return}let s=(a.taggedBuilds??{})[n];if(s?.buildId===e){warning({message:`Build "${e}" is already tagged as "${n}".`,stdout:!0});return}try{await r.actor(i.actId).update({taggedBuilds:{[n]:{buildId:i.id}}});let a=s?.buildNumber?` (previously pointed to build ${t.gray(s.buildNumber)})`:``;success({message:`Tag "${t.yellow(n)}" added to build ${t.gray(i.buildNumber)} (${t.gray(e)})${a}`,stdout:!0})}catch(t){let r=t;error({message:`Failed to add tag "${n}" to build "${e}".\n ${r.message||r}`,stdout:!0})}}};const noColor=e=>e;function prettyPrintBytes({bytes:e,shortBytes:t=!1,colorFunc:n=noColor,precision:r=2}){let i=[t?`B`:`Bytes`,`KB`,`MB`,`GB`,`TB`];if(e===0)return t?`${0 .toPrecision(r)} B`:`${0 .toPrecision(r)} Byte`;let a=Math.floor(Math.log(e)/Math.log(1e3));return`${(e/1e3**a).toFixed(r)} ${n(i[a])}`}var BuildsInfoCommand=class extends ApifyCommand{static name=`info`;static description=`Prints information about a specific build.`;static examples=[{description:`Print information about a build.`,command:`apify builds info <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-info`;static args={buildId:Z.string({required:!0,description:`The build ID to get information about.`})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){printJsonToStdout(r);return}let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[e,t]of Object.entries(i.taggedBuilds))if(t.buildId===r.id){a=e;break}}let s=Reflect.get(r,`exitCode`),c=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,l=a?` (tagged as ${t.yellow(a)})`:``,u=s===void 0?``:` (exit code: ${t.gray(s)})`,f=[`${t.yellow(`Actor`)}: ${c} (${t.gray(r.actId)})`,``,`${t.yellow(`Build Information`)} (ID: ${t.gray(r.id)})`,` ${t.yellow(`Build Number`)}: ${r.buildNumber}${l}`,` ${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${u}`,` ${t.yellow(`Started`)}: ${G.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${G.display(r.finishedAt)} (took ${t.gray(kn.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${kn.format(e)}`)}`)}r.stats?.computeUnits&&f.push(` ${t.yellow(`Compute Units`)}: ${r.stats.computeUnits.toFixed(3)}`);let p=Reflect.get(r.stats??{},`imageSizeBytes`);p&&f.push(` ${t.yellow(`Docker Image Size`)}: ${prettyPrintBytes({bytes:p})}`),f.push(` ${t.yellow(`Origin`)}: ${r.meta.origin??`UNKNOWN`}`),f.push(``);let m=`https://console.apify.com/actors/${r.actId}/builds/${r.buildNumber}`;f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
|
|
119
119
|
`),stdout:!0})}},BuildsLogCommand=class extends ApifyCommand{static name=`log`;static description=`Prints the log of a specific build.`;static examples=[{description:`Print the build log.`,command:`apify builds log <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-log`;static args={buildId:Z.string({required:!0,description:`The build ID to get the log from.`})};async run(){let{buildId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.build(e).get();if(!n)throw Error(`Build with ID "${e}" was not found on your account.`);info({message:`Log for build with ID "${e}":\n`}),await outputJobLog({job:n,apifyClient:t})}};const tableFactory=()=>new Q({allColumns:[`Number`,`ID`,`Status`,`Took`],mandatoryColumns:[`Number`,`ID`,`Status`,`Took`],columnAlignments:{Took:`right`}});var BuildsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all builds of the Actor.`;static examples=[{description:`List builds of the Actor in the current directory.`,command:`apify builds ls`},{description:`List builds of a specific Actor.`,command:`apify builds ls apify/hello-world`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-ls`;static flags={offset:Y.integer({description:`Number of builds that will be skipped.`,default:0}),limit:Y.integer({description:`Number of builds that will be listed.`,default:10}),desc:Y.boolean({description:`Sort builds 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.`,stdout:!0});return}let u=await c.actor(l.id).builds().list({desc:e,limit:n,offset:r}),f=await c.actor(l.id).get(),p=objectGroupBy(u.items,e=>{let[t,n]=Reflect.get(e,`buildNumber`).split(`.`);return`${t}.${n}`}),m=Object.entries(f.taggedBuilds??{}).reduce((e,[t,n])=>(e[n.buildNumber]=t,e),{});if(a){for(let e of u.items){let t=m[Reflect.get(e,`buildNumber`)];t&&Reflect.set(e,`buildTag`,t)}printJsonToStdout(u);return}simpleLog({message:`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} builds for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})\n`,stdout:!0});let h=Object.entries(p).sort((e,t)=>e[0].localeCompare(t[0]));for(let[e,n]of h){if(!n?.length){simpleLog({message:`No builds for version ${e}`,stdout:!0});continue}let r=f.versions.find(t=>t.versionNumber===e)?.buildTag,a=this.generateTableForActorVersion({buildsForVersion:n,buildTagToActorVersion:m}),s=r?` (latest build gets tagged with ${t.yellow(r)})`:``;simpleLog({message:[t.reset(`Builds for Actor Version ${t.yellow(e)}${s}`),a.render(i?0:-1),``].join(`
|
|
@@ -231,4 +231,4 @@ When no path is provided, validates all schemas found in '${W}':
|
|
|
231
231
|
- Dataset schema (from "storages.dataset")
|
|
232
232
|
- Output schema (from "output")
|
|
233
233
|
- 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 Qr=[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],$r=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Qr as n,processVersionCheck as r,$r as t};
|
|
234
|
-
//# sourceMappingURL=_register-
|
|
234
|
+
//# sourceMappingURL=_register-DSMUG3PQ.js.map
|