apify-cli 1.8.1-beta.2 → 1.8.1-beta.3
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 a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as ee,readFileSync as A,readdirSync as j,realpathSync as te,renameSync as ne,rmSync as M,statSync as re,unlinkSync as ie,writeFileSync as N}from"node:fs";import ae from"string-width";import oe from"strip-ansi";import{once as se}from"node:events";import{homedir as ce,platform as le}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as P,ACTOR_JOB_STATUSES as F,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as I,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{Result as Ce,err as we,none as L,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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=te(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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.8.1-beta.
|
|
1
|
+
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as ee,readFileSync as A,readdirSync as j,realpathSync as te,renameSync as ne,rmSync as M,statSync as re,unlinkSync as ie,writeFileSync as N}from"node:fs";import ae from"string-width";import oe from"strip-ansi";import{once as se}from"node:events";import{homedir as ce,platform as le}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as P,ACTOR_JOB_STATUSES as F,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as I,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{Result as Ce,err as we,none as L,ok as Te,some as Ee}from"@sapphire/result";import{execa as De}from"execa";import{access as Oe,appendFile as ke,mkdir as R,readFile as z,readdir as Ae,rename as je,rm as Me,stat as B,symlink as Ne,unlink as Pe,writeFile as V}from"node:fs/promises";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{createHmacSignature as Re,cryptoRandomObjectId as ze}from"@apify/utilities";import{execSync as Be,spawn as Ve}from"node:child_process";import{DurationFormatter as He,Time as Ue,TimeTypes as We}from"@sapphire/duration";import{Timestamp as Ge}from"@sapphire/timestamp";import Ke from"adm-zip";import qe from"ajv/dist/2019.js";import{ApifyClient as Je,DownloadItemsFormat as H}from"apify-client";import{ZipArchive as Ye}from"archiver";import Xe,{AxiosHeaders as Ze}from"axios";import Qe from"escape-string-regexp";import $e from"ignore";import{getEncoding as et}from"istextorbinary";import tt,{Mime as nt}from"mime";import rt from"mime/types/other.js";import it from"mime/types/standard.js";import{glob as at}from"tinyglobby";import{calculateRunDynamicMemory as ot}from"@apify/actor-memory-expression";import{Separator as st,createPrompt as ct,isEnterKey as lt,makeTheme as ut,useKeypress as dt,usePrefix as ft,useState as pt}from"@inquirer/core";import{pipeline as mt}from"node:stream/promises";import{MemoryStorage as ht}from"@crawlee/memory-storage";import{compile as gt}from"json-schema-to-typescript";import{validateInputSchema as _t,validateInputUsingValidator as vt}from"@apify/input_schema";import{getDatasetSchemaValidator as yt,getKeyValueStoreSchemaValidator as bt,getOutputSchemaValidator as xt}from"@apify/json_schemas";import St from"cli-table3";import{downloadTemplate as Ct}from"giget";import wt from"jju";import Tt from"open";import{fetchManifest as Et,manifestUrl as Dt,wrapperManifestUrl as Ot}from"@apify/actor-templates";import kt from"computer-name";import At from"@inquirer/password";import jt from"@inquirer/select";import{createServer as Mt}from"node:http";import Nt from"node:assert";import{ReadStream as Pt}from"node:tty";import Ft from"detect-indent";import{fileURLToPath as It}from"node:url";import Lt from"@root/walk";import Rt 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=te(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 zt=null;function useCLIMetadata(){if(zt)return zt;let e=detectInstallMethod(),t=getRuntimeInfo();return zt={version:`1.8.1-beta.3`,hash:`0e25909488e495000a6a860fc96a48fc09f63fe2`,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`&&(zt.installPath=c(process.execPath)),zt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Bt=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
|
|
2
2
|
`)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
|
|
3
3
|
`)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
|
|
4
4
|
`)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{N(i,n),r!==void 0&&C(i,r),ne(i,t)}catch(e){try{M(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{T(t,i),r!==void 0&&C(i,r),ne(i,n)}catch(e){try{M(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Bt)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Bt){let t=u(r,`${e}.exe.old`);if(D(t))try{M(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Bt.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Bt){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(ne(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):M(n,{force:!0})}catch(e){try{ne(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{M(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Vt;function getMaxLineWidth(){if(Vt)return Vt;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Vt=e;else if(!process.stdout.isTTY)Vt=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Vt=e<1?80:e<40?40:e}return Vt}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(`
|
|
@@ -23,7 +23,7 @@ import e from"node:process";import t from"chalk";import n from"indent-string";im
|
|
|
23
23
|
`);s.push(t.dim(n(a,2)))}s.push(` $ ${r.command}`),r.description&&e<h.length-1&&s.push(``)}s.push(``)}return s.push(t.bold(`LEARN MORE`),` Use '${e} <command> --help' for more information about a command.`,` Read the docs at https://docs.apify.com/cli.`,` Run '${e} help --skill' to print the Apify CLI agent skill (guidance for driving 'apify' from agents).`,``),s.push(t.bold(`TROUBLESHOOTING`),` For general support, reach out to us at https://apify.com/contact.`,` If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new.`),s.join(`
|
|
24
24
|
`).trim()}let qt=function(e){return e[e.NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE=0]=`NODEJS_ERR_PARSE_ARGS_INVALID_OPTION_VALUE`,e[e.NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL=1]=`NODEJS_ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`,e[e.NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION=2]=`NODEJS_ERR_PARSE_ARGS_UNKNOWN_OPTION`,e[e.APIFY_FLAG_PROVIDED_MULTIPLE_TIMES=3]=`APIFY_FLAG_PROVIDED_MULTIPLE_TIMES`,e[e.APIFY_INVALID_FLAG_INTEGER_VALUE=4]=`APIFY_INVALID_FLAG_INTEGER_VALUE`,e[e.APIFY_INVALID_CHOICE=5]=`APIFY_INVALID_CHOICE`,e[e.APIFY_MISSING_FLAG=6]=`APIFY_MISSING_FLAG`,e[e.APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG=7]=`APIFY_FLAG_IS_EXCLUSIVE_WITH_ANOTHER_FLAG`,e[e.APIFY_TOO_MANY_REQUESTERS_OF_STDIN=8]=`APIFY_TOO_MANY_REQUESTERS_OF_STDIN`,e[e.APIFY_UNKNOWN_ERROR=9]=`APIFY_UNKNOWN_ERROR`,e}({});var U=class CommandError extends Error{code;command;metadata;constructor({code:e,message:t=``,metadata:n={},command:r}){super(t||String(qt[e])),this.code=e,this.metadata=n,this.command=r}extractFlagNameFromMessage(){switch(this.code){case 0:{let e=/'(?:-[a-z], )?-?-(?<flagName>[a-zA-Z-]+)(?: <value>)?' (?<noArg>does not take)?(?<missingArg>argument missing)?(?<ambiguous>argument is ambiguous\.(?<ambiguousMessage>\s*.*\s*.*)?)?/gi.exec(this.message);if(!e)throw Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.flagName,expectsValue:e.groups.noArg===void 0,ambiguousFlag:e.groups.ambiguous?e.groups.ambiguous:void 0,ambiguousMessage:e.groups.ambiguousMessage?e.groups.ambiguousMessage.trim():void 0}}case 2:{let e=/Unknown option '-(?<longForm>-)?(?<optionName>.+)'\.(?<nodeSuggestion>.*)/gi.exec(this.message);if(!e)throw Error(`Encountered unparsable error message from argument parser: ${this.message}.\n\nPlease report this issue at https://github.com/apify/apify-cli/issues`);return{name:e.groups.optionName,expectsValue:!1,unknownOptionSuggestion:e.groups.nodeSuggestion,shortForm:!e.groups.longForm}}default:throw Error(`Not implemented`)}}getPrettyMessage(){switch(this.code){case 0:{let e=this.extractFlagNameFromMessage();return CommandError.buildMessageFromFlagData(e)}case 2:{let e=this.extractFlagNameFromMessage(),n=selectiveRenderHelpForCommand(this.command,{showUsageString:!0});return[t.gray(`Unknown flag provided: ${t.white.bold(e.shortForm?`-${e.name}`:`--${e.name}`)}`),e.unknownOptionSuggestion?t.gray(` ${e.unknownOptionSuggestion.trim()}`):null,``,n].filter(e=>e!==null).join(`
|
|
25
25
|
`)}case 3:{let e=`--${this.metadata.flag}`;return t.gray(`Flag ${t.white.bold(e)} can only be specified once.`)}case 4:{let e=`--${this.metadata.flag}`,n=t.whiteBright(String(this.metadata.value));return t.gray(`The provided value for the '${t.white.bold(e)}' flag could not be processed as an integer. Received: ${n}.`)}case 6:{let{flag:e,matcher:n,providedButReceivedNoValue:r}=this.metadata,i=`'${t.white.bold(`--${e}`)}'`;return n&&(i=`${i} (alias used: '${t.white.bold(`--${n}`)}')`),r?t.gray(`Flag ${i} was provided, but no value was received. Did you mean to pass the value as an argument or through standard input?`):t.gray(`Flag ${i} is required, but was not provided.`)}case 7:{let{flagPairs:e}=this.metadata,n=[t.gray(`The following errors occurred:`)],r=t.red(` > `);for(let[i,a]of e)n.push(t.gray(`${r}${t.white.bold(i)} cannot also be provided when using ${t.white.bold(a)}`));return n.push(t.gray(`${r}See more help with ${t.white.bold(`--help`)}`)),n.join(`
|
|
26
|
-
`)}case 8:{let{firstUse:e,secondUse:n}=this.metadata;return t.gray(`Flag ${t.white.bold(`--${e}`)} and ${t.white.bold(`--${n}`)} cannot both request that their value comes from standard input at the same time.`)}default:{let e=useCLIMetadata();return[`The CLI encountered an unhandled argument parsing error!`,`Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:`,``,`- Error code: ${this.code} (${qt[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,``,`- Stack:\n${this.stack}`,``,`- Arguments (!!!only provide these as is if there is no sensitive information!!!):`,` ${JSON.stringify(process.argv.slice(2))}`,``,`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?`Enabled`:`Disabled`}`,`- Stdin data? ${un?`Yes`:`No`}`].join(`
|
|
26
|
+
`)}case 8:{let{firstUse:e,secondUse:n}=this.metadata;return t.gray(`Flag ${t.white.bold(`--${e}`)} and ${t.white.bold(`--${n}`)} cannot both request that their value comes from standard input at the same time.`)}case 5:{let e=`--${this.metadata.flag}`,n=this.metadata.choices;return t.gray(`Invalid value for flag ${t.white.bold(e)}. Expected one of: ${n}`)}default:{let e=useCLIMetadata();return[`The CLI encountered an unhandled argument parsing error!`,`Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:`,``,`- Error code: ${this.code} (${qt[this.code]})`,`- Error metadata: ${JSON.stringify(this.metadata)}`,``,`- Stack:\n${this.stack}`,``,`- Arguments (!!!only provide these as is if there is no sensitive information!!!):`,` ${JSON.stringify(process.argv.slice(2))}`,``,`- CLI version: \`${e.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${process.env.APIFY_CLI_DEBUG?`Enabled`:`Disabled`}`,`- Stdin data? ${un?`Yes`:`No`}`].join(`
|
|
27
27
|
`)}}}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(`
|
|
28
28
|
`).map(e=>` ${e}`).join(`
|
|
29
29
|
`)}`):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})}};const Jt=_(O);let Yt;async function useStdin(){if(Yt)return Yt;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await Jt(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&w.S_IFIFO)===w.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),Yt=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());let onData=e=>{i.push(e),s&&=(clearTimeout(s),null)};r.on(`data`,onData);try{await se(r,`end`,{signal:a.signal})}catch(e){if(e.name===`AbortError`)return}finally{r.off(`data`,onData),r.pause()}s&&clearTimeout(s),e.hasData=!1;let c=Buffer.concat(i);if(c.length)return c}var Xt={node:`>=20`};const Zt=`storage`,Qt={actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},$t=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=u(ce(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?u(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>u(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),en=`.actor`,W=u(en,`actor.json`),tn=Xt.node,nn=ue.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,rn={"X-Apify-Request-Origin":ue.isCI?ye.CI:ye.CLI,...nn&&{"X-Apify-Github-Actions-Run-Url":nn}},an=`3.11.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 on={version:1};function useLocalState(){let e=STATE_FILE_PATH();if(!D(e))return on;let t=JSON.parse(A(e,`utf-8`));return migrateStateV0ToV1$1(t)?useLocalState():t}function updateLocalState(e,t){let n={...e};t(n);let r=STATE_FILE_PATH(),i=c(r);k(i,{recursive:!0}),N(STATE_FILE_PATH(),JSON.stringify(n,null,` `))}const sn=useCLIMetadata(),cn=`Apify CLI/${sn.version} (https://github.com/apify/apify-cli)`,ln=[`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(ln.map(async e=>fetch(e,{signal:t.signal,headers:{"User-Agent":cn},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":cn}});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:sn.version,latestVersion:`unknown`,shouldUpdate:!1,cacheHit:!1};let a=v(i,sn.version);return{currentVersion:sn.version,latestVersion:i,shouldUpdate:a,cacheHit:!r}}function useCommandSuggestions(e){let t=[...q.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 un=await readStdin(),dn=useCLIMetadata(),fn=`Apify CLI/${dn.version} (https://github.com/apify/apify-cli)`;function processVersionCheck(t){dn.installMethod!==`bundle`&&(x(e.version,tn)||(error({message:`${t} CLI requires Node.js version ${tn}. Your current version is ${e.version}.`}),e.exit(1)))}function printCLIVersionAndExitIfFlagUsed(t){t.values.version===!0&&t.positionals.length===0&&(console.log(dn.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+=`
|
|
@@ -51,7 +51,7 @@ Common package structures:
|
|
|
51
51
|
`),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=kn().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=Be(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
|
|
52
52
|
`).filter(Boolean);if(e.length>0){let t=kn().add(e);gitIgnoreFilter=e=>e.filter(e=>!t.ignores(e))}}catch{gitIgnoreFilter=await getGitignoreFallbackFilter(n)}let s=await at([`*`,`**/**`],{ignore:r,dot:!0,expandDirectories:!1,cwd:n}),c=gitIgnoreFilter?gitIgnoreFilter(s):s;if(i&&(c=i(c)),a.length>0){let e=kn().add(a),t=s.filter(t=>e.ignores(t)),n=new Set(c);for(let e of t)n.add(e);c=[...n]}let l=s.filter(e=>e===`.actor`||e.startsWith(`.actor/`));if(l.length>0){let e=new Set(c);for(let t of l)e.add(t);c=[...e]}return c},createActZip=async(e,t,n)=>{D(e)&&await deleteFile(e);let r=E(e),i=new Ye({zlib:{level:6}});i.pipe(r),t.forEach(e=>i.file(u(n,e),{name:e})),await i.finalize()},getLocalInput=(e,t)=>{let n=getLocalKeyValueStorePath();if(!D(u(e,n)))return;let r=j(u(e,n)).find(e=>!!e.match(inputFileRegExp(t??`INPUT`)));return r?{body:A(u(e,n,r)),contentType:Mn.getType(r),fileName:r}:void 0},purgeDefaultQueue=async()=>{let e=getLocalRequestQueuePath();D(getLocalStorageDir())&&D(e)&&await rimrafPromised(e)},purgeDefaultDataset=async()=>{let e=getLocalDatasetPath();D(getLocalStorageDir())&&D(e)&&await rimrafPromised(e)},purgeDefaultKeyValueStore=async(...e)=>{let t=getLocalKeyValueStorePath();if(!D(getLocalStorageDir())||!D(t))return;let n=j(t),r=(e.length>0?e:[`INPUT`]).map(inputFileRegExp),i=[];n.forEach(e=>{r.some(t=>t.test(e))||i.push(deleteFile(u(t,e)))}),await Promise.all(i)},outputJobLog=async({job:t,timeoutMillis:n,apifyClient:r})=>{let{id:i,status:a}=t,s=r||new Je({baseUrl:e.env.APIFY_CLIENT_BASE_URL});if(fe.includes(a)){if(e.env.APIFY_NO_LOGS_IN_TESTS)return;let t=await s.log(i).get();e.stderr.write(t);return}return new Promise(async t=>{let r=await s.log(i).stream();if(!r){t(`no-logs`);return}let a=null;r.on(`data`,t=>{e.env.APIFY_NO_LOGS_IN_TESTS||e.stderr.write(t.toString())}),r.once(`end`,()=>{t(`finished`),a&&clearTimeout(a)}),n!==void 0&&(a=setTimeout(()=>{r.destroy(),t(`timeouts`)},n))})},checkIfStorageIsEmpty=async e=>{let t=e||he.INPUT;return(await at([`${getLocalStorageDir()}/**`,`!${getLocalKeyValueStorePath()}/${t}.*`,`!${getLocalKeyValueStorePath()}/${On}${t}.*`])).length===0},validateActorName=e=>{if(!pe.REGEX.test(e))throw Error(`The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).`);if(e.length<pe.MIN_LENGTH)throw Error(`The Actor name must be at least 3 characters long.`);if(e.length>pe.MAX_LENGTH)throw Error(`The Actor name must be a maximum of 30 characters long.`)},sanitizeActorName=e=>{let t=e.replaceAll(/[^a-zA-Z0-9-]/g,`-`);return t.length<pe.MIN_LENGTH&&(t=`${t}-apify-actor`),t=t.replaceAll(/^-+/g,``).replaceAll(/-+$/g,``),t.slice(0,pe.MAX_LENGTH)},isPythonVersionSupported=e=>x(e,`^${an}`),isNodeVersionSupported=e=>{let t=b(tn);return y(e,t)},downloadZip=async e=>{let t=await Xe.get(e,{responseType:`arraybuffer`,validateStatus:()=>!0,headers:{"User-Agent":`Apify CLI/${useCLIMetadata().version} (https://github.com/apify/apify-cli)`}});if(t.status<200||t.status>=300){let n=Buffer.from(t.data).toString(`utf8`).trim().slice(0,500);throw Error(`Failed to download the archive from ${e} (HTTP ${t.status}).${n?`\nServer response: ${n}`:``}`)}let n=Buffer.from(t.data);if(n.subarray(0,2).toString()!==`PK`)throw Error(`The file downloaded from ${e} is not a valid zip archive - a proxy or firewall likely intercepted the download. Check your network or try a different one.`);return new Ke(n)},downloadAndUnzip=async({url:e,pathTo:t})=>{(await downloadZip(e)).extractAllTo(t,!0)},G=new Ge(`YYYY-MM-DD [at] HH:mm:ss`),Nn=new Ge(`YYYY-MM-DD[
|
|
53
53
|
]HH:mm:ss`),Pn=new Ge(`YYYY-MM-DD`),Fn=new He,K=new He({[We.Day]:{DEFAULT:`d`},[We.Hour]:{DEFAULT:`h`},[We.Minute]:{DEFAULT:`m`},[We.Month]:{DEFAULT:`M`},[We.Second]:{DEFAULT:`s`},[We.Week]:{DEFAULT:`w`},[We.Year]:{DEFAULT:`y`}});function objectGroupBy(e,t){if(`groupBy`in Object)return Object.groupBy(e,t);let n={},r=0;for(let i of e){let e=t(i,r++);n[e]||(n[e]=[]),n[e].push(i)}return n}function printJsonToStdout(e){console.log(JSON.stringify(e,null,2))}const userHomeDir=()=>e.env.HOME??ce(),tildify=e=>{let t=userHomeDir();return t&&e.startsWith(t)?e.replace(t,`~`):e};function detectShell(){let t=e.env.SHELL??``;return t.includes(`zsh`)?`zsh`:t.includes(`bash`)?`bash`:t.includes(`fish`)?`fish`:`unknown`}function shellConfigFile(t,n){switch(n){case`bash`:{let n=[u(t,`.bashrc`),u(t,`.bash_profile`)];e.env.XDG_CONFIG_HOME&&n.push(u(e.env.XDG_CONFIG_HOME,`.bashrc`),u(e.env.XDG_CONFIG_HOME,`.bash_profile`),u(e.env.XDG_CONFIG_HOME,`bashrc`),u(e.env.XDG_CONFIG_HOME,`bash_profile`));for(let e of n)if(D(e))return e;return null}case`zsh`:{let n=e.env.ZDOTDIR||t||userHomeDir();return u(n,`.zshrc`)}case`fish`:return u(t,`.config`,`fish`,`config.fish`);case`unknown`:return null}}function parseWaitForFinishMillis(e){if(e===void 0)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<0))return t*1e3}const In=[`Apify collects telemetry data about general usage of Apify CLI to help us improve the product.`,`This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1", or by running "apify telemetry disable".`,`You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry.`].join(`
|
|
54
|
-
`);function createAnonymousId(){return`CLI:${ze()}`}async function migrateStateV0ToV1(e){if(e.version&&e.version>=1)return!1;let t=e,n=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0},e=>{n.id&&t.distinctId===n.id?(e.anonymousId=createAnonymousId(),e.userId=n.id):e.anonymousId=t.distinctId}),!0}async function useTelemetryState(){let e=TELEMETRY_FILE_PATH();if(!D(e)){let e=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0,anonymousId:createAnonymousId(),userId:e.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||[`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&info({message:In}),useTelemetryState()}let t=JSON.parse(A(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n);let r=TELEMETRY_FILE_PATH(),i=c(r);k(i,{recursive:!0}),N(TELEMETRY_FILE_PATH(),JSON.stringify(n,null,` `))}async function updateUserId(e){updateTelemetryState(await useTelemetryState(),t=>{t.userId=e})}async function checkAndUpdateLastCommand(e){try{let t=await useTelemetryState(),n=Date.now(),r=t.lastCommand===e&&n-(t.lastCommandTimestamp??0)<1e4;return updateTelemetryState(t,t=>{t.lastCommand=e,t.lastCommandTimestamp=n}),r}catch{return!1}}async function updateTelemetryEnabled(e){updateTelemetryState(await useTelemetryState(),t=>{t.enabled=e})}async function useTelemetryEnabled(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&![`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return cliDebugPrint(`telemetry`,`disabled by env variable`),!1;let e=await useTelemetryState();return cliDebugPrint(`telemetry state`,{telemetryState:e}),e.enabled}async function useTelemetryIdentifiers(){let e=await useTelemetryState();return{anonymousId:e.anonymousId,userId:e.userId}}const Ln=useCLIMetadata(),Rn=Ln.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:Ln.version,build:Ln.hash},library:{name:`apify-cli`,version:Ln.version},os:{name:Ln.platform},userAgent:fn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Rn};if(cliDebugPrint(`trackEvent`,r),!await useTelemetryEnabled()){cliDebugPrint(`trackEvent`,`telemetry disabled`);return}try{let e=await fetch(`https://api.segment.io/v1/track`,{method:`POST`,body:JSON.stringify(r)});if(!e.ok){cliDebugPrint(`trackEvent`,`failed to send event`,await e.text());return}cliDebugPrint(`trackEvent`,`event sent`)}catch(e){cliDebugPrint(`trackEvent`,`failed to send event`,e)}}function camelCaseString(e){return e.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}function kebabCaseString(e){return e.replace(/[\s_]+/g,`-`)}function camelCaseToKebabCase(e){return e.replace(/([A-Z])/g,`-$1`).toLowerCase()}const zn={type:`boolean`,multiple:!1,short:`h`},Bn={type:`boolean`,multiple:!1},Vn={type:`string`,multiple:!1},Hn=`user-agent`,Un=new Set([`apify`]);function sanitizeUserAgentValue(e){if(typeof e!=`string`)return;let t=e.replace(/[\u0000-\u001f\u007f]/g,``).trim();if(t)return t.length>256?t.slice(0,256):t}function resolveUserAgentForTelemetry(e,t){return sanitizeUserAgentValue(e)??sanitizeUserAgentValue(t)}const q=new Map,Wn=[`init`,`run`,`push`,`actors push`,`pull`,`actors pull`,`call`,`actors call`,`actors start`];var ApifyCommand=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static group;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;constructor(e,t,n,r){this.entrypoint=e,this.commandString=t,this.aliasUsed=n,this.subcommandAliasUsed=r;let i=useCLIMetadata();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e;let a=detectCi();this.telemetryData.aiAgent=detectAiAgent(),this.telemetryData.isCi=a.isCi,this.telemetryData.ciProvider=a.ciProvider,this.telemetryData.isInteractive=detectIsInteractive()}get ctor(){return this.constructor}pluralString(e,t,n){return e===1?t:n}static printHelp(){console.log(renderHelpForCommand(this)),e.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(t){let n=Date.now(),{values:r,positionals:i,tokens:a}=t;if(r.help&&this.ctor.printHelp(),Un.has(this.entrypoint)){let t=r[Hn],n=resolveUserAgentForTelemetry(typeof t==`string`?t:void 0,e.env.APIFY_CLI_USER_AGENT);n&&(this.telemetryData.userAgent=n)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof r.json==`boolean`?this.flags.json=r.json:this.flags.json=!1,this.flags.json&&keepStdoutClean());let s=new Map;if(this.ctor.args){let e=0;for(let[t,n]of Object.entries(this.ctor.args)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let r=camelCaseString(t),a=i[e++];a?(n.argTag,this.args[r]=String(a),a===`-`&&n.stdin&&(this.args[r]=this._handleStdin(n.stdin)),n.catchAll&&(this.args[r]=i.slice(e-1).join(` `))):n.required&&s.set(t,n)}}if(s.size){e.exitCode=1,this._printMissingRequiredArgs(s);return}this._parseFlags(r,a);try{await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Wn.includes(this.commandString)&&(await useCwdProject()).inspect(e=>{e.type===0?(this.telemetryData.actorLanguage=`javascript`,this.telemetryData.actorRuntime=e.runtime.runtimeShorthand||`node`,this.telemetryData.actorRuntimeVersion=e.runtime.version):(e.type===1||e.type===2)&&(this.telemetryData.actorLanguage=`python`,this.telemetryData.actorRuntime=`python`,this.telemetryData.actorRuntimeVersion=e.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof e.exitCode==`number`?e.exitCode:0,this.telemetryData.durationMs=Date.now()-n,this.telemetryData.wasRetried=await checkAndUpdateLastCommand(this.commandString),await trackEvent(`cli_command`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let n=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),r=n;n.startsWith(`no-`)&&(r=n.slice(3));let i=new Set;for(let e of t.aliases??[])i.add(kebabCaseString(camelCaseToKebabCase(e)).toLowerCase());return{baseFlagName:r,rawBaseFlagName:n,allMatchers:[r,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();return t.startsWith(`no-`)&&(t=t.slice(3)),t}_parseFlags(e,n){if(!this.ctor.flags)return;let r=new Map,i;for(let[a,s]of Object.entries(this.ctor.flags)){if(typeof s==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let{allMatchers:c,baseFlagName:l,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(a,s),f=camelCaseString(u),p=n.some(e=>e.kind===`option`&&e.name===l);if(s.exclusive?.length){let e=r.get(l)??new Set;for(let t of s.exclusive)e.add(this._commandFlagKeyToKebabCaseRegisteredName(t));r.set(l,e);for(let e of s.exclusive){let t=this._commandFlagKeyToKebabCaseRegisteredName(e),n=r.get(t)??new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>e
|
|
54
|
+
`);function createAnonymousId(){return`CLI:${ze()}`}async function migrateStateV0ToV1(e){if(e.version&&e.version>=1)return!1;let t=e,n=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0},e=>{n.id&&t.distinctId===n.id?(e.anonymousId=createAnonymousId(),e.userId=n.id):e.anonymousId=t.distinctId}),!0}async function useTelemetryState(){let e=TELEMETRY_FILE_PATH();if(!D(e)){let e=await getLocalUserInfo().catch(()=>({}));return updateTelemetryState({version:1,enabled:!0,anonymousId:createAnonymousId(),userId:e.id}),(!process.env.APIFY_CLI_DISABLE_TELEMETRY||[`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))&&info({message:In}),useTelemetryState()}let t=JSON.parse(A(e,`utf-8`));return await migrateStateV0ToV1(t)?useTelemetryState():t}function updateTelemetryState(e,t){let n={...e};t?.(n);let r=TELEMETRY_FILE_PATH(),i=c(r);k(i,{recursive:!0}),N(TELEMETRY_FILE_PATH(),JSON.stringify(n,null,` `))}async function updateUserId(e){updateTelemetryState(await useTelemetryState(),t=>{t.userId=e})}async function checkAndUpdateLastCommand(e){try{let t=await useTelemetryState(),n=Date.now(),r=t.lastCommand===e&&n-(t.lastCommandTimestamp??0)<1e4;return updateTelemetryState(t,t=>{t.lastCommand=e,t.lastCommandTimestamp=n}),r}catch{return!1}}async function updateTelemetryEnabled(e){updateTelemetryState(await useTelemetryState(),t=>{t.enabled=e})}async function useTelemetryEnabled(){if(process.env.APIFY_CLI_DISABLE_TELEMETRY&&![`false`,`0`].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY))return cliDebugPrint(`telemetry`,`disabled by env variable`),!1;let e=await useTelemetryState();return cliDebugPrint(`telemetry state`,{telemetryState:e}),e.enabled}async function useTelemetryIdentifiers(){let e=await useTelemetryState();return{anonymousId:e.anonymousId,userId:e.userId}}const Ln=useCLIMetadata(),Rn=Ln.isBeta?`rT67mFpIQD5qS9bJBoIYSFbZucrt2DZC`:`2uPK6yhPqjC0eNUFhaY78S26cRKyaa6t`;async function trackEvent(e,t){let n=await useTelemetryIdentifiers(),r={anonymousId:n.anonymousId,context:{app:{name:`apify-cli`,version:Ln.version,build:Ln.hash},library:{name:`apify-cli`,version:Ln.version},os:{name:Ln.platform},userAgent:fn,channel:`server`},event:e,properties:{...t,app:`cli`},timestamp:new Date().toISOString(),userId:n.userId,writeKey:Rn};if(cliDebugPrint(`trackEvent`,r),!await useTelemetryEnabled()){cliDebugPrint(`trackEvent`,`telemetry disabled`);return}try{let e=await fetch(`https://api.segment.io/v1/track`,{method:`POST`,body:JSON.stringify(r)});if(!e.ok){cliDebugPrint(`trackEvent`,`failed to send event`,await e.text());return}cliDebugPrint(`trackEvent`,`event sent`)}catch(e){cliDebugPrint(`trackEvent`,`failed to send event`,e)}}function camelCaseString(e){return e.replace(/[-_\s](.)/g,(e,t)=>t.toUpperCase())}function kebabCaseString(e){return e.replace(/[\s_]+/g,`-`)}function camelCaseToKebabCase(e){return e.replace(/([A-Z])/g,`-$1`).toLowerCase()}const zn={type:`boolean`,multiple:!1,short:`h`},Bn={type:`boolean`,multiple:!1},Vn={type:`string`,multiple:!1},Hn=`user-agent`,Un=new Set([`apify`]);function sanitizeUserAgentValue(e){if(typeof e!=`string`)return;let t=e.replace(/[\u0000-\u001f\u007f]/g,``).trim();if(t)return t.length>256?t.slice(0,256):t}function resolveUserAgentForTelemetry(e,t){return sanitizeUserAgentValue(e)??sanitizeUserAgentValue(t)}const q=new Map,Wn=[`init`,`run`,`push`,`actors push`,`pull`,`actors pull`,`call`,`actors call`,`actors start`];var ApifyCommand=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static examples;static docsUrl;static interactive;static interactiveNote;static group;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;commandString;aliasUsed;subcommandAliasUsed;skipTelemetry=!1;constructor(e,t,n,r){this.entrypoint=e,this.commandString=t,this.aliasUsed=n,this.subcommandAliasUsed=r;let i=useCLIMetadata();this.telemetryData.installMethod=i.installMethod,this.telemetryData.osArch=i.arch,this.telemetryData.runtime=i.runtime.runtime,this.telemetryData.runtimeVersion=i.runtime.version,this.telemetryData.runtimeNodeVersion=i.runtime.nodeVersion??i.runtime.version,this.telemetryData.commandString=t,this.telemetryData.entrypoint=e;let a=detectCi();this.telemetryData.aiAgent=detectAiAgent(),this.telemetryData.isCi=a.isCi,this.telemetryData.ciProvider=a.ciProvider,this.telemetryData.isInteractive=detectIsInteractive()}get ctor(){return this.constructor}pluralString(e,t,n){return e===1?t:n}static printHelp(){console.log(renderHelpForCommand(this)),e.exit(0)}printHelp(){return this.ctor.printHelp()}async _run(t){let n=Date.now(),{values:r,positionals:i,tokens:a}=t;if(r.help&&this.ctor.printHelp(),Un.has(this.entrypoint)){let t=r[Hn],n=resolveUserAgentForTelemetry(typeof t==`string`?t:void 0,e.env.APIFY_CLI_USER_AGENT);n&&(this.telemetryData.userAgent=n)}this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof r.json==`boolean`?this.flags.json=r.json:this.flags.json=!1,this.flags.json&&keepStdoutClean());let s=new Map;if(this.ctor.args){let e=0;for(let[t,n]of Object.entries(this.ctor.args)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let r=camelCaseString(t),a=i[e++];a?(n.argTag,this.args[r]=String(a),a===`-`&&n.stdin&&(this.args[r]=this._handleStdin(n.stdin)),n.catchAll&&(this.args[r]=i.slice(e-1).join(` `))):n.required&&s.set(t,n)}}if(s.size){e.exitCode=1,this._printMissingRequiredArgs(s);return}this._parseFlags(r,a);try{await this.run()}catch(t){error({message:t.message}),e.exitCode||=1}finally{!this.telemetryData.actorLanguage&&Wn.includes(this.commandString)&&(await useCwdProject()).inspect(e=>{e.type===0?(this.telemetryData.actorLanguage=`javascript`,this.telemetryData.actorRuntime=e.runtime.runtimeShorthand||`node`,this.telemetryData.actorRuntimeVersion=e.runtime.version):(e.type===1||e.type===2)&&(this.telemetryData.actorLanguage=`python`,this.telemetryData.actorRuntime=`python`,this.telemetryData.actorRuntimeVersion=e.runtime.version)}),this.skipTelemetry||(this.telemetryData.flagsUsed=Object.keys(this.flags),this.telemetryData.exitCode=typeof e.exitCode==`number`?e.exitCode:0,this.telemetryData.durationMs=Date.now()-n,this.telemetryData.wasRetried=await checkAndUpdateLastCommand(this.commandString),await trackEvent(`cli_command`,this.telemetryData))}}_userFlagNameToRegisteredName(e,t){let n=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),r=n;n.startsWith(`no-`)&&(r=n.slice(3));let i=new Set;for(let e of t.aliases??[])i.add(kebabCaseString(camelCaseToKebabCase(e)).toLowerCase());return{baseFlagName:r,rawBaseFlagName:n,allMatchers:[r,...i]}}_commandFlagKeyToKebabCaseRegisteredName(e){let t=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();return t.startsWith(`no-`)&&(t=t.slice(3)),t}_parseFlags(e,n){if(!this.ctor.flags)return;let r=new Map,i;for(let[a,s]of Object.entries(this.ctor.flags)){if(typeof s==`string`)throw RangeError(`Do not provide the string for the json arg! It is a type level assertion!`);let{allMatchers:c,baseFlagName:l,rawBaseFlagName:u}=this._userFlagNameToRegisteredName(a,s),f=camelCaseString(u),p=n.some(e=>e.kind===`option`&&e.name===l);if(s.exclusive?.length){let e=r.get(l)??new Set;for(let t of s.exclusive)e.add(this._commandFlagKeyToKebabCaseRegisteredName(t));r.set(l,e);for(let e of s.exclusive){let t=this._commandFlagKeyToKebabCaseRegisteredName(e),n=r.get(t)??new Set;n.add(l),r.set(t,n)}}let m=c.filter(t=>Object.hasOwn(e,t));if(m.length>1)throw new U({code:3,command:this.ctor,metadata:{flag:l}});let h=e[m[0]];if(!h&&s.required)throw new U({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0]}});if(Array.isArray(h)){if(h.length>1)throw new U({code:3,command:this.ctor,metadata:{flag:l}});h=h[0]}if(p&&typeof h==`string`&&h.startsWith(`=`)&&(h=h.slice(1)),h!==void 0)switch(s.flagTag){case`boolean`:this.flags[f]=u.startsWith(`no-`)?!h:h;break;case`integer`:{let e=Number(h);if(Number.isNaN(e)||!Number.isInteger(e))throw new U({code:4,command:this.ctor,metadata:{flag:l,value:String(h)}});this.flags[f]=e;break}default:if(this.flags[f]=h,h===`-`&&s.stdin){if(i)throw new U({code:8,command:this.ctor,metadata:{firstUse:i,secondUse:l}});i=l,this.flags[f]=this._handleStdin(s.stdin)}}else s.hasDefault!==void 0&&(this.flags[f]=s.hasDefault);if(this.flags[f]!=null&&s.choices&&!s.choices.includes(this.flags[f]))throw new U({code:5,command:this.ctor,metadata:{flag:l,choices:s.choices.map(e=>t.white.bold(e)).join(`, `)}});if(this.flags[f]==null&&(s.required||h!=null))throw new U({code:6,command:this.ctor,metadata:{flag:l,matcher:m[0],providedButReceivedNoValue:!!h}})}let a=[];for(let[t,n]of r)if(e[t]!=null)for(let r of n){if(e[r]==null)continue;let n=e[t][0],i=e[r][0],flagRepresentation=(e,t)=>typeof t==`boolean`?t?`--${e}`:`--no-${e}`:`--${e}=${t}`;a.push([flagRepresentation(t,n),flagRepresentation(r,i)]);break}if(a.length)throw new U({code:7,command:this.ctor,metadata:{flagPairs:a}})}_printMissingRequiredArgs(e){let a;try{a=selectiveRenderHelpForCommand(this.ctor,{showUsageString:!0})}catch{}let s=r([...e.keys()].join(`
|
|
55
55
|
`)),c=[];for(let[r,a]of e){let e=`${r.padEnd(s)} ${a.description}`,l=i(e,getMaxLineWidth()-s-2),u=n(l,s+2+2).trim();c.push(` ${t.red(`>`)} ${u}`)}let l=[`Missing ${e.size} required ${this.pluralString(e.size,`argument`,`arguments`)}:`,...c,t.gray(` See more help with --help`)];a&&l.push(``,a),error({message:l.join(`
|
|
56
56
|
`)})}_handleStdin(e){switch(e){case 2:return(un?.toString(`utf8`)??``).trim();default:return un}}_buildParseArgsOption(){let e={help:zn};Un.has(this.entrypoint)&&(e[Hn]=Vn);let t={allowNegative:!0,allowPositionals:!0,strict:!0,tokens:!0,options:e};if(this.ctor.flags)for(let[e,n]of Object.entries(this.ctor.flags)){if(typeof n==`string`)throw RangeError(`Do not provide the string for the json flag! It is a type level assertion!`);if(e.toLowerCase()===`json`)continue;let r=kebabCaseString(camelCaseToKebabCase(e)).toLowerCase();r.startsWith(`no-`)&&(r=r.slice(3));let i=n.builder(r);for(let{flagName:e,option:n}of i)t.options[e]=n}return this.ctor.enableJsonFlag&&(t.options.json=Bn),t}static registerCommand(e){if(registerCommandForHelpGeneration(e,this),q.set(this.name,this),this.aliases?.length)for(let e of this.aliases)q.set(e,this);if(this.hiddenAliases?.length)for(let e of this.hiddenAliases)q.set(e,this);if(this.subcommands?.length)for(let e of this.subcommands){if(q.set(`${this.name} ${e.name}`,e),this.aliases?.length)for(let t of this.aliases)q.set(`${t} ${e.name}`,e);if(this.hiddenAliases?.length)for(let t of this.hiddenAliases)q.set(`${t} ${e.name}`,e);if(e.aliases?.length)for(let t of e.aliases){if(q.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)q.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)q.set(`${n} ${t}`,e)}if(e.hiddenAliases?.length)for(let t of e.hiddenAliases){if(q.set(`${this.name} ${t}`,e),this.aliases?.length)for(let n of this.aliases)q.set(`${n} ${t}`,e);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)q.set(`${n} ${t}`,e)}}}};async function internalRunCommand(e,t,n){let r={positionals:[],values:{},tokens:[]},i=0;for(let[e,t]of Object.entries(n)){let[n,a]=e.split(`_`);if(n===`args`)r.positionals[i++]=t;else{let e=kebabCaseString(camelCaseToKebabCase(a)).toLowerCase();e.startsWith(`no-`)?r.values[e.slice(3)]=!t:r.values[e]=t}}let a=new t(e,t.name,t.name);return a.skipTelemetry=!0,await a._run(r),a}const J={string:stringFlag,boolean:booleanFlag,integer:integerFlag};function YesFlag(e=`Automatic yes to prompts; assume "yes" as answer to all prompts.`){return{yes:J.boolean({char:`y`,description:e,default:!1})}}function stringFlag(e){return{flagTag:`string`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:e.choices,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??2,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function booleanFlag(e){return{flagTag:`boolean`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`boolean`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`boolean`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function integerFlag(e){return{flagTag:`integer`,builder:t=>{let n=new Set([...e.aliases??[]]);n.delete(t);let r=[{flagName:t,option:{type:`string`,multiple:!0}}];e.char&&(r[0].option.short=e.char);for(let e of n)r.push({flagName:kebabCaseString(camelCaseToKebabCase(e)).toLowerCase(),option:{type:`string`,multiple:!0}});return r},choices:null,required:e.required??!1,hasDefault:e.default,stdin:e.stdin??1,description:e.description,aliases:e.aliases,char:e.char,hidden:e.hidden,exclusive:e.exclusive}}function getBooleanValue(e,t){let n=t!==!1;return/^(y|yes)/i.test(e)?n=!0:/^(n|no)/i.test(e)&&(n=!1),n}function boolToString(e){return e?`Yes`:`No`}const Gn=ct((e,t)=>{let n=boolToString,[r,i]=pt(`idle`),[a,s]=pt(``),c=ut(),l=ft({status:r,theme:c});dt((r,c)=>{if(lt(r)){let r=getBooleanValue(a,e.default);s(n(r)),i(`done`),t(r);return}if(r.name===`tab`){let t=boolToString(!getBooleanValue(a,e.default));c.clearLine(0),c.write(t),s(t);return}if(r.name===`y`||r.name===`n`){let a=getBooleanValue(r.name,e.default);s(n(a)),i(`done`),t(a);return}c.clearLine(0),c.write(a),s(c.line)});let u=a,f=``;return r===`done`?u=c.style.answer(a):f=` ${c.style.defaultAnswer(e.default===!1?`y/N`:`Y/n`)}`,`${l} ${c.style.message(e.message,r)}${f} ${u}`}),Y=stdinCheckWrapper(async({message:e,default:t})=>await Gn({message:e,default:t},pn)),getDeprecatedLocalConfigPath=e=>u(e,`apify.json`),Kn=new Map;async function useActorConfig({cwd:t=e.cwd(),migrateConfig:n=!0,warnAboutOldConfig:r=!0}={cwd:e.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let i=Kn.get(t);if(i)return cliDebugPrint(`useActorConfig`,{cacheHit:!0,config:i}),Te(i);let a=getLocalConfigPath(t),s=getDeprecatedLocalConfigPath(t),c,l;try{c=getJsonFileContent(a)}catch(e){return we({message:`Failed to read local config at path: '${a}':`,cause:e,exists:!1,config:{}})}try{l=getJsonFileContent(s)}catch(e){return we({message:`Failed to read local config at path: '${s}':`,cause:e,exists:!1,config:{}})}if(c&&l&&r&&await handleBothConfigVersionsFound(s),!c&&!l)return Kn.set(t,{exists:!1,migrated:!1,config:{}}),Te({exists:!1,migrated:!1,config:{}});let u=!1;if(!c&&l&&n){let e=await handleMigrationFlow(l,s,a);if(e.isErr())return we(e.unwrapErr());c=e.unwrap(),u=!0}return Kn.set(t,{exists:!0,migrated:u,config:c||l||{}}),cliDebugPrint(`useActorConfig`,{cacheHit:!1,config:Kn.get(t)}),Te({exists:!0,migrated:u,config:c||l||{}})}async function handleBothConfigVersionsFound(e){if(!await Y({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?`})){warning({message:`The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.`});return}try{await je(e,`${e}.deprecated`),info({message:`The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.`})}catch(e){e instanceof Error?error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${e.message||e}`}):error({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${h(e,{showHidden:!1})}`})}}const qn=[`name`,`version`,`buildTag`];async function handleMigrationFlow(e,t,n){let r={...e};if(typeof r.version==`object`&&(r=updateLocalConfigStructure(r)),r={actorSpecification:1,environmentVariables:e?.env||void 0,...qn.reduce((t,n)=>(t[n]=e[n],t),{})},!await Y({message:`The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?`}))return we({message:`Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.`,exists:!0,config:r});try{await R(c(n),{recursive:!0}),await V(n,JSON.stringify(r,null,` `))}catch(e){let t=e;return we({message:`Failed to write the new "actor.json" file to path: '${n}'.\n ${t.message||t}`,exists:!0,config:r})}try{await je(t,`${t}.deprecated`)}catch(e){let t=e;warning({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".\n ${t.message||t}`})}return info({message:`The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.`}),Te(r)}function updateLocalConfigStructure(e){let t={name:e.name,template:e.template,version:e.version.versionNumber,buildTag:e.version.buildTag,env:null};if(e.version.envVars?.length){let n={};e.version.envVars.forEach(e=>{e.name&&e.value&&(n[e.name]=e.value)}),t.env=n}return t}const Jn=u(getLocalKeyValueStorePath(`default`),`INPUT.json`);var ActorCalculateMemoryCommand=class extends ApifyCommand{static name=`calculate-memory`;static description=`Calculates the Actor’s dynamic memory usage based on a memory expression from actor.json, input data, and run options.`;static group=`Actor Runtime`;static examples=[{description:`Calculate memory using the expression and input defaults from actor.json.`,command:`actor calculate-memory`},{description:`Override the memory expression and input file.`,command:`actor calculate-memory --defaultMemoryMbytes "input.length * 128" --input ./my-input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-calculate-memory`;static flags={input:J.string({description:`Path to the input JSON file used for the calculation.`,required:!1,default:Jn}),defaultMemoryMbytes:J.string({description:`Memory-calculation expression (in MB). If omitted, the value is loaded from the actor.json file.`,required:!1}),build:J.string({description:`Actor build version or build tag to evaluate the expression with.`,required:!1}),timeoutSecs:J.integer({description:`Maximum run timeout, in seconds.`,required:!1}),maxItems:J.integer({description:`Maximum number of items Actor can output.`,required:!1}),maxTotalChargeUsd:J.integer({description:`Maximum total charge in USD.`,required:!1})};async run(){let{input:t,memoryExpression:n,minMemory:r,maxMemory:i,runOptions:a}=await this.prepareMemoryArguments();if(!n)throw Error(`No memory-calculation expression found. Provide it via the --default-memory-mbytes flag or define defaultMemoryMbytes in actor.json.`);let s=p(e.cwd(),t),c=getJsonFileContent(s)??{};info({message:`Evaluating memory expression: ${n}`});try{let e=await ot(n,{input:c,runOptions:a});success({message:`Calculated memory: ${Math.min(Math.max(e,r),i)} MB`,stdout:!0})}catch(e){error({message:`Memory calculation failed: ${e.message}`})}}async prepareMemoryArguments(){let{input:e,defaultMemoryMbytes:t,...n}=this.flags,r=t,i=0,a=1/0;return r||({defaultMemoryMbytes:r,minMemoryMbytes:i=i,maxMemoryMbytes:a=a}=await this.getExpressionFromConfig()),{memoryExpression:r,minMemory:i,maxMemory:a,input:e,runOptions:n}}async getExpressionFromConfig(){let t=await useActorConfig({cwd:e.cwd()});if(t.isErr()){let{message:n,cause:r}=t.unwrapErr();return error({message:`${n}${r?`\n ${r.message}`:``}`}),e.exitCode=5,{}}let{config:n}=t.unwrap();return{defaultMemoryMbytes:n?.defaultMemoryMbytes?.toString(),minMemoryMbytes:n?.minMemoryMbytes,maxMemoryMbytes:n?.maxMemoryMbytes}}};const Yn={KEY_VALUE_STORE:`KEY_VALUE_STORE`,DATASET:`DATASET`,REQUEST_QUEUE:`REQUEST_QUEUE`},getApifyTokenFromEnvOrAuthFile=async()=>{let t=e.env[I.TOKEN];if(t)return t;let n=await getLocalUserInfo();if(!n||!n.token)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.`);return n.token},getApifyStorageClient=async(t={},n=Reflect.has(e.env,I.IS_AT_HOME))=>{let r=getLocalStorageDir();if(r&&!n)return new ht({localDataDirectory:r,...t});let i=await getApifyTokenFromEnvOrAuthFile();return new Je({...await getApifyClientOptions(i),...t})},getDefaultStorageId=t=>{let n=P[`DEFAULT_${t}_ID`];return e.env[n]||ge[n]},outputRecordFromDefaultStore=async t=>{let n=await getApifyStorageClient(),r=getDefaultStorageId(Yn.KEY_VALUE_STORE),i=await n.keyValueStore(r).getRecord(t,{stream:!0});i&&await mt(i.value,e.stdout,{end:!1})},outputInputFromDefaultStore=async()=>outputRecordFromDefaultStore(e.env[P.INPUT_KEY]||he.INPUT);function stringArg(e){return{argTag:`string`,required:e.required??!1,stdin:e.stdin??1,description:e.description,aliases:e.aliases,catchAll:e.catchAll??!1}}const X={string:stringArg};var ActorChargeCommand=class extends ApifyCommand{static name=`charge`;static description=`Charge for a specific event in a pay-per-event Actor run.`;static group=`Actor Runtime`;static examples=[{description:`Charge one event of the given type.`,command:`actor charge result-item`},{description:`Charge 5 events with an idempotency key.`,command:`actor charge result-item --count 5 --idempotency-key req-123`},{description:`Test locally without actually charging.`,command:`actor charge result-item --test-pay-per-event`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#actor-charge`;static args={eventName:X.string({description:`Name of the event to charge for.`,required:!0})};static flags={count:J.integer({description:`Number of events to charge.`,required:!1,default:1}),"idempotency-key":J.string({description:`Idempotency key for the charge request.`,required:!1}),"test-pay-per-event":J.boolean({description:`Test pay-per-event charging without actually charging.`,required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:t,testPayPerEvent:n,idempotencyKey:r}=this.flags;if(!process.env.APIFY_IS_AT_HOME){info({message:`No platform detected: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}if(n){info({message:`PPE test mode: would charge ${t} events of type "${e}" with idempotency key "${r??`not-provided`}".`,stdout:!0});return}let i=await getLoggedClient(await getApifyTokenFromEnvOrAuthFile());if(!i)throw Error(`Apify token is not set. Please set it using the environment variable APIFY_TOKEN.`);let a=process.env[I.ACTOR_RUN_ID];if(!a)throw Error(`Charge command must be executed in a running Actor. Run ID not found.`);if((await i.run(a).get())?.pricingInfo?.pricingModel!==`PAY_PER_EVENT`)throw Error(`Charge command can only be used with pay-per-event pricing model.`);info({message:`Charging ${t} events of type "${e}" with idempotency key "${r??`not-provided`}" (runId: ${a}).`,stdout:!0}),await i.run(a).charge({eventName:e,count:t,idempotencyKey:r})}};const Xn=[`.actor/INPUT_SCHEMA.json`,`./INPUT_SCHEMA.json`,`.actor/input_schema.json`,`./input_schema.json`],readInputSchema=async({forcePath:e,cwd:t,throwOnMissing:n=!1})=>{if(e)return{inputSchema:getJsonFileContent(e),inputSchemaPath:e};let r=getLocalConfig(t);if(typeof r?.input==`object`&&r.input!==null)return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input==`string`){let e=u(t,en,r.input),i=getJsonFileContent(e);if(!i){if(n)throw Error(`Input schema file not found at ${e} (referenced in '${W}').`);return warning({message:`Input schema file not found at ${e} (referenced in '${W}').`}),{inputSchema:null,inputSchemaPath:e}}return{inputSchema:i,inputSchemaPath:e}}for(let e of Xn){let n=u(t,e);if(D(n))return{inputSchema:getJsonFileContent(n),inputSchemaPath:n}}return{inputSchema:null,inputSchemaPath:u(t,Xn[0])}},readAndValidateInputSchema=async({forcePath:e,cwd:t,getMessage:n})=>{let{inputSchema:r,inputSchemaPath:i}=await readInputSchema({forcePath:e,cwd:t});if(!r)throw Error(`Input schema has not been found at ${i}.`);info({message:n(i)});let a=new An({strict:!1});return _t(a,r),{inputSchema:r,inputSchemaPath:i}},readStorageSchema=({cwd:e,key:t,label:n,getRef:r,throwOnMissing:i=!1})=>{let a=getLocalConfig(e),s=r?r(a):a?.storages?.[t];if(typeof s==`object`&&s)return{schema:s,schemaPath:null};if(typeof s==`string`){let t=u(e,en,s),r=getJsonFileContent(t);if(!r){if(i)throw Error(`${n} schema file not found at ${t} (referenced in '${W}').`);return warning({message:`${n} schema file not found at ${t} (referenced in '${W}').`}),null}return{schema:r,schemaPath:t}}return null},readDatasetSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`dataset`,label:`Dataset`});return t?{datasetSchema:t.schema,datasetSchemaPath:t.schemaPath}:null},readOutputSchema=({cwd:e})=>{let t=readStorageSchema({cwd:e,key:`output`,label:`Output`,getRef:e=>e?.output});return t?{outputSchema:t.schema,outputSchemaPath:t.schemaPath}:null},createPrefilledInputFileFromInputSchema=async e=>{let t={};try{let{inputSchema:n}=await readInputSchema({cwd:e});if(n){let e=new An({strict:!1});_t(e,n),t=Object.entries(n.properties).reduce((e,[t,n])=>(e[t]=n.type===`boolean`||n.editor===`hidden`?n.default:n.prefill,e),{})}}catch(e){warning({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${e.message}`})}finally{let n=getLocalKeyValueStorePath(),r=u(e,n,`${he.INPUT}.json`);N(r,JSON.stringify(t,null,` `))}},getDefaultsFromInputSchema=e=>{let t={};for(let[n,r]of Object.entries(e.properties))r.default!==void 0&&(t[n]=r.default);return t};function formatSchemaValidationErrors(e,t){return`${t} schema is not valid:\n${e.map(e=>{let t=e.instancePath?` at ${e.instancePath}`:``;return` - ${e.message}${t}`}).join(`
|
|
57
57
|
`)}`}function validateDatasetSchema(e){let t=yt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Dataset`))}function validateOutputSchema(e){let t=xt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Output`))}function validateKvsSchema(e){let t=bt();if(!t(e))throw Error(formatSchemaValidationErrors(t.errors,`Key-Value Store`))}const getAjvValidator=(e,t)=>{let n=structuredClone(e);n.required=[];for(let[t,r]of Object.entries(e.properties)){let i=e.required?.includes(t),a=r.default!==void 0;i&&!a&&(n.required.push(t),r.type===`array`&&(r.minItems=Math.max(1,r.minItems||0)))}return delete n.$schema,t.compile(n)};function makePropertiesRequired(e){let t=structuredClone(e);if(!t.properties||typeof t.properties!=`object`)return t;let n=t.properties,r=new Set(Array.isArray(t.required)?t.required:[]);for(let[e,t]of Object.entries(n))t.default!==void 0&&r.add(e),t.type===`object`&&t.properties&&(n[e]=makePropertiesRequired(t));return t.required=Array.from(r),t}function clearAllRequired(e){let t=structuredClone(e);if(delete t.required,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n.type===`object`&&n.properties&&(e[t]=clearAllRequired(n))}return t}function stripTitles(e){let t=structuredClone(e);if(delete t.title,t.properties&&typeof t.properties==`object`){let e=t.properties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}t.items&&typeof t.items==`object`&&(t.items=stripTitles(t.items));for(let e of[`allOf`,`anyOf`,`oneOf`])Array.isArray(t[e])&&(t[e]=t[e].map(e=>e&&typeof e==`object`?stripTitles(e):e));for(let e of[`definitions`,`$defs`])if(t[e]&&typeof t[e]==`object`&&!Array.isArray(t[e])){let n=t[e];for(let[e,t]of Object.entries(n))t&&typeof t==`object`&&(n[e]=stripTitles(t))}t.additionalProperties&&typeof t.additionalProperties==`object`&&(t.additionalProperties=stripTitles(t.additionalProperties));for(let e of[`if`,`then`,`else`,`not`])t[e]&&typeof t[e]==`object`&&(t[e]=stripTitles(t[e]));if(t.patternProperties&&typeof t.patternProperties==`object`&&!Array.isArray(t.patternProperties)){let e=t.patternProperties;for(let[t,n]of Object.entries(e))n&&typeof n==`object`&&(e[t]=stripTitles(n))}return t}function prepareFieldsSchemaForCompilation(e){let t=e.fields;if(!t||typeof t!=`object`||!t.properties||typeof t.properties!=`object`)return null;let n=structuredClone(t);return n.type||=`object`,n}function prepareOutputSchemaForCompilation(e){let t=e.properties;if(!t||typeof t!=`object`||Object.keys(t).length===0)return null;let n=structuredClone(t);for(let e of Object.values(n))e&&typeof e==`object`&&delete e.template;let r={type:e.type||`object`,properties:n};return Array.isArray(e.required)&&(r.required=[...e.required]),r}function prepareKvsCollectionsForCompilation(e){let t=e.collections;if(!t||typeof t!=`object`)return[];let n=[];for(let[e,r]of Object.entries(t)){if(!r||typeof r!=`object`)continue;let t=r.jsonSchema;if(!t||typeof t!=`object`||Object.keys(t).length===0)continue;let i=structuredClone(t);i.type||=`object`,n.push({name:e,schema:i})}return n}var ActorGenerateSchemaTypesCommand=class extends ApifyCommand{static name=`generate-schema-types`;static hiddenAliases=[`generate-types`];static description=`Generate TypeScript types from Actor schemas.
|
|
@@ -110,7 +110,7 @@ Skipping push. Use --force to override.`)}C=await createSourceFiles(r,n),S=me.SO
|
|
|
110
110
|
`).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}j.exitCode&&(e.exitCode=j.exitCode);let N={ok:j.ok,operation:`push`,actor:{id:O.actId,url:te},build:{id:O.id,number:O.buildNumber,status:ee,url:ne}};if(j.exitCode!==void 0&&(N.exitCode=j.exitCode),j.errorMessage&&(N.error={phase:`build`,message:j.errorMessage,logTail:M}),this.flags.json){printJsonToStdout(N);return}simpleLog({stdout:!0,message:[`Apify push result: ${j.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${ee}`,`Actor ID: ${O.actId}`,`Build ID: ${O.id}`,`Build number: ${O.buildNumber}`,...j.exitCode?[`Exit code: ${j.exitCode}`]:[],``,`Actor URL: ${te}`,`Build URL: ${ne}`,...j.errorMessage&&M.length?[``,`Reason:`,...M]:[]].join(`
|
|
111
111
|
`)}),this.flags.open&&await Tt(te)}catch(e){t.e=e}finally{t.d()}}},ActorsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently removes an Actor from your account.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete an Actor by its full name (prompts for confirmation).`,command:`apify actors rm my-username/my-actor`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-rm`;static args={actorId:X.string({description:`The Actor ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{actorId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow();if(!await n.actor(e).get()){error({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await Y({message:`Are you sure you want to delete this Actor?`,providedConfirmFromStdin:t||void 0})){info({message:`Deletion of Actor "${e}" was canceled.`});return}try{await n.actor(e).delete(),success({message:`Actor with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete Actor "${e}".\n ${n.message||n}`})}}};const fr={FREE:`Free`,FLAT_PRICE_PER_MONTH:`Subscription`,PRICE_PER_DATASET_ITEM:`Pay per result`,PAY_PER_EVENT:`Pay per event`};function formatPricingModel(e){return e?fr[e]??e:t.gray(`Unknown`)}function truncateDescription(e,t=60){return e?e.length<=t?e:`${e.slice(0,t-1)}…`:``}var ActorsSearchCommand=class extends ApifyCommand{static name=`search`;static description=`Searches Actors in the Apify Store.
|
|
112
112
|
|
|
113
|
-
Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static examples=[{description:`Search the Apify Store for "web scraper" Actors.`,command:`apify actors search "web scraper"`},{description:`Search for TikTok Actors sorted by popularity, limit to 5 results.`,command:`apify actors search "tiktok" --limit 5 --sort-by popularity`},{description:`Find free AI Actors.`,command:`apify actors search "ai" --category AI --pricing-model FREE`},{description:`Output results as JSON for scripting.`,command:`apify actors search "web scraper" --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-search`;static args={query:X.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":J.string({description:`Sort order for the results.`,
|
|
113
|
+
Searches the Apify Store for Actors matching the given query. Results can be filtered by category, author, pricing model, and more. This command does not require authentication.`;static examples=[{description:`Search the Apify Store for "web scraper" Actors.`,command:`apify actors search "web scraper"`},{description:`Search for TikTok Actors sorted by popularity, limit to 5 results.`,command:`apify actors search "tiktok" --limit 5 --sort-by popularity`},{description:`Find free AI Actors.`,command:`apify actors search "ai" --category AI --pricing-model FREE`},{description:`Output results as JSON for scripting.`,command:`apify actors search "web scraper" --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-search`;static args={query:X.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":J.string({description:`Sort order for the results.`,choices:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:J.string({description:`Filter by category (e.g. AI).`}),username:J.string({description:`Filter by Actor author username.`}),"pricing-model":J.string({description:`Filter by pricing model.`,choices:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:J.integer({description:`Maximum number of results to return.`,default:20}),offset:J.integer({description:`Number of results to skip for pagination.`,default:0})};static enableJsonFlag=!0;async run(){let{query:e}=this.args,{json:n,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l}=this.flags,u=await getApifyClientOptions();delete u.token;let f=new Je(u),p;try{p=await f.store().list({search:e,sortBy:r,category:i,username:a,pricingModel:s,limit:c,offset:l})}catch(e){process.exitCode=1,error({message:`Failed to search Apify Store: ${e instanceof Error?e.message:String(e)}`,stdout:!0});return}if(p.count===0){if(n){printJsonToStdout(p);return}info({message:`No Actors found matching your search.`,stdout:!0});return}if(n){printJsonToStdout(p);return}let m=new Z({allColumns:[`Name`,`Description`,`Users (30d)`,`Pricing`],mandatoryColumns:[`Name`,`Pricing`],columnAlignments:{"Users (30d)":`right`,Name:`left`}});for(let e of p.items)m.pushRow({Name:`${e.title}\n${t.gray(`${e.username}/${e.name}`)}`,Description:truncateDescription(e.description),"Users (30d)":t.cyan(`${e.stats?.totalUsers30Days??0}`),Pricing:formatPricingModel(e.currentPricingInfo?.pricingModel)});simpleLog({message:m.render(1),stdout:!0})}},ActorsStartCommand=class extends ApifyCommand{static name=`start`;static description=`Starts Actor remotely and returns run details immediately.
|
|
114
114
|
Uses authenticated account and local key-value store for input.`;static examples=[{description:`Start the Actor defined in the current directory and return immediately.`,command:`apify actors start`},{description:`Start a specific Actor with inline JSON input.`,command:`apify actors start apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Start with input from a file and custom memory/timeout.`,command:`apify actors start apify/web-scraper --input-file ./input.json --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-start`;static flags={...SharedRunOnCloudFlags(`Actor`),input:J.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":J.string({aliases:[`if`],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:[`input`]})};static enableJsonFlag=!0;static args={actorId:X.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${W}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getLocalUserInfo(),s=a.username||a.id,{id:c,userFriendlyId:l,actorData:u}=await er.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={};this.flags.build&&(f.build=this.flags.build),this.flags.timeout&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile);if(p===!1)return;let m=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),h;for await(let e of m)h=e;if(!h){simpleLog({message:`Actor run did not start.`,stdout:!1}),e.exitCode=1;return}let g=consoleRunUrl(c,h.id);if(this.flags.json){printJsonToStdout({ok:!0,operation:`actors.start`,waited:!1,actor:{id:c,url:`${getConsoleUrl()}/actors/${c}`},run:{id:h.id,status:h.status,url:g},next:{wait:`apify runs wait ${h.id} --json`,log:`apify runs log ${h.id}`,info:`apify runs info ${h.id} --json`},exitCode:0});return}simpleLog({message:[t.greenBright(`Run started.`),``,`${t.yellow(`Actor`)}: ${u.name} (${t.gray(c)})`,`${t.yellow(`Run ID`)}: ${h.id}`,`${t.yellow(`Status`)}: ${h.status}`,``,t.gray(`This command does not wait for the run to finish.`),``,`To wait for the final status:`,` apify runs wait ${h.id} --json`,``,`To stream or inspect logs:`,` apify runs log ${h.id}`,``,`To inspect run metadata:`,` apify runs info ${h.id} --json`].join(`
|
|
115
115
|
`),stdout:!0})}},ActorsIndexCommand=class extends ApifyCommand{static name=`actors`;static description=`Search, list, deploy, and call Actors on the Apify platform.
|
|
116
116
|
For runtime operations inside a running Actor (push-data, get-input, set-value...), see 'apify actor' (singular).`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors`;static subcommands=[ActorsStartCommand,ActorsRmCommand,ActorsSearchCommand,ActorsPushCommand,ActorsPullCommand,ActorsLsCommand,ActorsInfoCommand,er,ActorsBuildCommand];async run(){this.printHelp()}};const pr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],mr=new Set([`GET`,`HEAD`]),hr=`https://docs.apify.com/api/openapi.json`;function parseParams(e){if(!e)return``;let t;try{t=JSON.parse(e)}catch{throw Error(`Invalid JSON in --params flag. Please provide a valid JSON object, e.g. '{"limit": 1}'.`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`--params must be a JSON object (e.g. '{"limit": 1}').`);let n=new URLSearchParams;for(let[e,r]of Object.entries(t))if(r!=null){if(typeof r==`object`)throw Error(`--params value for "${e}" must be a scalar (string, number, or boolean), got ${Array.isArray(r)?`array`:`object`}. Query parameters cannot contain nested objects or arrays.`);n.append(e,String(r))}return n.toString()}function parseHeaders(e){if(!e)return{};let t=e.trim();if(t.startsWith(`{`)){let e;try{e=JSON.parse(t)}catch{throw Error(`Invalid JSON in --header flag. Provide a JSON object like '{"X-Foo": "bar"}'.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`--header JSON must be an object mapping header names to string values.`);let n={};for(let[t,r]of Object.entries(e)){if(typeof r!=`string`)throw Error(`--header value for "${t}" must be a string, got ${typeof r}.`);n[t.trim()]=r.trim()}return n}let n=t.indexOf(`:`);if(n===-1)throw Error(`Header must be in "key:value" format, or a JSON object for multiple headers.`);return{[t.slice(0,n).trim()]:t.slice(n+1).trim()}}const gr={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};function formatEndpointLine(e){let n=(gr[e.method]||t.white)(e.method.padEnd(7)),r=e.summary?t.gray(` ${e.summary}`):``;return`${n} ${e.path}${r}`}const _r=`Run ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`;function printSuggestions(e){if(e.length>0){simpleLog({message:`
|
|
@@ -236,4 +236,4 @@ When no path is provided, validates all schemas found in '${W}':
|
|
|
236
236
|
- Dataset schema (from "storages.dataset")
|
|
237
237
|
- Output schema (from "output")
|
|
238
238
|
- 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:X.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});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${W}'`}`});let t=new An({strict:!1});_t(t,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 ii=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],ai=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,ii as n,processVersionCheck as r,ai as t};
|
|
239
|
-
//# sourceMappingURL=_register-
|
|
239
|
+
//# sourceMappingURL=_register-CVJQMC0A.js.map
|