apify-cli 1.10.1-beta.58 → 1.10.1-beta.59
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{appendFileSync as a,chmodSync as s,closeSync as c,constants as l,copyFileSync as u,createWriteStream as f,existsSync as p,fstat as m,mkdirSync as h,openSync as g,readFileSync as _,readdirSync as v,realpathSync as y,renameSync as b,rmSync as x,statSync as S,unlinkSync as C,writeFileSync as w,writeSync as T}from"node:fs";import{ApifyApiError as E,ApifyClient as D,DownloadItemsFormat as O}from"apify-client";import k,{AxiosHeaders as A}from"axios";import{ACTOR_ENV_VARS as j,ACTOR_JOB_STATUSES as M,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as N,ACTOR_NAME as P,ACTOR_SOURCE_TYPES as te,APIFY_ENV_VARS as F,KEY_VALUE_STORE_KEYS as I,LOCAL_ACTOR_ENV_VARS as ne,LOCAL_STORAGE_SUBDIRS as re,MAX_MULTIFILE_BYTES as ie,META_ORIGINS as ae,SOURCE_FILE_FORMATS as oe}from"@apify/consts";import{createHmacSignature as se,cryptoRandomObjectId as ce}from"@apify/utilities";import{homedir as le,platform as ue}from"node:os";import de,{basename as fe,dirname as L,isAbsolute as pe,join as R,relative as me,resolve as z,sep as he}from"node:path";import ge,{isCI as _e}from"ci-info";import{access as ve,appendFile as ye,mkdir as B,readFile as V,readdir as be,rename as xe,rm as Se,stat as H,symlink as Ce,unlink as we,writeFile as U}from"node:fs/promises";import{setTimeout as Te}from"node:timers/promises";import{once as Ee}from"node:events";import{inspect as De,parseArgs as Oe,promisify as ke}from"node:util";import{Result as Ae,err as je,none as W,ok as Me,some as Ne}from"@sapphire/result";import{execa as Pe}from"execa";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{gt as Re,gte as ze,minVersion as Be,satisfies as Ve}from"semver";import He from"string-width";import Ue from"strip-ansi";import{jaroWinkler as We}from"@skyra/jaro-winkler";import Ge from"js-levenshtein";import{execFileSync as Ke,execSync as qe,spawn as Je}from"node:child_process";import{DurationFormatter as Ye,Time as Xe,TimeTypes as Ze}from"@sapphire/duration";import{Timestamp as Qe}from"@sapphire/timestamp";import $e from"adm-zip";import et from"ajv/dist/2019.js";import{ZipArchive as tt}from"archiver";import nt from"escape-string-regexp";import rt from"ignore";import{getEncoding as it}from"istextorbinary";import at,{Mime as ot}from"mime";import st from"mime/types/other.js";import ct from"mime/types/standard.js";import{glob as lt}from"tinyglobby";import{calculateRunDynamicMemory as ut}from"@apify/actor-memory-expression";import{Separator as dt,createPrompt as ft,isEnterKey as pt,makeTheme as mt,useKeypress as ht,usePrefix as gt,useState as _t}from"@inquirer/core";import{compile as vt}from"json-schema-to-typescript";import{validateInputSchema as yt,validateInputUsingValidator as bt}from"@apify/input_schema";import{getDatasetSchemaValidator as xt,getKeyValueStoreSchemaValidator as St,getOutputSchemaValidator as Ct}from"@apify/json_schemas";import{pipeline as wt}from"node:stream/promises";import{MemoryStorage as Tt}from"@crawlee/memory-storage";import Et from"cli-table3";import{downloadTemplate as Dt}from"giget";import Ot from"jju";import kt from"open";import{fetchManifest as At,manifestUrl as jt,wrapperManifestUrl as Mt}from"@apify/actor-templates";import Nt from"computer-name";import Pt from"@inquirer/password";import{createServer as Ft}from"node:http";import{createHash as It,randomBytes as Lt}from"node:crypto";import Rt from"@inquirer/select";import zt from"node:assert";import{ReadStream as Bt}from"node:tty";import Vt from"detect-indent";import{fileURLToPath as Ht}from"node:url";import Ut from"@root/walk";import Wt from"handlebars";var Gt={node:`>=22`};const Kt=`storage`,qt={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},Jt=Date.UTC(2026,9,1),Yt=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=R(le(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?R(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),Xt=`.actor`,G=R(Xt,`actor.json`),Zt=Gt.node,Qt=ge.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,$t={"X-Apify-Request-Origin":ge.isCI?ae.CI:ae.CLI,...Qt&&{"X-Apify-Github-Actions-Run-Url":Qt}},en=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await V(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await U(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(he).reduce((e,t)=>(e=R(e,t),p(e)||h(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Se(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await H(e)).isFile()&&await we(e)};function ensureApifyDirectory(e){let t=L(e);h(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>H(R(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0);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 cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}let tn;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(_(AUTH_FILE_PATH(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?null:e}catch{return null}}function readAuthFile(){return parseAuthFile()??{}}function writeAuthFile(e){atomicWriteJson(AUTH_FILE_PATH(),e)}function atomicWriteJson(e,t){ensureApifyDirectory(e);let n=`${e}.tmp-${ce(8)}`;try{w(n,JSON.stringify(t,null,` `),{mode:384}),b(n,e)}catch(e){throw x(n,{force:!0}),e}}function v1Profile(e){return{...typeof e.username==`string`?{username:e.username}:{},name:null,...typeof e.organizationOwnerUserId==`string`?{organizationOwnerUserId:e.organizationOwnerUserId}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:null}}function toV2(e){let t={version:2,profiles:{}};return typeof e.id==`string`&&(t.activeProfile=e.id,t.profiles[e.id]=v1Profile(e)),typeof e.token==`string`&&(t.token=e.token),typeof e.proxy?.password==`string`&&(t.proxy={password:e.proxy.password}),t}const nn={1:toV2};async function migrateAuthFile(){return tn??=(async()=>{try{let e=parseAuthFile();if(!e||Object.keys(e).length===0)return;let t=typeof e.version==`number`?e.version:1;if(t>=2)return;let n=e;for(let e=t;e<2;e++){let t=nn[e];if(!t)throw Error(`No migration step from auth file version ${e}.`);n=t(n)}writeAuthFile(n)}catch(e){cliDebugPrint(`auth-file`,`auth file migration failed`,e),warning({message:`Your stored login cannot be read until ${AUTH_FILE_PATH()} is updated to the current format, and the update failed. Make the directory it is in writable, then run the command again. Set APIFY_CLI_DEBUG=1 to see why.`})}})(),tn}function assertSupportedAuthFileVersion(){let{version:e}=readAuthFile();if(typeof e==`number`&&e>2)throw Error(`Your credentials in ${AUTH_FILE_PATH()} were written by a newer Apify CLI. It uses auth file version ${e} and this one reads 2. Upgrade the CLI, or run "apify logout" to discard them.`)}async function ensureAuthFileCurrent(){await migrateAuthFile(),assertSupportedAuthFileVersion()}function lookUpActiveProfile(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?{profile:{id:t.id,...v1Profile(t)}}:{}}if(!e.activeProfile)return{};let t=e.profiles?.[e.activeProfile];return t?{profile:{id:e.activeProfile,...t}}:{missingProfile:e.activeProfile}}function profileLabel(e){return e.name??e.username??e.id}function listProfiles(){let e=readAuthFile();if(e.version!==2){let{profile:e}=lookUpActiveProfile();return e?[e]:[]}return Object.entries(e.profiles??{}).map(([e,t])=>({id:e,...t}))}function matchProfiles(e){let t=listProfiles(),n=t.find(({id:t})=>t===e);return n?[n]:t.filter(t=>profileLabel(t)===e)}function lookUpProfile(e){let t=listProfiles().find(({id:t})=>t===e);return t?{profile:t}:{missingProfile:e}}function setActiveProfile(e){let t=readAuthFile();t.profiles?.[e]&&(t.activeProfile=e,writeAuthFile(t))}function getActiveProfile(){return lookUpActiveProfile().profile}function getActiveProfileId(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?t.id:void 0}return e.activeProfile}function readProfileSecret(e,t){let n=readAuthFile().profiles?.[e];if(n)switch(t){case`token`:return n.token;case`refresh-token`:return n.refreshToken;default:return n.proxy?.password}}function writeProfileSecret(e,t,n){updateProfile(e,e=>setProfileSecret(e,t,n))}function clearProfileFileSecrets(e){let t=readAuthFile().profiles?.[e];(t?.token!==void 0||t?.proxy!==void 0||t?.refreshToken!==void 0)&&updateProfile(e,e=>{delete e.token,delete e.proxy,delete e.refreshToken})}function setProfileSecret(e,t,n){t===`token`?e.token=n:t===`refresh-token`?e.refreshToken=n:e.proxy={...e.proxy,password:n}}function deleteProfileSecret(e,t){readProfileSecret(e,t)!==void 0&&updateProfile(e,e=>{t===`token`?delete e.token:t===`refresh-token`?delete e.refreshToken:delete e.proxy})}function updateProfile(e,t){let n=readAuthFile(),r=n.profiles?.[e];r&&(t(r),writeAuthFile(n))}function updateProfileAuth(e,t){updateProfile(e,e=>{e.authMethod=t.authMethod,e.expiresAt=t.expiresAt,e.hasRefreshToken=t.hasRefreshToken,t.oauth?e.oauth=t.oauth:delete e.oauth})}function upsertProfile(e,t){assertSupportedAuthFileVersion();let n=readAuthFile(),r=n.version===2?n:{version:2};r.profiles??={},delete r.token,delete r.proxy;let i=r.profiles[e];r.profiles[e]={...t,...i?.token?{token:i.token}:{},...i?.proxy?{proxy:i.proxy}:{},...i?.refreshToken?{refreshToken:i.refreshToken}:{}},r.activeProfile=e,writeAuthFile(r)}function removeProfile(e){let t=readAuthFile();if(t.version!==2)return discardAuthFile(),{};let n=e??t.activeProfile,r=n?t.profiles?.[n]:void 0,i=n&&r?{id:n,...r}:void 0;if(n&&t.profiles&&delete t.profiles[n],n!==t.activeProfile){writeAuthFile(t);let e=t.activeProfile?t.profiles?.[t.activeProfile]:void 0;return{removed:i,active:e&&{id:t.activeProfile,...e}}}delete t.activeProfile,delete t.token,delete t.proxy;let[a]=Object.entries(t.profiles??{}).sort(([,e],[,t])=>(t.loggedInAt??``).localeCompare(e.loggedInAt??``)).map(([e])=>e);return a?(t.activeProfile=a,writeAuthFile(t),{removed:i,active:{id:a,...t.profiles[a]}}):(discardAuthFile(),{removed:i})}function removeAllProfiles(){discardAuthFile()}function discardAuthFile(){x(AUTH_FILE_PATH(),{force:!0,maxRetries:10,retryDelay:100})}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=y(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 rn=null;function useCLIMetadata(){if(rn)return rn;let e=detectInstallMethod(),t=getRuntimeInfo();return rn={version:`1.10.1-beta.58`,hash:`b908820384318ef2eeda63f597213a22bf16ef5e`,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`&&(rn.installPath=L(process.execPath)),rn}const an=`com.apify.cli`,on=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${an}.${t}`,account:e}}function legacyKeyringKey(e){return{service:an,account:e}}let sn,cn,ln,un;async function loadKeyringModule(){return sn===void 0&&(sn=await importKeyringModule()),sn}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 cn||(cn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),cn)}function stripProxyPassword(e){e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy)}async function getKeyringEntry({service:e,account:t}){let n=await loadKeyringModule();return n?new n.Entry(e,t):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.service}/${e.account} 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);return t&&t.deletePassword(),null}catch(t){return cliDebugPrint(`credentials`,`failed to delete ${e.service}/${e.account} from keyring`,t),await readKeyring(e)===void 0?null:{key:e,error:t}}}async function backendFor(e){return readProfileSecret(e,`token`)===void 0?getBackend():`file`}async function getSecret(e,t){return await backendFor(e)===`keyring`?await readKeyring(keyringKey(e,t))??readProfileSecret(e,t):readProfileSecret(e,t)}async function setSecret(e,t,n,r={}){let i=await backendFor(e),a=t===`token`?await getBackend():i;if(!(r.skipIfUnchanged&&i===a&&await getSecret(e,t)===n)){if(a===`keyring`)try{await writeKeyring(keyringKey(e,t),n),t===`token`&&clearProfileFileSecrets(e);return}catch(n){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,n),t===`token`&&await moveKeyringSecretsToFile(e)}writeProfileSecret(e,t,n)}}async function moveKeyringSecretsToFile(e){for(let t of on){if(t===`token`)continue;let n=await readKeyring(keyringKey(e,t));n!==void 0&&(writeProfileSecret(e,t,n),readProfileSecret(e,t)===n&&await deleteKeyring(keyringKey(e,t)))}}async function deleteSecret(e,t){let n=await backendFor(e)===`keyring`?await deleteKeyring(keyringKey(e,t)):null;return deleteProfileSecret(e,t),n}async function clearKeyringSecrets(e,{keepLegacy:t=!1}={}){let n=[];for(let r of on)e&&n.push(await deleteKeyring(keyringKey(e,r))),t||n.push(await deleteKeyring(legacyKeyringKey(r)));return n.filter(e=>e!==null)}function describeLeftovers(e){return e.map(({key:e})=>`${e.service}/${e.account}`).join(`, `)}function leftoverReasons(e){let t=e.map(({error:e})=>e instanceof Error?e.message:String(e));return[...new Set(t)].join(` `)}async function ensureMigrated(){return ln||(ln=(async()=>{try{let e=readAuthFile();if(typeof e.version==`number`&&e.version>2||!e.token&&!e.proxy?.password||await getBackend()===`file`)return;try{e.token&&await writeKeyring(legacyKeyringKey(`token`),e.token),e.proxy?.password&&await writeKeyring(legacyKeyringKey(`proxy-password`),e.proxy.password)}catch(e){cliDebugPrint(`credentials`,`keyring write failed during migration; keeping secrets in the file`,e);return}delete e.token,stripProxyPassword(e),writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),ln)}async function dropUnkeyedSecrets(e){for(let e of on)await deleteKeyring(legacyKeyringKey(e));(e.token!==void 0||e.proxy!==void 0)&&(delete e.token,delete e.proxy,writeAuthFile(e))}async function keyKeyringSecrets(e){let t;for(let n of on){let r=legacyKeyringKey(n),i=await readKeyring(r);if(i!==void 0){if(t??=await readKeyring(keyringKey(e,`token`))===void 0,!t||await getSecret(e,n)!==void 0)await deleteKeyring(r);else{if(await backendFor(e)===`keyring`){let t=keyringKey(e,n);try{await writeKeyring(t,i),await readKeyring(t)===i&&await deleteKeyring(r);continue}catch(e){cliDebugPrint(`credentials`,`keyring write failed while keying secrets by user`,e)}}writeProfileSecret(e,n,i),readProfileSecret(e,n)===i&&await deleteKeyring(r)}}}}function keyFileSecrets(e,t){let n=t.profiles?.[e];if(!n)return;let{token:r}=t,i=t.proxy?.password;(r!==void 0||i!==void 0)&&(r!==void 0&&(n.token=r),i!==void 0&&(n.proxy={password:i}),delete t.token,delete t.proxy,writeAuthFile(t))}async function ensureSecretsKeyed(){return un??=(async()=>{try{let e=readAuthFile();if(e.version!==2)return;let t=e.activeProfile;if(!t){await dropUnkeyedSecrets(e);return}keyFileSecrets(t,e),await backendFor(t)===`keyring`&&await keyKeyringSecrets(t)}catch(e){cliDebugPrint(`credentials`,`keying secrets by user failed`,e)}})(),un}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const dn=`full_api_access`,fn=3e5,pn=3e4;function readUrlEnv(t,n){let r=e.env[t];if(!r)return n;let i=r.replace(/\/+$/,``);if(!URL.canParse(i))throw Error(`Invalid ${t} environment variable: "${r}" is not a valid URL.`);return i}function getOAuthIssuerUrl(){return readUrlEnv(`APIFY_CLI_OAUTH_ISSUER_URL`,`https://console-backend.apify.com`)}function getOAuthClientId(){let t=e.env.APIFY_CLI_OAUTH_CLIENT_ID;if(!t)return`https://apify.com/.well-known/oauth-clients/apify-cli.json`;if(!URL.canParse(t))throw Error(`Invalid APIFY_CLI_OAUTH_CLIENT_ID environment variable: "${t}" is not a valid URL.`);return t}var OAuthError=class extends Error{code;status;description;name=`OAuthError`;constructor(e,t,n){super(n?`${e}: ${n}`:e),this.code=e,this.status=t,this.description=n}};async function postTokenRequest(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...$t},body:new URLSearchParams(t),signal:AbortSignal.timeout(pn)}),r=await n.text(),i={};try{i=r?JSON.parse(r):{}}catch{}if(n.ok&&typeof i.access_token==`string`)return{ok:!0,tokens:i};let a=typeof i.error==`string`?i.error:`http_${n.status}`,s=typeof i.error_description==`string`?i.error_description:void 0;return{ok:!1,error:new OAuthError(a,n.status,s)}}async function refreshAccessToken(e){let t=await postTokenRequest(e.tokenEndpoint,{grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});if(!t.ok)throw t.error;return t.tokens}var OAuthSessionError=class extends Error{name=`OAuthSessionError`},OAuthSessionExpiredError=class extends OAuthSessionError{name=`OAuthSessionExpiredError`;constructor(){super(`Your Apify login session has expired. Run "apify login" to sign in again.`)}};const mn=/* @__PURE__ */ new Map;function sessionOf(e){let t=mn.get(e);return t||(t={refreshAttempted:!1},mn.set(e,t)),t}function readMetadata(e){let{profile:t}=lookUpProfile(e);if(t?.authMethod!==`oauth2`||!t.oauth||!t.expiresAt)return;let n=Date.parse(t.expiresAt);if(!Number.isFinite(n))return;let r=t.oauth.refreshTokenExpiresAt?Date.parse(t.oauth.refreshTokenExpiresAt):void 0;return{...t.oauth,expiresAt:n,...Number.isFinite(r)?{refreshTokenExpiresAtMs:r}:{}}}async function getAccessToken(e,{minRemainingMs:t=6e4}={}){let n=readMetadata(e);if(!n)return getSecret(e,`token`);let r=sessionOf(e),i=Date.now();if(!needsRefresh(n,i,t)){if(r.cached&&r.cached.expiresAt===n.expiresAt)return r.cached.token;let t=await getSecret(e,`token`);return t&&(r.cached={token:t,expiresAt:n.expiresAt}),t}if(n.refreshTokenExpiresAtMs!==void 0&&n.refreshTokenExpiresAtMs<=i)throw new OAuthSessionExpiredError;if(r.refreshAttempted){if(r.refreshFailure)throw r.refreshFailure;return r.cached?.token??getSecret(e,`token`)}return r.inflightRefresh??=refreshSession(e,r,n,t).catch(e=>{throw r.refreshFailure=e,e}).finally(()=>{r.inflightRefresh=void 0}),r.inflightRefresh}async function saveOAuthSession(e,t,n){await persistTokens(e,t,{...n,refreshTokenExpiresAt:null})}async function clearOAuthSession(e){mn.delete(e);let t=await deleteSecret(e,`refresh-token`);t&&cliDebugPrint(`oauth`,`the keyring kept the refresh token`,t.error),lookUpProfile(e).profile?.authMethod===`oauth2`&&updateProfileAuth(e,{authMethod:`token`,expiresAt:null,hasRefreshToken:!1})}function needsRefresh(e,t,n){return e.expiresAt-t<n||e.refreshTokenExpiresAtMs!==void 0&&e.refreshTokenExpiresAtMs-t<18e5}async function refreshSession(e,t,n,r){let i=await acquireRefreshLock(e);try{let i=readMetadata(e)??n;if(!needsRefresh(i,Date.now(),r)){let n=await getSecret(e,`token`);return n&&(t.cached={token:n,expiresAt:i.expiresAt}),n}let a=await getSecret(e,`refresh-token`);if(!a)throw new OAuthSessionExpiredError;t.refreshAttempted=!0;let s;try{s=await refreshAccessToken({tokenEndpoint:i.tokenEndpoint,clientId:i.clientId,refreshToken:a})}catch(n){return handleRefreshFailure(e,t,n,i,a)}return await persistTokens(e,s,i),s.access_token}finally{i()}}async function handleRefreshFailure(e,t,n,r,i){cliDebugPrint(`oauth`,`refresh failed`,n);let a=n instanceof OAuthError&&(n.code===`invalid_grant`||n.code===`expired_token`);if(a){let n=await getSecret(e,`refresh-token`);if(n&&n!==i){let n=await getSecret(e,`token`),r=readMetadata(e);return n&&r&&(t.cached={token:n,expiresAt:r.expiresAt}),n}}if(Date.now()<r.expiresAt)return getSecret(e,`token`);throw a?(await clearOAuthSession(e),new OAuthSessionExpiredError):new OAuthSessionError(`Could not refresh your Apify session. Check your connection or run "apify login".`)}async function persistTokens(e,t,n){let r=Date.now(),i=r+(t.expires_in??3600)*1e3,a=t.refresh_token_expires_in===void 0?n.refreshTokenExpiresAt:new Date(r+t.refresh_token_expires_in*1e3).toISOString();t.refresh_token&&await setSecret(e,`refresh-token`,t.refresh_token,{skipIfUnchanged:!0}),await setSecret(e,`token`,t.access_token,{skipIfUnchanged:!0}),updateProfileAuth(e,{authMethod:`oauth2`,expiresAt:new Date(i).toISOString(),hasRefreshToken:!!t.refresh_token||await getSecret(e,`refresh-token`)!==void 0,oauth:{issuer:n.issuer,clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,refreshTokenExpiresAt:a}}),sessionOf(e).cached={token:t.access_token,expiresAt:i}}async function acquireRefreshLock(t){let n=R(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{C(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=g(n,`wx`);return T(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-S(n).mtimeMs>3e4){C(n);continue}}catch{continue}await Te(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const hn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[F.TOKEN]?.trim();return t?hn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${F.TOKEN} is set to "${e}", which is not an API token. Unset ${F.TOKEN} and try again.`}const gn={env:`${F.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let _n,vn;const yn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${F.TOKEN} is set, so commands ignore ${e}. Unset ${F.TOKEN} and try again.`}async function requireProfile(t){await ensureCredentialsCurrent();let n=matchProfiles(t);if(n.length===1)return n[0];if(e.exitCode=5,n.length>1)throw Error(`More than one stored account is called "${t}": ${n.map(({id:e})=>e).join(`, `)}. Use the user ID instead.`);let r=listProfiles().map(profileLabel);throw Error(r.length?`No stored account is called "${t}". Stored accounts: ${r.join(`, `)}.`:`No stored account is called "${t}". Run "apify login" to add one.`)}function getCurrentProfile(){return vn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));vn=await requireProfile(t),_n=void 0}const resolveAuth=async()=>{_n??=(async()=>{await ensureMigrated();let t=readEnvToken();if(t.kind===`invalid`)throw e.exitCode=5,Error(invalidEnvTokenMessage(t.raw));if(t.kind===`token`)return p(AUTH_FILE_PATH())&&warning({message:`Using the API token from ${F.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),vn){let t=await getAccessToken(vn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(vn));return{token:t,source:`profile`,profile:profileRef(vn)}}let n=getActiveProfileId(),r=n?await getAccessToken(n):void 0;if(!r)return;let i=getActiveProfile();return{token:r,source:`stored`,...i?{profile:profileRef(i)}:{}}})();try{return await _n}catch(e){throw _n=void 0,e}};function profileRef(e){return{id:e.id,label:profileLabel(e)}}function missingProfileTokenMessage(e){return`No API token is stored for ${profileLabel(e)}. Run "apify login" to log in to ${profileLabel(e)} again.`}function describeAuthFailure(e,t){if(!e)return`You are not logged in with your Apify account. Call "apify login" to fix that.`;let n=t instanceof E?t.statusCode:void 0;if(t&&n!==401&&n!==403)return`Could not verify your API token. The Apify API request failed: ${t instanceof Error?t.message:String(t)}`;switch(e.source){case`env`:return`The API token in ${F.TOKEN} was rejected. Unset it to use your stored login instead.`;default:return e.profile?`The stored API token for ${e.profile.label} was rejected. Run "apify login" to log in to ${e.profile.label} again.`:`Your stored API token was rejected. Call "apify login" to log in again.`}}const getAnonymousApifyClientOptions=t=>({baseUrl:t||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new A;for(let[t,n]of Object.entries($t))e.headers[t]=n;return e}]}),getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new D(getApifyClientOptionsForToken(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[loginWithToken] error getting user info`,{error:e,apiBaseUrl:t}),null}if(!r.id)throw Error(`The Apify API returned no user ID for this token, so the login cannot be stored.`);let i=r.proxy?.password;await ensureCredentialsCurrent();let{organizationOwnerUserId:a}=r;upsertProfile(r.id,{username:r.username,name:r.username||r.id,...a?{organizationOwnerUserId:a}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:(/* @__PURE__ */ new Date()).toISOString()});let s=await clearKeyringSecrets();if(await clearOAuthSession(r.id),await setSecret(r.id,`token`,e,{skipIfUnchanged:!0}),i)await setSecret(r.id,`proxy-password`,i,{skipIfUnchanged:!0});else{let e=await deleteSecret(r.id,`proxy-password`);e&&s.push(e)}return s.length&&warning({message:`Secrets this login could not remove are still in the OS keyring at ${describeLeftovers(s)}; delete them with your OS keyring app.`}),{client:n,userInfo:r}}const bn=ke(m);let xn;async function useStdin(){if(xn)return xn;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await bn(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&l.S_IFIFO)===l.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),xn=n,n}const Sn=5e3;let Cn,wn,Tn=!1,En=!1;async function readStdin(e={}){return Cn??=_readStdin(e).then(e=>(wn=e,Tn=!0,e)),Cn}function stdinWasCutShort(){return En}function describeStdinRead(){return Tn?wn?`Yes`:`No`:`Not read`}async function _readStdin({implicit:e}){let{hasData:t,waitDelay:n,stream:r}=await useStdin();if(!t)return;let i=e?n||Sn:n,a=[],s=new AbortController,c=null,armTimeout=e=>{e&&(c=setTimeout(()=>s.abort(),e).unref())},disarmTimeout=()=>{c&&=(clearTimeout(c),null)};armTimeout(i);let onData=t=>{a.push(t),disarmTimeout(),e&&armTimeout(1e3)};r.on(`data`,onData);try{await Ee(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;En=a.length>0||i===Sn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}const Dn={output:e.stderr},On=`confirm`,kn=`no-${On}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${On}/--${kn} flags to confirm the action.`}={}){return async(n,...r)=>{let{isTTY:i}=await useStdin(),a=n;if(_e||!i){if(a.providedConfirmFromStdin===void 0)throw Error(a.errorMessageForStdin??t);return a.providedConfirmFromStdin}return await e(n,...r)}}const An=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await Ie({message:e,validate:t,default:n},Dn),{errorMessageForStdin:`Please provide a valid input based on the command options.`});var Spider=class{name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}},SpiderFileAnalyzer=class{pathname;constructor(e){this.pathname=e}getSpiders(){let e=_(this.pathname,`utf8`),t=/class\s+(\w+)/g,n=[],r=t.exec(e);for(;r;)n.push(new Spider({class_name:r[1],pathname:this.pathname})),r=t.exec(e);return n}},ScrapyProjectAnalyzer=class{pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return p(R(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Fe,t=z(R(this.pathname,`scrapy.cfg`));if(!p(t))throw Error(`scrapy.cfg not found in "${t}".
|
|
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{appendFileSync as a,chmodSync as s,closeSync as c,constants as l,copyFileSync as u,createWriteStream as f,existsSync as p,fstat as m,mkdirSync as h,openSync as g,readFileSync as _,readdirSync as v,realpathSync as y,renameSync as b,rmSync as x,statSync as S,unlinkSync as C,writeFileSync as w,writeSync as T}from"node:fs";import{ApifyApiError as E,ApifyClient as D,DownloadItemsFormat as O}from"apify-client";import k,{AxiosHeaders as A}from"axios";import{ACTOR_ENV_VARS as j,ACTOR_JOB_STATUSES as M,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as N,ACTOR_NAME as P,ACTOR_SOURCE_TYPES as te,APIFY_ENV_VARS as F,KEY_VALUE_STORE_KEYS as I,LOCAL_ACTOR_ENV_VARS as ne,LOCAL_STORAGE_SUBDIRS as re,MAX_MULTIFILE_BYTES as ie,META_ORIGINS as ae,SOURCE_FILE_FORMATS as oe}from"@apify/consts";import{createHmacSignature as se,cryptoRandomObjectId as ce}from"@apify/utilities";import{homedir as le,platform as ue}from"node:os";import de,{basename as fe,dirname as L,isAbsolute as pe,join as R,relative as me,resolve as z,sep as he}from"node:path";import ge,{isCI as _e}from"ci-info";import{access as ve,appendFile as ye,mkdir as B,readFile as V,readdir as be,rename as xe,rm as Se,stat as H,symlink as Ce,unlink as we,writeFile as U}from"node:fs/promises";import{setTimeout as Te}from"node:timers/promises";import{once as Ee}from"node:events";import{inspect as De,parseArgs as Oe,promisify as ke}from"node:util";import{Result as Ae,err as je,none as W,ok as Me,some as Ne}from"@sapphire/result";import{execa as Pe}from"execa";import Fe from"configparser";import Ie from"@inquirer/input";import Le from"which";import{gt as Re,gte as ze,minVersion as Be,satisfies as Ve}from"semver";import He from"string-width";import Ue from"strip-ansi";import{jaroWinkler as We}from"@skyra/jaro-winkler";import Ge from"js-levenshtein";import{execFileSync as Ke,execSync as qe,spawn as Je}from"node:child_process";import{DurationFormatter as Ye,Time as Xe,TimeTypes as Ze}from"@sapphire/duration";import{Timestamp as Qe}from"@sapphire/timestamp";import $e from"adm-zip";import et from"ajv/dist/2019.js";import{ZipArchive as tt}from"archiver";import nt from"escape-string-regexp";import rt from"ignore";import{getEncoding as it}from"istextorbinary";import at,{Mime as ot}from"mime";import st from"mime/types/other.js";import ct from"mime/types/standard.js";import{glob as lt}from"tinyglobby";import{calculateRunDynamicMemory as ut}from"@apify/actor-memory-expression";import{Separator as dt,createPrompt as ft,isEnterKey as pt,makeTheme as mt,useKeypress as ht,usePrefix as gt,useState as _t}from"@inquirer/core";import{compile as vt}from"json-schema-to-typescript";import{validateInputSchema as yt,validateInputUsingValidator as bt}from"@apify/input_schema";import{getDatasetSchemaValidator as xt,getKeyValueStoreSchemaValidator as St,getOutputSchemaValidator as Ct}from"@apify/json_schemas";import{pipeline as wt}from"node:stream/promises";import{MemoryStorage as Tt}from"@crawlee/memory-storage";import Et from"cli-table3";import{downloadTemplate as Dt}from"giget";import Ot from"jju";import kt from"open";import{fetchManifest as At,manifestUrl as jt,wrapperManifestUrl as Mt}from"@apify/actor-templates";import Nt from"computer-name";import Pt from"@inquirer/password";import{createServer as Ft}from"node:http";import{createHash as It,randomBytes as Lt}from"node:crypto";import Rt from"@inquirer/select";import zt from"node:assert";import{ReadStream as Bt}from"node:tty";import Vt from"detect-indent";import{fileURLToPath as Ht}from"node:url";import Ut from"@root/walk";import Wt from"handlebars";var Gt={node:`>=22`};const Kt=`storage`,qt={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},Jt=Date.UTC(2026,9,1),Yt=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=R(le(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?R(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>R(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),Xt=`.actor`,G=R(Xt,`actor.json`),Zt=Gt.node,Qt=ge.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,$t={"X-Apify-Request-Origin":ge.isCI?ae.CI:ae.CLI,...Qt&&{"X-Apify-Github-Actions-Run-Url":Qt}},en=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await V(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await U(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(he).reduce((e,t)=>(e=R(e,t),p(e)||h(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Se(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await H(e)).isFile()&&await we(e)};function ensureApifyDirectory(e){let t=L(e);h(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>H(R(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0);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 cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}let tn;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(_(AUTH_FILE_PATH(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?null:e}catch{return null}}function readAuthFile(){return parseAuthFile()??{}}function writeAuthFile(e){atomicWriteJson(AUTH_FILE_PATH(),e)}function atomicWriteJson(e,t){ensureApifyDirectory(e);let n=`${e}.tmp-${ce(8)}`;try{w(n,JSON.stringify(t,null,` `),{mode:384}),b(n,e)}catch(e){throw x(n,{force:!0}),e}}function v1Profile(e){return{...typeof e.username==`string`?{username:e.username}:{},name:null,...typeof e.organizationOwnerUserId==`string`?{organizationOwnerUserId:e.organizationOwnerUserId}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:null}}function toV2(e){let t={version:2,profiles:{}};return typeof e.id==`string`&&(t.activeProfile=e.id,t.profiles[e.id]=v1Profile(e)),typeof e.token==`string`&&(t.token=e.token),typeof e.proxy?.password==`string`&&(t.proxy={password:e.proxy.password}),t}const nn={1:toV2};async function migrateAuthFile(){return tn??=(async()=>{try{let e=parseAuthFile();if(!e||Object.keys(e).length===0)return;let t=typeof e.version==`number`?e.version:1;if(t>=2)return;let n=e;for(let e=t;e<2;e++){let t=nn[e];if(!t)throw Error(`No migration step from auth file version ${e}.`);n=t(n)}writeAuthFile(n)}catch(e){cliDebugPrint(`auth-file`,`auth file migration failed`,e),warning({message:`Your stored login cannot be read until ${AUTH_FILE_PATH()} is updated to the current format, and the update failed. Make the directory it is in writable, then run the command again. Set APIFY_CLI_DEBUG=1 to see why.`})}})(),tn}function assertSupportedAuthFileVersion(){let{version:e}=readAuthFile();if(typeof e==`number`&&e>2)throw Error(`Your credentials in ${AUTH_FILE_PATH()} were written by a newer Apify CLI. It uses auth file version ${e} and this one reads 2. Upgrade the CLI, or run "apify logout" to discard them.`)}async function ensureAuthFileCurrent(){await migrateAuthFile(),assertSupportedAuthFileVersion()}function lookUpActiveProfile(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?{profile:{id:t.id,...v1Profile(t)}}:{}}if(!e.activeProfile)return{};let t=e.profiles?.[e.activeProfile];return t?{profile:{id:e.activeProfile,...t}}:{missingProfile:e.activeProfile}}function profileLabel(e){return e.name??e.username??e.id}function listProfiles(){let e=readAuthFile();if(e.version!==2){let{profile:e}=lookUpActiveProfile();return e?[e]:[]}return Object.entries(e.profiles??{}).map(([e,t])=>({id:e,...t}))}function matchProfiles(e){let t=listProfiles(),n=t.find(({id:t})=>t===e);return n?[n]:t.filter(t=>profileLabel(t)===e)}function lookUpProfile(e){let t=listProfiles().find(({id:t})=>t===e);return t?{profile:t}:{missingProfile:e}}function setActiveProfile(e){let t=readAuthFile();t.profiles?.[e]&&(t.activeProfile=e,writeAuthFile(t))}function getActiveProfile(){return lookUpActiveProfile().profile}function getActiveProfileId(){let e=readAuthFile();if(e.version!==2){let t=e;return typeof t.id==`string`?t.id:void 0}return e.activeProfile}function readProfileSecret(e,t){let n=readAuthFile().profiles?.[e];if(n)switch(t){case`token`:return n.token;case`refresh-token`:return n.refreshToken;default:return n.proxy?.password}}function writeProfileSecret(e,t,n){updateProfile(e,e=>setProfileSecret(e,t,n))}function clearProfileFileSecrets(e){let t=readAuthFile().profiles?.[e];(t?.token!==void 0||t?.proxy!==void 0||t?.refreshToken!==void 0)&&updateProfile(e,e=>{delete e.token,delete e.proxy,delete e.refreshToken})}function setProfileSecret(e,t,n){t===`token`?e.token=n:t===`refresh-token`?e.refreshToken=n:e.proxy={...e.proxy,password:n}}function deleteProfileSecret(e,t){readProfileSecret(e,t)!==void 0&&updateProfile(e,e=>{t===`token`?delete e.token:t===`refresh-token`?delete e.refreshToken:delete e.proxy})}function updateProfile(e,t){let n=readAuthFile(),r=n.profiles?.[e];r&&(t(r),writeAuthFile(n))}function updateProfileAuth(e,t){updateProfile(e,e=>{e.authMethod=t.authMethod,e.expiresAt=t.expiresAt,e.hasRefreshToken=t.hasRefreshToken,t.oauth?e.oauth=t.oauth:delete e.oauth})}function upsertProfile(e,t){assertSupportedAuthFileVersion();let n=readAuthFile(),r=n.version===2?n:{version:2};r.profiles??={},delete r.token,delete r.proxy;let i=r.profiles[e];r.profiles[e]={...t,...i?.token?{token:i.token}:{},...i?.proxy?{proxy:i.proxy}:{},...i?.refreshToken?{refreshToken:i.refreshToken}:{}},r.activeProfile=e,writeAuthFile(r)}function removeProfile(e){let t=readAuthFile();if(t.version!==2)return discardAuthFile(),{};let n=e??t.activeProfile,r=n?t.profiles?.[n]:void 0,i=n&&r?{id:n,...r}:void 0;if(n&&t.profiles&&delete t.profiles[n],n!==t.activeProfile){writeAuthFile(t);let e=t.activeProfile?t.profiles?.[t.activeProfile]:void 0;return{removed:i,active:e&&{id:t.activeProfile,...e}}}delete t.activeProfile,delete t.token,delete t.proxy;let[a]=Object.entries(t.profiles??{}).sort(([,e],[,t])=>(t.loggedInAt??``).localeCompare(e.loggedInAt??``)).map(([e])=>e);return a?(t.activeProfile=a,writeAuthFile(t),{removed:i,active:{id:a,...t.profiles[a]}}):(discardAuthFile(),{removed:i})}function removeAllProfiles(){discardAuthFile()}function discardAuthFile(){x(AUTH_FILE_PATH(),{force:!0,maxRetries:10,retryDelay:100})}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=y(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 rn=null;function useCLIMetadata(){if(rn)return rn;let e=detectInstallMethod(),t=getRuntimeInfo();return rn={version:`1.10.1-beta.59`,hash:`556263bf9775ba3b3253e4ca791f6caf7d701d21`,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`&&(rn.installPath=L(process.execPath)),rn}const an=`com.apify.cli`,on=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${an}.${t}`,account:e}}function legacyKeyringKey(e){return{service:an,account:e}}let sn,cn,ln,un;async function loadKeyringModule(){return sn===void 0&&(sn=await importKeyringModule()),sn}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 cn||(cn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),cn)}function stripProxyPassword(e){e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy)}async function getKeyringEntry({service:e,account:t}){let n=await loadKeyringModule();return n?new n.Entry(e,t):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.service}/${e.account} 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);return t&&t.deletePassword(),null}catch(t){return cliDebugPrint(`credentials`,`failed to delete ${e.service}/${e.account} from keyring`,t),await readKeyring(e)===void 0?null:{key:e,error:t}}}async function backendFor(e){return readProfileSecret(e,`token`)===void 0?getBackend():`file`}async function getSecret(e,t){return await backendFor(e)===`keyring`?await readKeyring(keyringKey(e,t))??readProfileSecret(e,t):readProfileSecret(e,t)}async function setSecret(e,t,n,r={}){let i=await backendFor(e),a=t===`token`?await getBackend():i;if(!(r.skipIfUnchanged&&i===a&&await getSecret(e,t)===n)){if(a===`keyring`)try{await writeKeyring(keyringKey(e,t),n),t===`token`&&clearProfileFileSecrets(e);return}catch(n){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,n),t===`token`&&await moveKeyringSecretsToFile(e)}writeProfileSecret(e,t,n)}}async function moveKeyringSecretsToFile(e){for(let t of on){if(t===`token`)continue;let n=await readKeyring(keyringKey(e,t));n!==void 0&&(writeProfileSecret(e,t,n),readProfileSecret(e,t)===n&&await deleteKeyring(keyringKey(e,t)))}}async function deleteSecret(e,t){let n=await backendFor(e)===`keyring`?await deleteKeyring(keyringKey(e,t)):null;return deleteProfileSecret(e,t),n}async function clearKeyringSecrets(e,{keepLegacy:t=!1}={}){let n=[];for(let r of on)e&&n.push(await deleteKeyring(keyringKey(e,r))),t||n.push(await deleteKeyring(legacyKeyringKey(r)));return n.filter(e=>e!==null)}function describeLeftovers(e){return e.map(({key:e})=>`${e.service}/${e.account}`).join(`, `)}function leftoverReasons(e){let t=e.map(({error:e})=>e instanceof Error?e.message:String(e));return[...new Set(t)].join(` `)}async function ensureMigrated(){return ln||(ln=(async()=>{try{let e=readAuthFile();if(typeof e.version==`number`&&e.version>2||!e.token&&!e.proxy?.password||await getBackend()===`file`)return;try{e.token&&await writeKeyring(legacyKeyringKey(`token`),e.token),e.proxy?.password&&await writeKeyring(legacyKeyringKey(`proxy-password`),e.proxy.password)}catch(e){cliDebugPrint(`credentials`,`keyring write failed during migration; keeping secrets in the file`,e);return}delete e.token,stripProxyPassword(e),writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),ln)}async function dropUnkeyedSecrets(e){for(let e of on)await deleteKeyring(legacyKeyringKey(e));(e.token!==void 0||e.proxy!==void 0)&&(delete e.token,delete e.proxy,writeAuthFile(e))}async function keyKeyringSecrets(e){let t;for(let n of on){let r=legacyKeyringKey(n),i=await readKeyring(r);if(i!==void 0){if(t??=await readKeyring(keyringKey(e,`token`))===void 0,!t||await getSecret(e,n)!==void 0)await deleteKeyring(r);else{if(await backendFor(e)===`keyring`){let t=keyringKey(e,n);try{await writeKeyring(t,i),await readKeyring(t)===i&&await deleteKeyring(r);continue}catch(e){cliDebugPrint(`credentials`,`keyring write failed while keying secrets by user`,e)}}writeProfileSecret(e,n,i),readProfileSecret(e,n)===i&&await deleteKeyring(r)}}}}function keyFileSecrets(e,t){let n=t.profiles?.[e];if(!n)return;let{token:r}=t,i=t.proxy?.password;(r!==void 0||i!==void 0)&&(r!==void 0&&(n.token=r),i!==void 0&&(n.proxy={password:i}),delete t.token,delete t.proxy,writeAuthFile(t))}async function ensureSecretsKeyed(){return un??=(async()=>{try{let e=readAuthFile();if(e.version!==2)return;let t=e.activeProfile;if(!t){await dropUnkeyedSecrets(e);return}keyFileSecrets(t,e),await backendFor(t)===`keyring`&&await keyKeyringSecrets(t)}catch(e){cliDebugPrint(`credentials`,`keying secrets by user failed`,e)}})(),un}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const dn=`full_api_access`,fn=3e5,pn=3e4;function readUrlEnv(t,n){let r=e.env[t];if(!r)return n;let i=r.replace(/\/+$/,``);if(!URL.canParse(i))throw Error(`Invalid ${t} environment variable: "${r}" is not a valid URL.`);return i}function getOAuthIssuerUrl(){return readUrlEnv(`APIFY_CLI_OAUTH_ISSUER_URL`,`https://console-backend.apify.com`)}function getOAuthClientId(){let t=e.env.APIFY_CLI_OAUTH_CLIENT_ID;if(!t)return`https://apify.com/.well-known/oauth-clients/apify-cli.json`;if(!URL.canParse(t))throw Error(`Invalid APIFY_CLI_OAUTH_CLIENT_ID environment variable: "${t}" is not a valid URL.`);return t}var OAuthError=class extends Error{code;status;description;name=`OAuthError`;constructor(e,t,n){super(n?`${e}: ${n}`:e),this.code=e,this.status=t,this.description=n}};async function postTokenRequest(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...$t},body:new URLSearchParams(t),signal:AbortSignal.timeout(pn)}),r=await n.text(),i={};try{i=r?JSON.parse(r):{}}catch{}if(n.ok&&typeof i.access_token==`string`)return{ok:!0,tokens:i};let a=typeof i.error==`string`?i.error:`http_${n.status}`,s=typeof i.error_description==`string`?i.error_description:void 0;return{ok:!1,error:new OAuthError(a,n.status,s)}}async function refreshAccessToken(e){let t=await postTokenRequest(e.tokenEndpoint,{grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});if(!t.ok)throw t.error;return t.tokens}var OAuthSessionError=class extends Error{name=`OAuthSessionError`},OAuthSessionExpiredError=class extends OAuthSessionError{name=`OAuthSessionExpiredError`;constructor(){super(`Your Apify login session has expired. Run "apify login" to sign in again.`)}};const mn=/* @__PURE__ */ new Map;function sessionOf(e){let t=mn.get(e);return t||(t={refreshAttempted:!1},mn.set(e,t)),t}function readMetadata(e){let{profile:t}=lookUpProfile(e);if(t?.authMethod!==`oauth2`||!t.oauth||!t.expiresAt)return;let n=Date.parse(t.expiresAt);if(!Number.isFinite(n))return;let r=t.oauth.refreshTokenExpiresAt?Date.parse(t.oauth.refreshTokenExpiresAt):void 0;return{...t.oauth,expiresAt:n,...Number.isFinite(r)?{refreshTokenExpiresAtMs:r}:{}}}async function getAccessToken(e,{minRemainingMs:t=6e4}={}){let n=readMetadata(e);if(!n)return getSecret(e,`token`);let r=sessionOf(e),i=Date.now();if(!needsRefresh(n,i,t)){if(r.cached&&r.cached.expiresAt===n.expiresAt)return r.cached.token;let t=await getSecret(e,`token`);return t&&(r.cached={token:t,expiresAt:n.expiresAt}),t}if(n.refreshTokenExpiresAtMs!==void 0&&n.refreshTokenExpiresAtMs<=i)throw new OAuthSessionExpiredError;if(r.refreshAttempted){if(r.refreshFailure)throw r.refreshFailure;return r.cached?.token??getSecret(e,`token`)}return r.inflightRefresh??=refreshSession(e,r,n,t).catch(e=>{throw r.refreshFailure=e,e}).finally(()=>{r.inflightRefresh=void 0}),r.inflightRefresh}async function saveOAuthSession(e,t,n){await persistTokens(e,t,{...n,refreshTokenExpiresAt:null})}async function clearOAuthSession(e){mn.delete(e);let t=await deleteSecret(e,`refresh-token`);t&&cliDebugPrint(`oauth`,`the keyring kept the refresh token`,t.error),lookUpProfile(e).profile?.authMethod===`oauth2`&&updateProfileAuth(e,{authMethod:`token`,expiresAt:null,hasRefreshToken:!1})}function needsRefresh(e,t,n){return e.expiresAt-t<n||e.refreshTokenExpiresAtMs!==void 0&&e.refreshTokenExpiresAtMs-t<18e5}async function refreshSession(e,t,n,r){let i=await acquireRefreshLock(e);try{let i=readMetadata(e)??n;if(!needsRefresh(i,Date.now(),r)){let n=await getSecret(e,`token`);return n&&(t.cached={token:n,expiresAt:i.expiresAt}),n}let a=await getSecret(e,`refresh-token`);if(!a)throw new OAuthSessionExpiredError;t.refreshAttempted=!0;let s;try{s=await refreshAccessToken({tokenEndpoint:i.tokenEndpoint,clientId:i.clientId,refreshToken:a})}catch(n){return handleRefreshFailure(e,t,n,i,a)}return await persistTokens(e,s,i),s.access_token}finally{i()}}async function handleRefreshFailure(e,t,n,r,i){cliDebugPrint(`oauth`,`refresh failed`,n);let a=n instanceof OAuthError&&(n.code===`invalid_grant`||n.code===`expired_token`);if(a){let n=await getSecret(e,`refresh-token`);if(n&&n!==i){let n=await getSecret(e,`token`),r=readMetadata(e);return n&&r&&(t.cached={token:n,expiresAt:r.expiresAt}),n}}if(Date.now()<r.expiresAt)return getSecret(e,`token`);throw a?(await clearOAuthSession(e),new OAuthSessionExpiredError):new OAuthSessionError(`Could not refresh your Apify session. Check your connection or run "apify login".`)}async function persistTokens(e,t,n){let r=Date.now(),i=r+(t.expires_in??3600)*1e3,a=t.refresh_token_expires_in===void 0?n.refreshTokenExpiresAt:new Date(r+t.refresh_token_expires_in*1e3).toISOString();t.refresh_token&&await setSecret(e,`refresh-token`,t.refresh_token,{skipIfUnchanged:!0}),await setSecret(e,`token`,t.access_token,{skipIfUnchanged:!0}),updateProfileAuth(e,{authMethod:`oauth2`,expiresAt:new Date(i).toISOString(),hasRefreshToken:!!t.refresh_token||await getSecret(e,`refresh-token`)!==void 0,oauth:{issuer:n.issuer,clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,refreshTokenExpiresAt:a}}),sessionOf(e).cached={token:t.access_token,expiresAt:i}}async function acquireRefreshLock(t){let n=R(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{C(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=g(n,`wx`);return T(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-S(n).mtimeMs>3e4){C(n);continue}}catch{continue}await Te(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const hn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[F.TOKEN]?.trim();return t?hn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${F.TOKEN} is set to "${e}", which is not an API token. Unset ${F.TOKEN} and try again.`}const gn={env:`${F.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let _n,vn;const yn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${F.TOKEN} is set, so commands ignore ${e}. Unset ${F.TOKEN} and try again.`}async function requireProfile(t){await ensureCredentialsCurrent();let n=matchProfiles(t);if(n.length===1)return n[0];if(e.exitCode=5,n.length>1)throw Error(`More than one stored account is called "${t}": ${n.map(({id:e})=>e).join(`, `)}. Use the user ID instead.`);let r=listProfiles().map(profileLabel);throw Error(r.length?`No stored account is called "${t}". Stored accounts: ${r.join(`, `)}.`:`No stored account is called "${t}". Run "apify login" to add one.`)}function getCurrentProfile(){return vn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));vn=await requireProfile(t),_n=void 0}const resolveAuth=async()=>{_n??=(async()=>{await ensureMigrated();let t=readEnvToken();if(t.kind===`invalid`)throw e.exitCode=5,Error(invalidEnvTokenMessage(t.raw));if(t.kind===`token`)return p(AUTH_FILE_PATH())&&warning({message:`Using the API token from ${F.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),vn){let t=await getAccessToken(vn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(vn));return{token:t,source:`profile`,profile:profileRef(vn)}}let n=getActiveProfileId(),r=n?await getAccessToken(n):void 0;if(!r)return;let i=getActiveProfile();return{token:r,source:`stored`,...i?{profile:profileRef(i)}:{}}})();try{return await _n}catch(e){throw _n=void 0,e}};function profileRef(e){return{id:e.id,label:profileLabel(e)}}function missingProfileTokenMessage(e){return`No API token is stored for ${profileLabel(e)}. Run "apify login" to log in to ${profileLabel(e)} again.`}function describeAuthFailure(e,t){if(!e)return`You are not logged in with your Apify account. Call "apify login" to fix that.`;let n=t instanceof E?t.statusCode:void 0;if(t&&n!==401&&n!==403)return`Could not verify your API token. The Apify API request failed: ${t instanceof Error?t.message:String(t)}`;switch(e.source){case`env`:return`The API token in ${F.TOKEN} was rejected. Unset it to use your stored login instead.`;default:return e.profile?`The stored API token for ${e.profile.label} was rejected. Run "apify login" to log in to ${e.profile.label} again.`:`Your stored API token was rejected. Call "apify login" to log in again.`}}const getAnonymousApifyClientOptions=t=>({baseUrl:t||e.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[e=>{e.headers??=new A;for(let[t,n]of Object.entries($t))e.headers[t]=n;return e}]}),getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new D(getApifyClientOptionsForToken(e,t)),r;try{r=await n.user(`me`).get()}catch(e){return cliDebugPrint(`[loginWithToken] error getting user info`,{error:e,apiBaseUrl:t}),null}if(!r.id)throw Error(`The Apify API returned no user ID for this token, so the login cannot be stored.`);let i=r.proxy?.password;await ensureCredentialsCurrent();let{organizationOwnerUserId:a}=r;upsertProfile(r.id,{username:r.username,name:r.username||r.id,...a?{organizationOwnerUserId:a}:{},authMethod:`token`,expiresAt:null,hasRefreshToken:!1,loggedInAt:(/* @__PURE__ */ new Date()).toISOString()});let s=await clearKeyringSecrets();if(await clearOAuthSession(r.id),await setSecret(r.id,`token`,e,{skipIfUnchanged:!0}),i)await setSecret(r.id,`proxy-password`,i,{skipIfUnchanged:!0});else{let e=await deleteSecret(r.id,`proxy-password`);e&&s.push(e)}return s.length&&warning({message:`Secrets this login could not remove are still in the OS keyring at ${describeLeftovers(s)}; delete them with your OS keyring app.`}),{client:n,userInfo:r}}const bn=ke(m);let xn;async function useStdin(){if(xn)return xn;let t=e.stdin,n={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await bn(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&l.S_IFIFO)===l.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),xn=n,n}const Sn=5e3;let Cn,wn,Tn=!1,En=!1;async function readStdin(e={}){return Cn??=_readStdin(e).then(e=>(wn=e,Tn=!0,e)),Cn}function stdinWasCutShort(){return En}function describeStdinRead(){return Tn?wn?`Yes`:`No`:`Not read`}async function _readStdin({implicit:e}){let{hasData:t,waitDelay:n,stream:r}=await useStdin();if(!t)return;let i=e?n||Sn:n,a=[],s=new AbortController,c=null,armTimeout=e=>{e&&(c=setTimeout(()=>s.abort(),e).unref())},disarmTimeout=()=>{c&&=(clearTimeout(c),null)};armTimeout(i);let onData=t=>{a.push(t),disarmTimeout(),e&&armTimeout(1e3)};r.on(`data`,onData);try{await Ee(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;En=a.length>0||i===Sn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}const Dn={output:e.stderr},On=`confirm`,kn=`no-${On}`;function stdinCheckWrapper(e,{errorMessageForStdin:t=`Please use the --${On}/--${kn} flags to confirm the action.`}={}){return async(n,...r)=>{let i=n;if(i.preAnswered!==void 0)return i.preAnswered;let{isTTY:a}=await useStdin();if(_e||!a){if(i.defaultWhenNonInteractive===void 0)throw Error(i.errorMessageForStdin??t);return i.defaultWhenNonInteractive}return await e(n,...r)}}const An=stdinCheckWrapper(async({message:e,validate:t,default:n})=>await Ie({message:e,validate:t,default:n},Dn),{errorMessageForStdin:`Please provide a valid input based on the command options.`});var Spider=class{name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}},SpiderFileAnalyzer=class{pathname;constructor(e){this.pathname=e}getSpiders(){let e=_(this.pathname,`utf8`),t=/class\s+(\w+)/g,n=[],r=t.exec(e);for(;r;)n.push(new Spider({class_name:r[1],pathname:this.pathname})),r=t.exec(e);return n}},ScrapyProjectAnalyzer=class{pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return p(R(e,`scrapy.cfg`))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Fe,t=z(R(this.pathname,`scrapy.cfg`));if(!p(t))throw Error(`scrapy.cfg not found in "${t}".
|
|
2
2
|
Are you sure there is a Scrapy project there?`);e.read(t),this.configuration=e}async loadSettings(){let e=this.configuration.get(`settings`,`default`).split(`.`)[0],t=await An({message:`Enter the Scrapy BOT_NAME (see settings.py):`,default:e}),n=await An({message:`What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):`,default:`${e}.spiders`});this.settings={BOT_NAME:t,SPIDER_MODULES:typeof n==`string`?[n]:n}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw Error(`SPIDER_MODULES path not found in settings.`);let t=[];for(let n of e){let e=R(this.pathname,n.replaceAll(`.`,`/`)),r=v(e,{withFileTypes:!0});for(let n of r)n.isFile()&&n.name.endsWith(`.py`)&&n.name!==`__init__.py`&&t.push(...new SpiderFileAnalyzer(R(e,n.name)).getSpiders())}return t}};const jn=/* @__PURE__ */ new Map,Mn={node:[`--version`],deno:[`eval`,`"console.log(process.versions.node)"`],bun:[`--eval`,`"console.log(process.versions.node)"`]};async function getRuntimeVersion(t,n){try{let r=await Pe(t,n,{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return r.stdout?r.stdout.trim().replace(/^v/,``):null}catch{return null}}async function getNpmVersion(t){let n=await Pe(t,[`--version`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim().replace(/^v/,``):null}async function useJavaScriptRuntime(t=e.cwd()){let n=jn.get(t);if(n)return cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!0,cwd:t,runtime:n.unwrapOr(null)}),n;for(let[e,n]of Object.entries(Mn))try{let r=normalizeExecutablePath(await Le(e)),i=await getRuntimeVersion(r,n);if(i){let n={executablePath:r,version:i};if(e===`node`){let e=normalizeExecutablePath(await Le(`npm`).catch(()=>null));e&&(n.pmPath=e,n.pmVersion=await getNpmVersion(e),n.pmName=`npm`)}else n.runtimeShorthand=e,n.pmPath=r,n.pmVersion=i,n.pmName=e;return jn.set(t,Ne(n)),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:jn.get(t)?.unwrap()}),Ne(n)}}catch{}return jn.set(t,W),cliDebugPrint(`useJavaScriptRuntime`,{cacheHit:!1,cwd:t,runtime:null}),W}const Nn=/* @__PURE__ */ new Map;async function getPythonVersion(t){try{let n=await Pe(t,[`-c`,`"import platform; print(platform.python_version())"`],{shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return n.stdout?n.stdout.trim():null}catch{return null}}async function usePythonRuntime({cwd:t=e.cwd(),force:n=!1}={}){let r=Nn.get(t);if(r&&!n)return cliDebugPrint(`usePythonRuntime`,{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let i=ue()===`win32`,a=i?[`Scripts`,`python.exe`]:[`bin`,`python3`],s;s=e.env.VIRTUAL_ENV?R(e.env.VIRTUAL_ENV,...a):R(t,`.venv`,...a),s=normalizeExecutablePath(s);try{let e=await getPythonVersion(s);if(e)return Nn.set(t,Ne({executablePath:s,version:e})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:Nn.get(t)?.unwrap()}),Nn.get(t)}catch{}let c=[`python3`,`python`,...i?[`python3.exe`,`python.exe`]:[]];for(let e of c)try{let n=normalizeExecutablePath(await Le(e)),r=await getPythonVersion(n);if(r)return Nn.set(t,Ne({executablePath:n,version:r})),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:Nn.get(t)?.unwrap()}),Nn.get(t)}catch{}return Nn.set(t,W),cliDebugPrint(`usePythonRuntime`,{cacheHit:!1,cwd:t,runtime:null}),W}const Pn=/* @__PURE__ */ new Map;async function useCwdProject({cwd:t=e.cwd()}={}){let n=Pn.get(t);if(n)return cliDebugPrint(`useCwdProject`,{cacheHit:!0,project:n}),Me(n);let r={type:3},check=async()=>{if(await checkScrapyProject(t)){r.type=2;let e=await usePythonRuntime({cwd:t});r.runtime=e.unwrapOr(void 0),await fileExists(R(t,`uv.lock`))&&(r.packageManager=`uv`);let n=new ScrapyProjectAnalyzer(t);if(n.loadScrapyCfg(),n.configuration.hasKey(`apify`,`mainpy_location`))r.entrypoint={path:n.configuration.get(`apify`,`mainpy_location`)};else try{let e=await checkPythonProject(t);e&&(r.entrypoint={path:e})}catch{}return}let e=await checkNodeProject(t);if(!e){let e=null;try{e=await checkPythonProject(t)}catch(e){return je({message:e instanceof Error?e.message:String(e)})}if(e){r.type=1;let n=await usePythonRuntime({cwd:t});r.entrypoint={path:e},r.runtime=n.unwrapOr(void 0),await fileExists(R(t,`uv.lock`))&&(r.packageManager=`uv`);let i=R(t,e.replace(/\./g,`/`));await fileExists(R(i,`__main__.py`))||(r.warnings=[`The detected Python package "${e}" is missing __main__.py. Running with "python -m" will fail without it.`]);return}}if(e){r.type=0;let t=await useJavaScriptRuntime();r.runtime=t.unwrapOr(void 0),e.type===`file`?r.entrypoint={path:e.path}:e.type===`script`&&(r.entrypoint={script:e.script})}else return Me(r)},i=await check();return i?.isErr()?(cliDebugPrint(`useCwdProject`,{cacheHit:!1,error:i}),i):(cliDebugPrint(`useCwdProject`,{cacheHit:!1,project:r}),Pn.set(t,r),Me(r))}async function checkNodeProject(e){let t=R(e,`package.json`);try{let n=await V(t,`utf-8`),r=JSON.parse(n);if(r.scripts?.start)return{type:`script`,script:`start`};if(r.main)try{return await ve(z(e,r.main)),{path:z(e,r.main),type:`file`}}catch{}return{type:`unknown-entrypoint`}}catch{}let n=[R(e,`index.js`),R(e,`index.mjs`),R(e,`index.cjs`),R(e,`main.js`),R(e,`main.mjs`),R(e,`main.cjs`),R(e,`src`,`index.js`),R(e,`src`,`index.mjs`),R(e,`src`,`index.cjs`),R(e,`src`,`main.js`),R(e,`src`,`main.mjs`),R(e,`src`,`main.cjs`),R(e,`dist`,`index.js`),R(e,`dist`,`index.mjs`),R(e,`dist`,`index.cjs`),R(e,`dist`,`main.js`),R(e,`dist`,`main.mjs`),R(e,`dist`,`main.cjs`)];for(let e of n)try{return await ve(e),{path:e,type:`file`}}catch{}return null}async function fileExists(e){try{return await ve(e),!0}catch{return!1}}async function dirExists(e){try{return(await H(e)).isDirectory()}catch{return!1}}function isValidPythonIdentifier(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}async function hasPythonFilesInDirOrSubdirs(e){try{let t=await be(e,{withFileTypes:!0});if(t.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;for(let n of t){if(!n.isDirectory()||n.name.startsWith(`.`)||n.name.startsWith(`_`))continue;let t=R(e,n.name);try{let e=await be(t,{withFileTypes:!0});if(e.some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0;if(n.name===`src`){for(let n of e)if(n.isDirectory()&&!(n.name.startsWith(`.`)||n.name.startsWith(`_`)))try{if((await be(R(t,n.name),{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)))return!0}catch{}}}catch{}}return!1}catch{return!1}}async function dirHasPyFiles(e){try{return(await be(e,{withFileTypes:!0})).some(e=>e.isFile()&&e.name.endsWith(`.py`)&&e.name!==`__init__.py`)}catch{return!1}}async function findNearMissPackagesInDir(e){try{let t=await be(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory()||r.name.startsWith(`.`)||r.name.startsWith(`_`))continue;let t=isValidPythonIdentifier(r.name),i=await fileExists(R(e,r.name,`__init__.py`)),a=i||await dirHasPyFiles(R(e,r.name));t&&i||a&&n.push({name:r.name,needsRename:!t,needsInit:!i})}return n}catch{return[]}}async function findPackagesInDir(e){try{let t=await be(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let{name:t}=r;t.startsWith(`.`)||t.startsWith(`_`)||!isValidPythonIdentifier(t)||await fileExists(R(e,t,`__init__.py`))&&n.push({name:t,path:R(e,t)})}return n}catch{return[]}}async function discoverPythonPackages(e){let t=[],n=await findPackagesInDir(e);t.push(...n.map(e=>e.name));let r=R(e,`src`),i=await fileExists(R(r,`__init__.py`));if(await dirExists(r)&&!i){let e=await findPackagesInDir(r);t.push(...e.map(e=>`src.${e.name}`))}return t}async function checkPythonProject(e){let t=await discoverPythonPackages(e);if(t.length===1)return t[0];if(t.length>1){let e=t.map(e=>` - ${e}`).join(`
|
|
3
3
|
`);throw Error(`Multiple Python packages found:\n${e}\n\nApify CLI cannot determine which package to run.
|
|
4
4
|
Please specify the package using the --entrypoint flag, e.g.:
|
|
@@ -92,7 +92,7 @@ For platform-level management (deploy, list, call Actors), see 'apify actors' (p
|
|
|
92
92
|
`))}throw e}if(i.u(useAbortJobOnSignal({apifyClient:n,kind:N.RUN,jobId:y.id,runType:l,silent:p})),yield y,!p&&h)try{await outputJobLog({job:y,timeoutMillis:u,apifyClient:n})===`timeouts`?console.error(`\n${t.gray(`Timeout for printing logs was hit, there may be future logs.`)}\n`):console.error()}catch(e){warning({message:`Can not get log:`}),console.error(e)}if(y=await n.run(y.id).get(),m)for(;!Tr.includes(y.status)&&(y=await n.run(y.id).get(),!Tr.includes(y.status));)await new Promise(e=>{setTimeout(e,1e3)});g||(y.status===M.SUCCEEDED?p||success({message:`${l} finished.`}):y.status===M.RUNNING?p||warning({message:`${l} is still running!`}):y.status===M.ABORTED||y.status===M.ABORTING?(p||warning({message:`${l} was aborted!`}),e.exitCode=3):(p||error({message:`${l} failed!`}),e.exitCode=1)),yield y}catch(e){i.e=e}finally{i.d()}}const SharedRunOnCloudFlags=e=>({build:Y.string({char:`b`,description:`Tag or number of the build to run (e.g. "latest" or "1.2.34").`,required:!1}),timeout:Y.integer({char:`t`,description:`Timeout for the ${e} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:Y.integer({char:`m`,description:`Amount of memory allocated for the ${e} run, in megabytes.`,required:!1})}),Er={call:`Apify call`,"task-run":`Apify task run`};function isSucceeded(e){return e.status===M.SUCCEEDED}function getRunExitCode(e){switch(e.status){case M.SUCCEEDED:return 0;case M.ABORTED:case M.ABORTING:return 3;case M.TIMED_OUT:case M.TIMING_OUT:return 2;default:return e.exitCode&&e.exitCode!==0?e.exitCode:1}}function genericReason(e){switch(e.status){case M.ABORTED:case M.ABORTING:return`Actor run was aborted`;case M.TIMED_OUT:case M.TIMING_OUT:return`Actor run timed out`;default:return`Actor run failed`}}async function fetchRunLogTail(e,t){return isSucceeded(t)?[]:fetchLogTail(e,t.id,10)}function buildRunResultJson({run:e,operation:t,logTail:n}){let r=isSucceeded(e),i={ok:r,operation:t,actor:{id:e.actId,url:consoleActorUrl(e.actId)},run:{id:e.id,status:e.status,url:consoleRunUrl(e.actId,e.id)},storage:{defaultDatasetId:e.defaultDatasetId,defaultKeyValueStoreId:e.defaultKeyValueStoreId,datasetUrl:consoleDatasetUrl(e.defaultDatasetId)},exitCode:getRunExitCode(e)};return r||(i.error={phase:`run`,message:e.statusMessage||genericReason(e),logTail:n}),i}function printRunResultSummary({run:e,operation:n,logTail:r}){let i=isSucceeded(e),a=i?t.green:t.red,s=[`${Er[n]} result: ${a(e.status)}`,``,`${t.yellow(`Run`)}: ${a(e.status)}`,`${t.yellow(`Actor ID`)}: ${e.actId}`,`${t.yellow(`Run ID`)}: ${e.id}`,`${t.yellow(`Build number`)}: ${e.buildNumber}`];!i&&e.exitCode!=null&&s.push(`${t.yellow(`Exit code`)}: ${e.exitCode}`),s.push(`${t.yellow(`Dataset ID`)}: ${e.defaultDatasetId}`,`${t.yellow(`Key-value store ID`)}: ${e.defaultKeyValueStoreId}`,``,`${t.blue(`Run URL`)}: ${consoleRunUrl(e.actId,e.id)}`,`${t.blue(`Dataset URL`)}: ${consoleDatasetUrl(e.defaultDatasetId)}`),i||s.push(``,`${t.yellow(`Reason`)}:`,e.statusMessage||genericReason(e),...r),simpleLog({message:s.join(`
|
|
93
93
|
`),stdout:!0})}async function finalizeRun({apifyClient:t,run:n,operation:r,json:i,silent:a}){if(e.exitCode=getRunExitCode(n),a)return;let s=await fetchRunLogTail(t,n);i?printJsonToStdout(buildRunResultJson({run:n,operation:r,logTail:s})):printRunResultSummary({run:n,operation:r,logTail:s})}var Dr=class ActorsCallCommand extends ApifyCommand{static name=`call`;static enableProfileFlag=!0;static description=`Executes Actor remotely using your authenticated account.
|
|
94
94
|
Reads input from local key-value store by default.
|
|
95
|
-
To inspect the input schema before creating a JSON input, use "apify actors info <actor> --input".`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Inspect the Actor input schema before preparing JSON input.`,command:`apify actors info apify/hello-world --input`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional inline JSON object input for the Actor. To avoid shell parsing issues, wrap the JSON in quotes. For JSON files, use --input-file.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({char:`f`,description:"Optional path to a file with
|
|
95
|
+
To inspect the input schema before creating a JSON input, use "apify actors info <actor> --input".`;static group=`Apify Console`;static examples=[{description:`Call the Actor defined in the current directory (from .actor/actor.json).`,command:`apify call`},{description:`Call a specific Actor by its full name.`,command:`apify call apify/hello-world`},{description:`Inspect the Actor input schema before preparing JSON input.`,command:`apify actors info apify/hello-world --input`},{description:`Call an Actor with inline JSON input.`,command:`apify call apify/hello-world --input '{"url":"https://example.com"}'`},{description:`Call an Actor with input from a file and print the dataset on success.`,command:`apify call apify/web-scraper --input-file input.json --output-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-call`;static flags={...SharedRunOnCloudFlags(`Actor`),input:Y.string({char:`i`,description:`Optional inline JSON object input for the Actor. To avoid shell parsing issues, wrap the JSON in quotes. For JSON files, use --input-file.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({char:`f`,description:"Optional path to a JSON file with input for the Actor. To read from standard input and wait until all input arrives, use `-`. Without this flag or `--input`, the CLI still reads standard input, but stops waiting if input is slow to start or pauses.",required:!1,stdin:2,exclusive:[`input`]}),silent:Y.boolean({char:`s`,description:`Prevents printing the logs of the Actor run to the console.`,default:!1}),"output-dataset":Y.boolean({char:`o`,description:`Prints out the entire default dataset on successful run of the Actor.`})};static enableJsonFlag=!0;static args={actorId:Z.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 '${G}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getCurrentUserInfo(),s=a.username||a.id;if(this.flags.json&&this.flags.outputDataset){error({message:`You cannot use both --json and --output-dataset. Use --json for run details or --output-dataset for dataset items.`}),e.exitCode=5;return}let{id:c,userFriendlyId:l,actorData:u}=await ActorsCallCommand.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={waitForFinish:2};this.flags.build&&(f.build=this.flags.build),this.flags.timeout!==void 0&&(f.timeout=this.flags.timeout),this.flags.memory&&(f.memory=this.flags.memory);let p=await getInputOverride(n,this.flags.input,this.flags.inputFile,{schemaHint:`Run "apify actors info ${l} --input" to inspect the Actor input schema.`});if(p===!1)return;let m=!1,h,g=runActorOrTaskOnCloud(i,{actorOrTaskData:{id:c,userFriendlyId:l},runOptions:f,type:`Actor`,inputOverride:p?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of g)if(h=e,!m&&(m=!0,!this.flags.silent)){let n=consoleRunUrl(c,e.id),r=[`${t.yellow(`Started`)}: ${q.display(e.startedAt)}`];e.containerUrl&&r.push(`${t.yellow(`Container URL`)}: ${t.blue(e.containerUrl)}`);let i=h.buildNumber.split(`.`).slice(0,2).join(`.`),a=u.versions.find(e=>e.versionNumber===i),s=Object.entries(u.taggedBuilds??{}).find(([,t])=>t.buildNumber===e.buildNumber)?.[0],l=[`${t.yellow(`Build`)}:`,t.cyan(h.buildNumber)];s?l.push(`(${t.yellow(s)})`):l.push(`(${t.gray(`N/A`)})`),a&&l.push(`| ${t.gray(`Actor version:`)} ${t.cyan(a.versionNumber)} (${t.yellow(a.buildTag)})`),r.push(l.join(` `)),r.push(`${t.yellow(`Timeout`)}: ${h.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),r.push(`${t.yellow(`Memory`)}: ${h.options.memoryMbytes} MB`),r.push(`${t.blue(`View on Apify Console`)}: ${n}`,``),simpleLog({message:r.join(`
|
|
96
96
|
`),stdout:!this.flags.json})}if(await finalizeRun({apifyClient:i,run:h,operation:`call`,json:this.flags.json,silent:this.flags.silent}),!this.flags.json&&this.flags.outputDataset&&h.status===M.SUCCEEDED){let e=h.defaultDatasetId,t,n=4;do{if(t=await i.dataset(e).get(),t?.itemCount)break;await new Promise(e=>{setTimeout(e,250)})}while(n--);let r=await i.dataset(e).downloadItems(O.JSON,{clean:!0});console.log(r.toString())}}static async resolveActorId({client:e,localActorName:t,usernameOrId:n,providedActorNameOrId:r}){if(r?.includes(`/`)){let t=await e.actor(r).get();if(!t)throw Error(`Cannot find Actor with ID '${r}' in your account.`);return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t}}if(r){let t=await e.actor(r).get();if(t)return{userFriendlyId:`${t.username}/${t.name}`,id:t.id,actorData:t};let i=await e.actor(`${n}/${r.toLowerCase()}`).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};throw Error(`Cannot find Actor with name or ID '${r}' in your account.`)}if(t){let r=await e.actor(`${n}/${t}`).get();if(!r)throw Error(`Cannot find Actor with ID '${n}/${t}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${r.username}/${r.name}`,id:r.id,actorData:r}}throw Error(`Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.`)}};const Or={[-1]:void 0,0:{mid:``,"left-mid":``,"mid-mid":``,"right-mid":``,middle:` `,"top-mid":`─`,"bottom-mid":`─`},1:{middle:` `,"top-mid":`─`,"bottom-mid":`─`,top:`─`,bottom:`─`,"left-mid":`├`,mid:`─`,"mid-mid":`─`,"right-mid":`┤`},2:{left:``,right:``,mid:``,"bottom-left":``,"bottom-mid":``,"bottom-right":``,top:``,"top-left":``,"top-mid":``,"top-right":``,"left-mid":``,"mid-mid":``,"right-mid":``,bottom:``,middle:` `}};function generateHeaderColors(e){return Array.from({length:e},()=>`cyan`)}const kr=process.stdout.columns??100,Ar=Symbol.for(`@apify/cli:responsive-table:skip-column`);var Q=class ResponsiveTable{options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let t=ResponsiveTable.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,n=generateHeaderColors(t.length),r=e===0||e===2,i=Or[e],a=[],s=[],c=[];for(let e of t)this.options.hiddenColumns?.includes(e)||this.rows.some(t=>t[e]===Ar)||(a.push(this.options.columnAlignments?.[e]||`left`),ResponsiveTable.isSmallTerminal()?(s.push(this.options.breakpointOverrides?.small?.[e]?.label??e),c.push(this.options.breakpointOverrides?.small?.[e]?.valueFrom??e)):(s.push(e),c.push(e)));let l=new Et({head:s,style:{head:n,compact:r},colAligns:a,chars:i});for(let e of this.rows){let t=c.map(t=>e[t]);l.push(t)}return l.toString()}static isSmallTerminal(){return kr<100}};function formatEventPrice(e){return e===0?`$0.00`:e>=.01?`$${e.toFixed(2)}`:`$${Number(e.toPrecision(2))}`}async function getDefaultBuild(e,t,n){try{return await(await e.actor(t).defaultBuild()).get()??n}catch(e){if(e.statusCode===404)return n;throw e}}const jr=``,Mr=new Q({allColumns:[``,jr],mandatoryColumns:[``,jr],columnAlignments:{"":`left`,[jr]:`right`}});var ActorsInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Get information about an Actor.`;static examples=[{description:`Print summary information about an Actor.`,command:`apify actors info apify/hello-world`},{description:`Print the Actor README only.`,command:`apify actors info apify/hello-world --readme`},{description:`Print the Actor input schema as JSON.`,command:`apify actors info apify/hello-world --input`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-actors-info`;static flags={readme:Y.boolean({description:`Return the Actor README.`,exclusive:[`input`]}),input:Y.boolean({description:`Return the Actor input schema.`,exclusive:[`readme`]})};static args={actorId:Z.string({description:`The ID of the Actor to return information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:n,input:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),s=await resolveActorContext({providedActorNameOrId:e,client:a});if(!s.valid){error({message:`${s.reason}. Please specify the Actor ID.`,stdout:!0});return}let c=await a.actor(s.id).get();c.actorMaker=await a.user(c.userId).get();for(let e of Object.values(c.taggedBuilds??{}))e.buildId&&(e.build=await a.build(e.buildId).get());if(i){printJsonToStdout(c);return}if(n||r){let e=await getDefaultBuild(a,s.id,c.taggedBuilds?.latest?.build);if(n){if(!e?.readme){error({message:`No README found for this Actor.`,stdout:!0});return}simpleLog({message:e.readme,stdout:!0});return}if(!e?.inputSchema){error({message:`No input schema found for this Actor.`,stdout:!0});return}simpleLog({message:e.inputSchema,stdout:!0});return}let l=[`Information about Actor ${t.yellow(`${c.username}/${c.name}`)} (${t.gray(c.id)})`,``];c.title&&l.push(`${t.yellow(`Title:`)} ${t.bold(c.title)}`),c.description&&l.push(`${t.yellow(`Description:`)} ${c.description}`),l.push(`${t.yellow(`Created at:`)} ${t.cyan(q.display(c.createdAt))} ${t.gray(`|`)} ${t.yellow(`Updated at:`)} ${t.cyan(q.display(c.modifiedAt))}`),c.actorMaker&&(l.push(``,`${t.yellow(`Made by:`)} ${t.cyan(c.actorMaker.profile.name??c.actorMaker.username)}`),Reflect.get(c,`isCritical`)&&(l[l.length-1]+=` ${t.bgGray(`Maintained by Apify`)}`)),c.isPublic?l.push(``,`${t.yellow(`Actor is`)} ${t.green(`PUBLIC`)}`):l.push(``,`${t.yellow(`Actor is`)} ${t.cyan(`PRIVATE`)}`),c.isDeprecated&&l.push(``,`${t.yellow(`Actor is`)} ${t.red(`DEPRECATED`)}`);let u=c.pricingInfos;if(u?.length){let e=u.at(-1);switch(e.pricingModel){case`FLAT_PRICE_PER_MONTH`:if(l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${e.pricePerUnitUsd}/month + usage`)}`),e.trialMinutes){let n=e.trialMinutes*60*1e3,r=sr.format(n);l.push(` ${t.yellow(`Trial duration:`)} ${t.bold(r)}`)}break;case`PRICE_PER_DATASET_ITEM`:{let n=e.pricePerUnitUsd*1e3;l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`$${n.toFixed(2)} / 1,000 results`)}`);break}case`PAY_PER_EVENT`:{l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay per event`)}`);let n=Object.values(e.pricingPerEvent?.actorChargeEvents??{});for(let e of n){let n=e.eventPriceUsd,r=e.eventTieredPricingUsd,i;i=typeof n==`number`?formatEventPrice(n):r&&Object.keys(r).length>0?`from ${formatEventPrice(Math.min(...Object.values(r).map(e=>e.tieredEventPriceUsd)))} (tiered)`:`N/A`,Mr.pushRow({"":e.eventTitle,[jr]:t.bold(i)})}let r=Mr.render(0).split(`
|
|
97
97
|
`);r.splice(1,1),l.push(r.join(`
|
|
98
98
|
`));break}case`FREE`:l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);break;default:{let n=e.pricingModel;l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Unknown pricing model (${t.yellow(n)})`)}`)}}}else l.push(`${t.yellow(`Pricing information:`)} ${t.bgGray(`Pay for usage`)}`);(c.seoTitle||c.seoDescription)&&(l.push(``,t.yellow(`SEO information:`)),c.seoTitle&&l.push(` ${t.yellow(`Title:`)} ${c.seoTitle}`),c.seoDescription&&l.push(` ${t.yellow(`Description:`)} ${c.seoDescription}`));let{stats:f}=c;if(l.push(``,t.yellow(`Actor stats:`),` ${t.yellow(`Total users:`)} ${t.cyan(`${f.totalUsers}`)}`,` ${t.yellow(`Users (30d):`)} ${t.cyan(`${f.totalUsers30Days}`)}`,` ${t.yellow(`Total runs:`)} ${t.cyan(`${f.totalRuns}`)}`),c.taggedBuilds){l.push(``,t.yellow(`Builds:`));let e=c.taggedBuilds.latest;e&&l.push(` ${t.yellow(`-`)} ${t.cyan(e.buildNumber)} ${t.gray(`/`)} ${t.yellow(`latest`)}`);for(let[e,n]of Object.entries(c.taggedBuilds))e!==`latest`&&l.push(` ${t.yellow(`-`)} ${t.cyan(n.buildNumber)} ${t.gray(`/`)} ${t.yellow(e)}`)}simpleLog({message:l.join(`
|
|
@@ -110,10 +110,10 @@ Use --force to override newer remote versions.`;static group=`Local Actor Develo
|
|
|
110
110
|
`)}),e.exitCode=4;return}let i=await getLoggedClientOrThrow(),a=await useActorConfig({cwd:n});if(a.isErr()){error({message:a.unwrapErr().message}),e.exitCode=5;return}let{config:s}=a.unwrap(),c=resolveDockerContext(n,s?.dockerContextDir);if(c.kind===`invalid`){error({message:c.message}),e.exitCode=5;return}if(c.kind===`outside`){error({message:monorepoUnsupportedMessage(s?.name??fe(n))}),e.exitCode=255;return}let l=await getCurrentUserInfo(),u=l.organizationOwnerUserId?`/organization/${l.id}`:``,f,p,m=!1,h=this.flags.version||s?.version||`0.0`,g=this.flags.buildTag||s?.buildTag;!g&&h===`0.0`&&(g=`latest`);let v=parseWaitForFinishMillis(this.flags.waitForFinish),y=this.args.actorId;if(y){if(p=await i.actor(y).get(),!p)throw Error(`Cannot find Actor with ID '${y}' in your account.`);f=p.id}else{let e=l.username||l.id;if(p=await i.actor(`${e}/${s.name}`).get(),p)f=p.id;else{let{templates:e}=await At(),t=e.find(e=>e.name===s.template)?.defaultRunOptions||Rr,n={name:s.name,title:s.title,description:s.description,defaultRunOptions:t,versions:[{versionNumber:h,buildTag:g,sourceType:te.SOURCE_FILES,sourceFiles:[]}]};s.usesStandbyMode&&(n.actorStandby={isEnabled:!0}),p=await i.actors().create(n),f=p.id,m=!0,info({message:`Created Actor with name ${s.name} on Apify.`})}}this.telemetryData.push={actorId:f,wasCreated:m};let b=i.actor(f);info({message:`Deploying Actor '${s.name}' to Apify.`});let x=await sumFilesSizeInBytes(r,n);if(x<ie&&!m){let e=await b.get(),t=r.reduce((e,t)=>{let{mtimeMs:r,ctimeMs:i}=S(R(n,t)),a=r>i?r:i;return e>a?e:a},0),i=e?.modifiedAt.valueOf();if(!this.flags.force&&i&&t<i&&(s?.name||y))throw Error(`Actor with identifier "${s?.name||y}" already exists on the platform and has newer changes than your local copy.
|
|
111
111
|
Skipping push. Use --force to override.`)}let w=await b.version(h).get();if(w?.sourceType===te.GIT_REPO&&!await confirmGitSourceSwitch({actorName:p.name,gitRepoUrl:w.gitRepoUrl,force:this.flags.force})){info({message:`Push aborted. Actor ${p.name} still builds from its Git repository.`});return}let T,E,D;if(x<ie)E=await createSourceFiles(r,n),T=te.SOURCE_FILES;else{run({message:`Zipping Actor files`}),await createActZip(Lr,r,n);let e=await i.keyValueStores().getOrCreate(`actor-${f}-source`),t=`version-${h}.zip`,a=_(Lr);await i.keyValueStore(e.id).setRecord({key:t,value:a,contentType:`application/zip`}),C(Lr);let s=new URL(`${i.baseUrl}/key-value-stores/${e.id}/records/${t}?disableRedirect=true`);if(e?.urlSigningSecretKey){let n=se(e.urlSigningSecretKey,t);s.searchParams.set(`signature`,n)}D=s.toString(),T=te.TARBALL}let O=s.environmentVariables?transformEnvToEnvVars(s.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets}):void 0,k=this.flags.applyEnvVarsToBuild??s.applyEnvVarsToBuild;if(w){let e={tarballUrl:D,sourceFiles:E,buildTag:g,sourceType:T,envVars:O,applyEnvVarsToBuild:k};await b.version(h).update(e),run({message:`Updated version ${h} for Actor ${p.name}.`})}else{let e={versionNumber:h,tarballUrl:D,sourceFiles:E,buildTag:g,sourceType:T,envVars:O,applyEnvVarsToBuild:k};await b.versions().create({...e}),run({message:`Created version ${h} for Actor ${p.name}.`})}if(!m&&!!s.usesStandbyMode!=!!p.actorStandby?.isEnabled){let e=!!s.usesStandbyMode;await b.update({actorStandby:{isEnabled:e}}),info({message:`${e?`Enabled`:`Disabled`} standby mode for Actor ${p.name}.`})}run({message:`Building Actor ${p.name}`});let A=v===void 0?1/0:Date.now()+v,j=await b.build(h,{useCache:!0,waitForFinish:2});t.u(useAbortJobOnSignal({apifyClient:i,kind:N.BUILD,jobId:j.id}));try{let e=Number.isFinite(A)?Math.max(0,A-Date.now()):void 0;await outputJobLog({job:j,timeoutMillis:e,apifyClient:i})}catch(e){warning({message:`Can not get log:`}),console.error(e)}let ee=j.id;if(j=await i.build(ee).get(),!j){error({message:`Could not fetch build with ID "${ee}" after deployment.`}),e.exitCode=1;return}for(;!isTerminalStatus(j.status)&&Date.now()<A;)await new Promise(e=>setTimeout(e,1e3)),j=await i.build(j.id).get();if(j.status===M.SUCCEEDED&&g&&v!==0){run({message:`Applying build tag "${g}"...`});let e=Date.now()+5e3,t=!1;for(;Date.now()<e;){if((await b.get())?.taggedBuilds?.[g]?.buildId===j.id){t=!0;break}await new Promise(e=>setTimeout(e,1e3))}t||warning({message:`Build succeeded but tag "${g}" was not set after 5 seconds; subsequent calls referencing this tag may not find it.`})}let P=j.status,F=resolvePushOutcome(P),I=`${getConsoleUrl()}${u}/actors/${j.actId}`,ne=`${I}/builds/${j.buildNumber}`,re=[];if(F.errorMessage)try{let e=await i.log(j.id).get();e&&(re=e.split(`
|
|
112
112
|
`).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-10))}catch{}F.exitCode&&(e.exitCode=F.exitCode);let ae={ok:F.ok,operation:`push`,actor:{id:j.actId,url:I},build:{id:j.id,number:j.buildNumber,status:P,url:ne}};if(F.exitCode!==void 0&&(ae.exitCode=F.exitCode),F.errorMessage&&(ae.error={phase:`build`,message:F.errorMessage,logTail:re}),this.flags.json){printJsonToStdout(ae);return}simpleLog({stdout:!0,message:[`Apify push result: ${F.resultLabel}`,``,`Upload: SUCCEEDED`,`Build: ${P}`,`Actor ID: ${j.actId}`,`Build ID: ${j.id}`,`Build number: ${j.buildNumber}`,...F.exitCode?[`Exit code: ${F.exitCode}`]:[],``,`Actor URL: ${I}`,`Build URL: ${ne}`,...F.errorMessage&&re.length?[``,`Reason:`,...re]:[]].join(`
|
|
113
|
-
`)}),this.flags.open&&await kt(I)}catch(e){t.e=e}finally{t.d()}}},ActorsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;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:Z.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.`});else if(!await X({message:`Are you sure you want to delete this Actor?`,
|
|
113
|
+
`)}),this.flags.open&&await kt(I)}catch(e){t.e=e}finally{t.d()}}},ActorsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;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:Z.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.`});else if(!await X({message:`Are you sure you want to delete this Actor?`,preAnswered:t||void 0}))info({message:`Deletion of Actor "${e}" was canceled.`});else 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 zr={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?zr[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.
|
|
114
114
|
|
|
115
115
|
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:Z.string({description:`Search query to find Actors by title, name, description, username, or readme.`,required:!1})};static flags={"sort-by":Y.string({description:`Sort order for the results.`,choices:[`relevance`,`popularity`,`newest`,`lastUpdate`],default:`relevance`}),category:Y.string({description:`Filter by category (e.g. AI).`}),username:Y.string({description:`Filter by Actor author username.`}),"pricing-model":Y.string({description:`Filter by pricing model.`,choices:[`FREE`,`FLAT_PRICE_PER_MONTH`,`PRICE_PER_DATASET_ITEM`,`PAY_PER_EVENT`]}),limit:Y.integer({description:`Maximum number of results to return.`,default:20}),offset:Y.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=new D(getAnonymousApifyClientOptions()),f;try{f=await u.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(f.count===0){if(n){printJsonToStdout(f);return}info({message:`No Actors found matching your search.`,stdout:!0});return}if(n){printJsonToStdout(f);return}let p=new Q({allColumns:[`Name`,`Description`,`Users (30d)`,`Pricing`],mandatoryColumns:[`Name`,`Pricing`],columnAlignments:{"Users (30d)":`right`,Name:`left`}});for(let e of f.items)p.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:p.render(1),stdout:!0})}},ActorsStartCommand=class extends ApifyCommand{static name=`start`;static enableProfileFlag=!0;static description=`Starts Actor remotely and returns run details immediately.
|
|
116
|
-
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:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a file with
|
|
116
|
+
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:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a JSON file with input for the Actor. To read from standard input and wait until all input arrives, use `-`. Without this flag or `--input`, the CLI still reads standard input, but stops waiting if input is slow to start or pauses.",required:!1,stdin:2,exclusive:[`input`]})};static enableJsonFlag=!0;static args={actorId:Z.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 '${G}' file.`})};async run(){let n=e.cwd(),r=getLocalConfig(n)||{},i=await getLoggedClientOrThrow(),a=await getCurrentUserInfo(),s=a.username||a.id,{id:c,userFriendlyId:l,actorData:u}=await Dr.resolveActorId({client:i,localActorName:r.name,usernameOrId:s,providedActorNameOrId:this.args.actorId}),f={};this.flags.build&&(f.build=this.flags.build),this.flags.timeout!==void 0&&(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);this.flags.json?printJsonToStdout({ok:!0,operation:`actors.start`,waited:!1,actor:{id:c,url:consoleActorUrl(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}):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(`
|
|
117
117
|
`),stdout:!0})}},ActorsIndexCommand=class extends ApifyCommand{static name=`actors`;static description=`Search, list, deploy, and call Actors on the Apify platform.
|
|
118
118
|
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,Dr,ActorsBuildCommand];async run(){this.printHelp()}};const Br=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],Vr=/* @__PURE__ */ 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 Ur={GET:t.green,POST:t.yellow,PUT:t.blue,PATCH:t.cyan,DELETE:t.red};function formatEndpointLine(e){let n=(Ur[e.method]||t.white)(e.method.padEnd(7)),r=e.summary?t.gray(` ${e.summary}`):``;return`${n} ${e.path}${r}`}const Wr=`Run ${t.cyan(`apify api --list-endpoints`)} to see all available Apify API endpoints.`;function printSuggestions(e){if(e.length>0){simpleLog({message:`
|
|
119
119
|
Did you mean:`,stdout:!1});for(let t of e)simpleLog({message:` ${formatEndpointLine(t)}`,stdout:!1})}simpleLog({message:`\n${Wr}`,stdout:!1})}var ApiCommand=class extends ApifyCommand{cachedEndpoints=null;static name=`api`;static enableProfileFlag=!0;static description=`Makes an authenticated HTTP request to the Apify API and prints the response.
|
|
@@ -129,12 +129,12 @@ By default, you confirm logging in to Apify Console in your browser by entering
|
|
|
129
129
|
Run 'apify login' to authenticate again.`;static group=`Authentication`;static examples=[{description:`Remove the stored Apify credentials.`,command:`apify logout`},{description:`Log out of one stored account and keep the active one.`,command:`apify logout --profile my-org`},{description:`Log out of every stored account without a prompt.`,command:`apify logout --all --yes`}];static flags={profile:Y.string({description:`The stored account to log out of, by name or user ID. See "apify auth list".`,exclusive:[`all`]}),all:Y.boolean({description:`Log out of every stored account.`,exclusive:[`profile`]}),...YesFlag()};static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-logout`;async run(){if(!this.flags.profile&&!p(AUTH_FILE_PATH())){let t=await clearKeyringSecrets();t.length?(error({message:partialLogoutMessage(t,null,{hadFile:!1})}),e.exitCode=1):info({message:yn})}else if(!(this.flags.all?await this.logOutOfAll():await this.logOutOf(this.flags.profile)))return;let t=readEnvToken();t.kind===`token`?warning({message:`${F.TOKEN} is still set, so commands stay authenticated with that token.`}):t.kind===`invalid`&&warning({message:invalidEnvTokenMessage(t.raw)})}async logOutOf(t){let n=getActiveProfileId(),r=t?await requireProfile(t):void 0,i=r?.id??n,a=i===n,s=await clearKeyringSecrets(i,{keepLegacy:!a}),c=null,l={};try{l=removeProfile(i)}catch(e){c=e}let{removed:u,active:f}=l;if(a&&!c&&await updateUserId(f?.id??null),s.length||c){let t=!a&&r?profileLabel(r):void 0;error({message:partialLogoutMessage(s,c,{keptAccount:t})}),e.exitCode=1}else success(a?f?{message:`You are logged out${u?` of ${profileLabel(u)}`:``}. ${profileLabel(f)} is now the active account.`}:{message:`You are logged out from your Apify account.`}:{message:`You are logged out${u?` of ${profileLabel(u)}`:``}.${f?` ${profileLabel(f)} is still the active account.`:``}`});return!0}async logOutOfAll(){let t=listProfiles();if(t.length&&!this.flags.yes&&!await X({message:`Log out of ${t.length===1?`your stored account`:`all ${t.length} stored accounts`}?`,errorMessageForStdin:`Use --yes to log out of every stored account without a prompt.`}))return info({message:`Logout was cancelled.`}),!1;let n=await clearKeyringSecrets();for(let e of/* @__PURE__ */ new Set([getActiveProfileId(),...t.map(e=>e.id)]))n.push(...await clearKeyringSecrets(e,{keepLegacy:!0}));let r=null;try{removeAllProfiles()}catch(e){r=e}return r||await updateUserId(null),n.length||r?(error({message:partialLogoutMessage(n,r)}),e.exitCode=1):success({message:`You are logged out of all your Apify accounts.`}),!0}};function reasonOf(e){return e instanceof Error?e.message:String(e)}function partialLogoutMessage(e,t,{hadFile:n=!0,keptAccount:r}={}){return`Logout did not finish. ${e.length?`Your secrets are still in the OS keyring at ${describeLeftovers(e)}; delete them with your OS keyring app.`:`Your secrets were removed from the OS keyring.`}${n?t?r?` ${r} is still stored in ${tildify(AUTH_FILE_PATH())}; run the logout again to remove it.`:` Your account is still in ${tildify(AUTH_FILE_PATH())}; delete that file to finish logging out.`:` Your account was removed from ${tildify(AUTH_FILE_PATH())}.`:``} The reason was: ${[leftoverReasons(e),t?reasonOf(t):``].filter(Boolean).join(` `)}`}const Yr=stdinCheckWrapper(async({message:e,choices:t,pageSize:n,loop:r,default:i})=>await Rt({message:e,choices:t,pageSize:n,loop:r,default:i},Dn),{errorMessageForStdin:`Please provide the selection using the command options.`});var AuthSwitchCommand=class extends ApifyCommand{static name=`switch`;static description=`Sets the stored account that commands use. Without an argument, prompts you to pick one of the stored accounts.`;static group=`Authentication`;static interactive=!0;static interactiveNote=`Prompts for the account when called without an argument. Pass the name or user ID to skip the prompt.`;static args={profile:Z.string({description:`The stored account to make active, by name or user ID. See "apify auth list".`})};static examples=[{description:`Pick the active account from a list.`,command:`apify auth switch`},{description:`Make the "my-org" account active.`,command:`apify auth switch my-org`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth-switch`;async run(){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`the active account`));let t=await requireProfile(this.args.profile??await this.pickProfile());if(!await getSecret(t.id,`token`))throw e.exitCode=1,Error(missingProfileTokenMessage(t));t.id===getActiveProfileId()?info({message:`${profileLabel(t)} is already the active account.`}):(setActiveProfile(t.id),await updateUserId(t.id),success({message:`${profileLabel(t)} is now the active account.`}))}async pickProfile(){await ensureCredentialsCurrent();let t=listProfiles();if(!t.length)throw e.exitCode=1,Error(yn);return Yr({message:`Which account do you want to use?`,choices:t.map(e=>({name:`${profileLabel(e)} (${e.id})`,value:e.id})),default:getActiveProfileId(),errorMessageForStdin:`Pass the account to switch to, for example "apify auth switch <name>". Run "apify auth list" to see the stored accounts.`})}},AuthTokenCommand=class extends ApifyCommand{static name=`token`;static enableProfileFlag=!0;static description=`Prints the API token the CLI authenticates with, resolved from APIFY_TOKEN or the token from 'apify login'.
|
|
130
130
|
Tokens from an OAuth login expire after about an hour. The command prints the expiry time to stderr.`;static examples=[{description:`Print the resolved API token to stdout. Be careful with the output, it's 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 resolveAuth();simpleLog({message:e.token,stdout:!0});let t=e.profile?lookUpProfile(e.profile.id).profile:void 0;t?.authMethod===`oauth2`&&t.expiresAt&&simpleLog({message:`Note: this token expires at ${t.expiresAt}.`})}},AuthIndexCommand=class extends ApifyCommand{static name=`auth`;static description="Log in, log out, switch between stored accounts, and inspect your stored Apify API token. Also available as `apify login` and `apify logout`.";static group=`Authentication`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-auth`;static subcommands=[AuthLoginCommand,AuthLogoutCommand,AuthListCommand,AuthSwitchCommand,AuthTokenCommand];async run(){this.printHelp()}},BuildsAddTagCommand=class extends ApifyCommand{static name=`add-tag`;static enableProfileFlag=!0;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});else 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 enableProfileFlag=!0;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`)}: ${q.display(r.startedAt)}`];if(r.finishedAt)f.push(` ${t.yellow(`Finished`)}: ${q.display(r.finishedAt)} (took ${t.gray(sr.format(r.stats?.durationMillis??0))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(` ${t.yellow(`Finished`)}: ${t.gray(`Running for ${sr.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=consoleBuildUrl(r.actId,r.buildNumber);f.push(`${t.blue(`View in Apify Console`)}: ${m}`),simpleLog({message:f.join(`
|
|
131
131
|
`),stdout:!0})}},BuildsLogCommand=class extends ApifyCommand{static name=`log`;static enableProfileFlag=!0;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 enableProfileFlag=!0;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(`
|
|
132
|
-
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${cr.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${cr.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{static name=`remove-tag`;static enableProfileFlag=!0;static description=`Removes a tag from a specific Actor build.`;static examples=[{description:`Remove a tag from a build (prompts for confirmation).`,command:`apify builds remove-tag --build <buildId> --tag beta`},{description:`Remove a tag non-interactively.`,command:`apify builds remove-tag --build <buildId> --tag beta --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c)error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});else if(c.buildId!==e)error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});else if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,
|
|
132
|
+
`),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:n}){let r=tableFactory();for(let i of e){let e=Reflect.get(i,`buildNumber`),a=n[e]?` (${t.yellow(n[e])})`:``,s;if(i.finishedAt){let e=i.finishedAt.getTime()-i.startedAt.getTime();s=t.gray(`${cr.format(e,void 0,{left:``})}`)}else{let e=Date.now()-i.startedAt.getTime();s=t.gray(`Running for ${cr.format(e,void 0,{left:``})}`)}r.pushRow({Number:`${e}${a}`,ID:t.gray(i.id),Status:prettyPrintStatus(i.status),Took:s})}return r}},BuildsRemoveTagCommand=class extends ApifyCommand{static name=`remove-tag`;static enableProfileFlag=!0;static description=`Removes a tag from a specific Actor build.`;static examples=[{description:`Remove a tag from a build (prompts for confirmation).`,command:`apify builds remove-tag --build <buildId> --tag beta`},{description:`Remove a tag non-interactively.`,command:`apify builds remove-tag --build <buildId> --tag beta --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-remove-tag`;static flags={build:Y.string({char:`b`,description:`The build ID to remove the tag from.`,required:!0}),tag:Y.string({char:`t`,description:`The tag to remove from the build.`,required:!0}),...YesFlag()};async run(){let{build:e,tag:n,yes:r}=this.flags,i=await getLoggedClientOrThrow(),a=await i.build(e).get();if(!a){error({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await i.actor(a.actId).get();if(!s){error({message:`Actor with ID "${a.actId}" was not found.`,stdout:!0});return}let c=(s.taggedBuilds??{})[n];if(!c)error({message:`Tag "${n}" does not exist on Actor "${s.name}".`,stdout:!0});else if(c.buildId!==e)error({message:`Tag "${n}" is not associated with build "${e}". It points to build "${c.buildNumber}" (${c.buildId}).`,stdout:!0});else if(!await X({message:`Are you sure you want to remove tag "${t.yellow(n)}" from build ${t.gray(a.buildNumber)}?`,preAnswered:r||void 0}))info({message:`Tag removal was canceled.`,stdout:!0});else try{await i.actor(a.actId).update({taggedBuilds:{[n]:null}}),success({message:`Tag "${t.yellow(n)}" removed from build ${t.gray(a.buildNumber)} (${t.gray(e)})`,stdout:!0})}catch(t){let r=t;error({message:`Failed to remove tag "${n}" from build "${e}".\n ${r.message||r}`,stdout:!0})}}};const Xr=stdinCheckWrapper(async({message:e,expectedValue:t,failureMessage:n})=>await Ie({message:e,validate(e){return e===t?!0:n??`That is not the correct input!`}},Dn));var BuildsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Permanently removes an Actor build from the Apify platform.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Tagged builds additionally require typing the tag name.`;static examples=[{description:`Delete a build (prompts for confirmation).`,command:`apify builds rm <buildId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-rm`;static args={buildId:Z.string({description:`The build ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{buildId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.build(e).get();if(!r)throw Error(`Build with ID "${e}" was not found on your account.`);let i=await n.actor(r.actId).get(),a;if(i?.taggedBuilds){for(let[t,n]of Object.entries(i.taggedBuilds))if(e===n.buildId){a=t;break}}let s;s=a?await Xr({message:`Are you sure you want to delete this Actor Build? If so, please type in "${a}":`,expectedValue:a,failureMessage:`Your provided value does not match the build tag.`,preAnswered:t?a:void 0}):await X({message:`Are you sure you want to delete this Actor Build?`,preAnswered:t||void 0}),s?(await n.build(e).delete(),success({message:`Build with ID "${e}" was deleted.`,stdout:!0})):info({message:`Deletion of build "${e}" was canceled.`,stdout:!0})}},BuildsWaitCommand=class extends ApifyCommand{static name=`wait`;static enableProfileFlag=!0;static description=`Waits for an Actor build to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
|
|
133
133
|
Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a build to finish and return a non-zero exit code on failure.`,command:`apify builds wait <buildId>`},{description:`Wait for a build and emit a structured JSON result.`,command:`apify builds wait <buildId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds-wait`;static enableJsonFlag=!0;static args={buildId:Z.string({required:!0,description:`The build ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`In seconds, how long to wait before giving up. If skipped, it waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`In seconds, how often to poll the platform. Defaults to 2.`,required:!1})};async run(){let{buildId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:N.BUILD,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleBuildUrl(l.actId,l.buildNumber),f=l.status===M.SUCCEEDED,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},N.BUILD),m=`Gave up waiting after ${n}s; build is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`builds.wait`,timedOutWaiting:c,build:{id:l.id,status:l.status,number:l.buildNumber,url:u},...f?{}:{error:{phase:`build`,message:c?m:`Actor build did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Build`,value:l.status},{label:`Build ID`,value:l.id},{label:`Build number`,value:l.buildNumber},{label:`Actor ID`,value:l.actId}],_=[{label:`Build URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify build result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Build ended with status ${l.status}.`}),e.exitCode=p}},BuildsIndexCommand=class extends ApifyCommand{static name=`builds`;static description=`Create, inspect, tag, and delete Actor builds on the Apify platform.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-builds`;static subcommands=[BuildsAddTagCommand,BuildsRemoveTagCommand,BuildsRmCommand,BuildsLsCommand,BuildsLogCommand,BuildsInfoCommand,BuildsCreateCommand,BuildsWaitCommand];async run(){this.printHelp()}},TopLevelCallCommand=class extends Dr{static name=`call`};const pathToInstallMarker=e=>R(e,`.install-marker`);var InstallCommand=class extends ApifyCommand{static name=`install`;static description=`Finalizes the first-time setup of Apify and Actor CLI.`;static hidden=!0;static flags={"shims-only":Y.boolean({description:`Only (re)create the apify/actor wrapper scripts next to the bundle, then exit. Used by the install/upgrade scripts.`,hidden:!0,default:!1})};async run(){let{installMethod:n,installPath:r,version:i}=useCLIMetadata();if(n!==`bundle`){info({message:`Apify and Actor CLI are already fully configured! 👍`});return}if(zt(r,`When CLI is installed via bundles, the install path must be set`),writeEntrypointShims(r,e.platform===`win32`),cliDebugPrint(`[install] wrote entrypoint shims to`,r),this.flags.shimsOnly)return;let a=pathToInstallMarker(r);if(p(a))info({message:`Apify and Actor CLI are already fully configured! 👍`});else{if(e.platform!==`win32`){await this.symlinkToLocalBin(r);try{await this.promptAddToShell()}catch(e){error({message:e.message||`Failed to automatically handle shell integration`})}simpleLog({message:``})}await U(a,i),cliDebugPrint(`[install] install marker written to`,a),simpleLog({message:[``,t.green(`Apify and Actor CLI were installed successfully!`),``,t.gray(` Version: ${t.green(i)}`),t.gray(` Location: ${t.bold.white(tildify(R(r,`apify`)))} and ${t.bold.white(tildify(R(r,`actor`)))}`)].join(`
|
|
134
134
|
`)}),simpleLog({message:``}),success({message:`To get started, run:`}),simpleLog({message:t.white.bold(` apify --help
|
|
135
135
|
actor --help`)})}}async symlinkToLocalBin(e){let n=userHomeDir();if(cliDebugPrint(`[install -> symlinkToLocalBin] user home directory`,n),!n){cliDebugPrint(`[install -> symlinkToLocalBin] user home directory not found`),warning({message:t.gray(`User home directory not found, cannot symlink to ~/.local/bin`)});return}let r=R(n,`.local`,`bin`);await B(r,{recursive:!0});for(let n of[`apify`,`actor`,`apify-cli`]){let i=R(e,n);if(!p(i)){cliDebugPrint(`[install] file not found for symlinking`,n,i),warning({message:t.gray(`Bundle not found for symlinking: ${n}`)});continue}let a=R(r,n);await we(a).catch(()=>{}),await Ce(i,a),cliDebugPrint(`[install] symlink created for item`,n,a)}info({message:t.gray(`Symlinked apify, actor, and apify-cli to ${tildify(r)}`)})}async confirmFromTty(n){let r,i,a=`${t.green(`?`)} ${t.bold(n)} ${t.dim(`(Y/n)`)} `,writeDone=r=>{e.stdout.write(`\r\x1b[2K${t.green(`?`)} ${t.bold(n)} ${t.cyan(r)}\n`)};try{return cliDebugPrint(`[install] opening /dev/tty for raw mode`),r=g(`/dev/tty`,`r`),i=new Bt(r),e.stdout.write(a),i.setRawMode(!0),i.resume(),await new Promise(t=>{let onData=n=>{let r=n.toString();r===`y`||r===`Y`||r===`\r`||r===`
|
|
136
136
|
`?(i.removeListener(`data`,onData),writeDone(`Yes`),t(!0)):r===`n`||r===`N`?(i.removeListener(`data`,onData),writeDone(`No`),t(!1)):(r===``||r===``)&&(i.removeListener(`data`,onData),e.stdout.write(`
|
|
137
|
-
`),t(!1))};i.on(`data`,onData)})}catch(e){return cliDebugPrint(`[install] failed to open /dev/tty for raw mode`,e),!1}finally{i&&(i.setRawMode(!1),i.pause(),i.destroy())}}async promptAddToShell(){let[n,r]=await Promise.allSettled([Le(`apify`,{nothrow:!0}),Le(`actor`,{nothrow:!0})]);if(n.status===`fulfilled`&&r.status===`fulfilled`&&n.value&&r.value){cliDebugPrint(`[install -> promptAddToShell] already in PATH`,{apifyCliPath:n,actorCliPath:r}),info({message:t.gray(`Apify and Actor CLIs are already in PATH, skipping shell integration`)});return}let i=userHomeDir();cliDebugPrint(`[install -> promptAddToShell] user home directory`,i);let a=e.env.APIFY_CLI_INSTALL??R(i,`.apify`),s=e.env.FINAL_BIN_DIR??R(a,`bin`),c=e.env.PROVIDED_INSTALL_DIR??a;if(!c){warning({message:t.gray(`Install directory not found, cannot add to shell`)});return}let l=e.env.FINAL_BIN_DIR??s;simpleLog({message:``});let u=`Should the CLI handle adding itself to your shell automatically?`,f;e.env.APIFY_OPEN_TTY?f=await this.confirmFromTty(u):(cliDebugPrint(`[install] opening /dev/tty for raw mode not requested, falling back to normal flow`),f=await X({message:u,
|
|
137
|
+
`),t(!1))};i.on(`data`,onData)})}catch(e){return cliDebugPrint(`[install] failed to open /dev/tty for raw mode`,e),!1}finally{i&&(i.setRawMode(!1),i.pause(),i.destroy())}}async promptAddToShell(){let[n,r]=await Promise.allSettled([Le(`apify`,{nothrow:!0}),Le(`actor`,{nothrow:!0})]);if(n.status===`fulfilled`&&r.status===`fulfilled`&&n.value&&r.value){cliDebugPrint(`[install -> promptAddToShell] already in PATH`,{apifyCliPath:n,actorCliPath:r}),info({message:t.gray(`Apify and Actor CLIs are already in PATH, skipping shell integration`)});return}let i=userHomeDir();cliDebugPrint(`[install -> promptAddToShell] user home directory`,i);let a=e.env.APIFY_CLI_INSTALL??R(i,`.apify`),s=e.env.FINAL_BIN_DIR??R(a,`bin`),c=e.env.PROVIDED_INSTALL_DIR??a;if(!c){warning({message:t.gray(`Install directory not found, cannot add to shell`)});return}let l=e.env.FINAL_BIN_DIR??s;simpleLog({message:``});let u=`Should the CLI handle adding itself to your shell automatically?`,f;e.env.APIFY_OPEN_TTY?f=await this.confirmFromTty(u):(cliDebugPrint(`[install] opening /dev/tty for raw mode not requested, falling back to normal flow`),f=await X({message:u,defaultWhenNonInteractive:!1}));let p=detectShell(),m=shellConfigFile(i,p),h=`"${c.replaceAll(`"`,`\\"`)}"`,g=[],_=!0;switch(p){case`bash`:case`zsh`:g.push(`export APIFY_CLI_INSTALL=${h}`),g.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`);break;case`fish`:g.push(`set --export APIFY_CLI_INSTALL ${h}`),g.push(`set --export PATH ${l} $PATH`);break;default:g.push(`export APIFY_CLI_INSTALL=${h}`),g.push(`export PATH="$APIFY_CLI_INSTALL/bin:$PATH"`),f=!1,_=!1}if(simpleLog({message:``}),f&&m){let e=`${await V(m,`utf-8`).catch(e=>{if(e.code===`ENOENT`)return``;throw Error(`Failed to read config file "${tildify(m)}". Received error code: ${e.code}; ${e.message}`)})}\n\n# apify cli\n${g.join(`
|
|
138
138
|
`)}\n`;try{await B(L(m),{recursive:!0}),await U(m,e)}catch(e){throw e.code===`EACCES`?Error(`Failed to write to config file "${tildify(m)}", as the CLI does not have permission to write to it.`):Error(`Failed to write to config file "${tildify(m)}". Received error code: ${e.code}; ${e.message}`)}info({message:[t.gray(`Added "${tildify(l)}" to your PATH in ${tildify(m)}.`),t.gray(` You may need to run ${t.white.bold(`source ${tildify(m)}`)} to reload your shell.`)].join(`
|
|
139
139
|
`)});return}let v=m??`your shell config file`;if(_){let e=`echo -e '${g.join(`\\n`)}' >> "${v}" && source "${v}"`;info({message:[t.gray(`The Apify & Actor CLIs are not in your PATH. Run:`),``,t.white.bold(` ${e}`)].join(`
|
|
140
140
|
`)})}else info({message:[t.gray(`Manually add the following lines to ${v} or similar:`),...g.map(e=>t.white.bold(` ${e}`))].join(`
|
|
@@ -157,7 +157,7 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
|
|
|
157
157
|
`);_i.pushRow({Row1:v,Row2:S});let C=_i.render(2).split(`
|
|
158
158
|
`).map(e=>e.trim());C.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,C.join(`
|
|
159
159
|
`),``,_].join(`
|
|
160
|
-
`),stdout:!0})}};const vi=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Prints all datasets on your account.`;static examples=[{description:`List your datasets (most recently modified first).`,command:`apify datasets ls --desc`},{description:`List only unnamed (auto-generated) datasets.`,command:`apify datasets ls --unnamed`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-ls`;static flags={offset:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getCurrentUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i)printJsonToStdout(l);else if(l.count===0)info({message:`You don't have any Datasets on your account`,stdout:!0});else{for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);vi.pushRow({"Dataset ID":e.id,Created:q.display(e.createdAt),Items:`${e.itemCount}`,Modified:q.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:vi.render(1),stdout:!0})}}},DatasetsPushDataCommand=class extends ApifyCommand{static name=`push-items`;static enableProfileFlag=!0;static description=`Adds data items to specified dataset. Accepts single object or array of objects.`;static examples=[{description:`Push a single item as an inline JSON argument.`,command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:`Push an array of items from stdin.`,command:`cat ./items.json | apify datasets push-items my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-push-items`;static args={nameOrId:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||await readStdin();if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{static name=`rename`;static enableProfileFlag=!0;static description=`Change the dataset name or remove the name with --unname flag.`;static examples=[{description:`Rename a dataset.`,command:`apify datasets rename old-name new-name`},{description:`Remove the name from a dataset (makes it unnamed).`,command:`apify datasets rename my-dataset --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Permanently removes a dataset.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a dataset by name or ID (prompts for confirmation).`,command:`apify datasets rm my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rm`;static args={datasetNameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,
|
|
160
|
+
`),stdout:!0})}};const vi=new Q({allColumns:[`Dataset ID`,`Name`,`Items`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Dataset ID`,`Name`,`Items`,`Size`],columnAlignments:{Items:`right`}});var DatasetsLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Prints all datasets on your account.`;static examples=[{description:`List your datasets (most recently modified first).`,command:`apify datasets ls --desc`},{description:`List only unnamed (auto-generated) datasets.`,command:`apify datasets ls --unnamed`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-ls`;static flags={offset:Y.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:Y.integer({description:`Number of datasets that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists datasets that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getCurrentUserInfo(),l=await s.datasets().list({desc:e,offset:n,limit:r,unnamed:a});if(i)printJsonToStdout(l);else if(l.count===0)info({message:`You don't have any Datasets on your account`,stdout:!0});else{for(let e of l.items){let n=Reflect.get(e.stats,`s3StorageBytes`);vi.pushRow({"Dataset ID":e.id,Created:q.display(e.createdAt),Items:`${e.itemCount}`,Modified:q.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:vi.render(1),stdout:!0})}}},DatasetsPushDataCommand=class extends ApifyCommand{static name=`push-items`;static enableProfileFlag=!0;static description=`Adds data items to specified dataset. Accepts single object or array of objects.`;static examples=[{description:`Push a single item as an inline JSON argument.`,command:`apify datasets push-items my-dataset '{"url":"https://example.com"}'`},{description:`Push an array of items from stdin.`,command:`cat ./items.json | apify datasets push-items my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-push-items`;static args={nameOrId:Z.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Z.string({description:`The object or array of objects to be pushed.`})};async run(){let{nameOrId:e,item:n}=this.args,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:a}=r,s,c=n||await readStdin();if(!c){error({message:`No items were provided.`});return}try{s=JSON.parse(c.toString(`utf8`))}catch(e){error({message:`Failed to parse data as JSON string: ${e.message}`});return}if(Array.isArray(s)&&s.length===0){error({message:`No items were provided.`});return}let l=a.name?`Dataset named ${t.yellow(a.name)} (${t.gray(`ID:`)} ${t.yellow(a.id)})`:`Dataset with ID ${t.yellow(a.id)}`;try{await i.pushItems(s),success({message:`${this.pluralString(Array.isArray(s)?s.length:1,`Object`,`Objects`)} pushed to ${l} successfully.`})}catch(e){let t=e;error({message:`Failed to push items into ${l}\n ${t.message||t}`})}}},DatasetsRenameCommand=class extends ApifyCommand{static name=`rename`;static enableProfileFlag=!0;static description=`Change the dataset name or remove the name with --unname flag.`;static examples=[{description:`Rename a dataset.`,command:`apify datasets rename old-name new-name`},{description:`Remove the name from a dataset (makes it unnamed).`,command:`apify datasets rename my-dataset --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the dataset.`})};async run(){let{unname:e}=this.flags,{newName:n,nameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetDataset(await getLoggedClientOrThrow(),r);if(!i){error({message:`Dataset with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.dataset,c=s?e?`The name of the dataset with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the dataset with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the dataset with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.datasetClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename dataset with ID ${t.yellow(a)}\n ${n.message||n}`})}}},DatasetsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Permanently removes a dataset.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a dataset by name or ID (prompts for confirmation).`,command:`apify datasets rm my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-rm`;static args={datasetNameOrId:Z.string({description:`The dataset ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{datasetNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetDataset(await getLoggedClientOrThrow(),e);if(!r){error({message:`Dataset with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Dataset?`,preAnswered:n||void 0})){info({message:`Dataset deletion has been aborted.`});return}let{id:i,name:a}=r.dataset;try{await r.datasetClient.delete(),success({message:`Dataset with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete dataset with ID ${t.yellow(i)}\n ${n.message||n}`})}}},DatasetsIndexCommand=class extends ApifyCommand{static name=`datasets`;static description=`Manage Apify datasets — create, list, rename, delete, push items, and download items in various formats.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets`;static subcommands=[DatasetsCreateCommand,DatasetsGetItems,DatasetsLsCommand,DatasetsInfoCommand,DatasetsRmCommand,DatasetsRenameCommand,DatasetsPushDataCommand];async run(){this.printHelp()}};const yi=`https://apify.github.io/input-schema-editor-react/`,bi=new URL(yi).origin;var EditInputSchemaCommand=class extends ApifyCommand{static name=`edit-input-schema`;static description=`Lets you edit your input schema that would be used on the platform in a visual input schema editor.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Opens a browser-based schema editor. Requires a local display; cannot be run headlessly.`;static examples=[{description:`Edit the input schema of the Actor in the current directory.`,command:`apify edit-input-schema`},{description:`Edit a specific INPUT_SCHEMA.json file.`,command:`apify edit-input-schema ./.actor/INPUT_SCHEMA.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-edit-input-schema`;static args={path:Z.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided default platform location for input schema is used.`})};static hidden=!0;static aliases=[`eis`];async run(){let{inputSchema:e,inputSchemaPath:t}=await readInputSchema({forcePath:this.args.path,cwd:process.cwd()});if(e&&!t)throw Error(`Editing an input schema directly embedded in '${G}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
|
|
161
161
|
`}),info({message:`Editing input schema at "${t}"...`});let n=ce(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:bi,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=p(t)?_(t,{encoding:`utf-8`}):`{}
|
|
162
162
|
`,a.length>3&&(r=Vt(a).indent||r),a&&(i=a[a.length-1]===`
|
|
163
163
|
`),p(t)?info({message:`Input schema loaded from "${t}"`}):info({message:`Empty input schema initialized.`})}catch(e){let t=`Reading input schema from disk failed with: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}let s;try{s=JSON.parse(a||`{}`)}catch(e){let t=`Parsing input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t);return}n.send(s),info({message:`Input schema sent to editor.`})},"POST /api/v1/input-schema":(e,n)=>{try{info({message:`Got input schema from editor...`});let a=JSON.stringify(e,null,r);i&&(a+=`
|
|
@@ -172,17 +172,18 @@ It adds the following features:
|
|
|
172
172
|
...
|
|
173
173
|
`;static args={path:Z.string({required:!1,description:`Optional path to your scrapy project. If not provided, the current directory is used.`})};static hidden=!0;async run(){await wrapScrapyProject({projectPath:this.args.path}),info({message:`Scrapy project wrapped successfully.`})}},InitCommand=class extends ApifyCommand{static name=`init`;static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
|
|
174
174
|
If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
|
|
175
|
-
Creates the '${G}' file and the '${Kt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Kt}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd();t&&validateActorName(t);let r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=fe(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=e.includes(`.`)?e.split(`.`).pop():e}let s=sanitizeActorName(a);if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,errorMessageForStdin:`Confirmation is required to continue. Pass --yes to skip the prompt.`})))return;let c=await useActorConfig({cwd:n});if(c.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${G}', the file already exists in the current directory.`});else{if(c.isErr()){error({message:c.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=c.isOkAnd(e=>e.exists)?c.unwrap().config.name:null;if(e)t=e;else if(this.flags.yes){try{validateActorName(s)}catch{throw Error(`Cannot derive an Actor name from '${a}'. Run 'apify init <name>' to set it.`)}t=s}else t=await An({message:`Actor name:`,default:s,validate:validateActorNameForPrompt,errorMessageForStdin:`Actor name is required. Run 'apify init <name>', or pass --yes to use the current directory name.`})}let r={...qt,...c.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);this.flags.json?printJsonToStdout(r):success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static enableProfileFlag=!0;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n))error({message:`Item with key "${n}" not found in the key-value store.`});else if(!await X({message:`Are you sure you want to delete this record?`,
|
|
175
|
+
Creates the '${G}' file and the '${Kt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Kt}' directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name if not provided. To run non-interactively, pass the Actor name as a positional argument, or pass --yes to accept the default (current directory name).`;static examples=[{description:`Initialize an Actor in the current directory, prompting for a name.`,command:`apify init`},{description:`Initialize non-interactively with an explicit Actor name.`,command:`apify init my-actor`},{description:`Initialize non-interactively, accepting the default Actor name.`,command:`apify init --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-init`;static args={actorName:Z.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:Y.string({description:`Path to a Dockerfile to use for the Actor (e.g., "./Dockerfile" or "./docker/Dockerfile").`,required:!1})};async run(){let{actorName:t}=this.args,n=e.cwd();t&&validateActorName(t);let r=await useCwdProject();r.isErr()&&(error({message:r.unwrapErr().message}),e.exit(1));let i=r.unwrap();if(i.warnings?.length)for(let e of i.warnings)warning({message:e});let a=fe(n);if(i.type===1&&i.entrypoint?.path){let e=i.entrypoint.path;a=e.includes(`.`)?e.split(`.`).pop():e}let s=sanitizeActorName(a);if(i.type===2)return info({message:`The current directory looks like a Scrapy project. Using automatic project wrapping.`}),this.telemetryData.actorWrapper=`scrapy`,wrapScrapyProject({projectPath:n});if(!this.flags.yes&&i.type===3&&(warning({message:`The current directory does not look like a Node.js or Python project.`}),!await X({message:`Do you want to continue?`,errorMessageForStdin:`Confirmation is required to continue. Pass --yes to skip the prompt.`})))return;let c=await useActorConfig({cwd:n});if(c.isOkAnd(e=>e.exists&&!e.migrated))warning({message:`Skipping creation of '${G}', the file already exists in the current directory.`});else{if(c.isErr()){error({message:c.unwrapErr().message}),e.exitCode=5;return}if(!t){let e=c.isOkAnd(e=>e.exists)?c.unwrap().config.name:null;if(e)t=e;else if(this.flags.yes){try{validateActorName(s)}catch{throw Error(`Cannot derive an Actor name from '${a}'. Run 'apify init <name>' to set it.`)}t=s}else t=await An({message:`Actor name:`,default:s,validate:validateActorNameForPrompt,errorMessageForStdin:`Actor name is required. Run 'apify init <name>', or pass --yes to use the current directory name.`})}let r={...qt,...c.unwrap().config,name:t};this.flags.dockerfile&&(r.dockerfile=this.flags.dockerfile),await setLocalConfig(r,n)}await setLocalEnv(n),await createPrefilledInputFileFromInputSchema(n),success({message:`The Actor has been initialized in the current directory.`})}},KeyValueStoresCreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates a new key-value store on your account.`;static examples=[{description:`Create an unnamed key-value store.`,command:`apify key-value-stores create`},{description:`Create a named key-value store.`,command:`apify key-value-stores create my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-create`;static args={"key-value store name":Z.string({description:`Optional name for the key-value store.`,required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetKeyValueStore(n,e)){error({message:`Cannot create a key-value store with the same name!`});return}let r=await n.keyValueStores().getOrCreate(e);this.flags.json?printJsonToStdout(r):success({message:`Key-value store with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}},KeyValueStoresDeleteValueCommand=class extends ApifyCommand{static name=`delete-value`;static enableProfileFlag=!0;static description=`Delete a value from a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting the record. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a single record by key.`,command:`apify key-value-stores delete-value <storeId> OUTPUT`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-delete-value`;static args={"store id":Z.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};static flags={...YesFlag()};async run(){let{storeId:e,itemKey:n}=this.args,{yes:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;if(!await a.getRecord(n))error({message:`Item with key "${n}" not found in the key-value store.`});else if(!await X({message:`Are you sure you want to delete this record?`,preAnswered:r||void 0}))info({message:`Key-value store record deletion aborted.`,stdout:!0});else try{await a.deleteRecord(n),info({message:`Record with key "${t.yellow(n)}" deleted from the key-value store.`,stdout:!0})}catch(e){let t=e;error({message:`Failed to delete record with key "${n}" from the key-value store.\n ${t.message||t}`})}}},KeyValueStoresGetValueCommand=class extends ApifyCommand{static name=`get-value`;static enableProfileFlag=!0;static description=`Retrieves stored value for specified key. Use --only-content-type to check MIME type.`;static examples=[{description:`Read a record value and print it to stdout.`,command:`apify key-value-stores get-value <storeId> INPUT`},{description:`Print only the record content-type.`,command:`apify key-value-stores get-value <storeId> INPUT --only-content-type`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-get-value`;static flags={"only-content-type":Y.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Z.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:t,itemKey:n}=this.args,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),t);if(!r){error({message:`Key-value store with ID "${t}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.getRecord(n,{stream:!0});if(!a)error({message:`Item with key "${n}" not found in the key-value store.`});else if(simpleLog({message:a.contentType??`application/octet-stream`}),e)a.value.destroy();else if(a.contentType?.includes(`application/json`)){let{value:e}=a,t=[];for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();try{let e=JSON.parse(n);simpleLog({message:JSON.stringify(e,null,2),stdout:!0})}catch{simpleLog({message:n,stdout:!0})}}else a.value.pipe(process.stdout)}};const wi=new Q({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var KeyValueStoresInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Shows information about a key-value store.`;static examples=[{description:`Show metadata about a key-value store.`,command:`apify key-value-stores info <storeId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-info`;static args={storeId:Z.string({description:`The key-value store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetKeyValueStore(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:i}=r,[a,s,c]=await Promise.all([n.user(i.userId).get().then(e=>e),i.actId?n.actor(i.actId).get():Promise.resolve(void 0),i.actRunId?n.run(i.actRunId).get():Promise.resolve(void 0)]),l;if(c?.actorTaskId&&(l=await n.task(c.actorTaskId).get().catch(()=>void 0)),this.flags.json){printJsonToStdout({...i,user:a,actor:s||null,run:c||null,task:l||null});return}let u=i.stats?.storageBytes||0,f=i.stats?.readCount||0,p=i.stats?.writeCount||0,m=i.stats?.deleteCount||0,h=i.stats?.listCount||0,g=`Operations: ${[`${t.bold(f.toLocaleString(`en-US`))} ${t.gray(this.pluralString(f,`read`,`reads`))}`,`${t.bold(p.toLocaleString(`en-US`))} ${t.gray(this.pluralString(p,`write`,`writes`))}`,`${t.bold(m.toLocaleString(`en-US`))} ${t.gray(this.pluralString(m,`delete`,`deletes`))}`,`${t.bold(h.toLocaleString(`en-US`))} ${t.gray(this.pluralString(h,`list`,`lists`))}`].join(` / `)}`;if(a.plan){let e=getUserPlanPricing(a.plan);if(e){let n=e.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(u/1e3**3),r=n*24*30,i=r>1?`$${r.toFixed(2)}`:`$${n.toFixed(3)}`;g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else g+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`$unknown per month`)}`;let _=[`Store ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(q.display(i.createdAt))}`,`Modified: ${t.bold(q.display(i.modifiedAt))}`].join(`
|
|
176
176
|
`),v=t.bold(`—`);i.actRunId&&(v=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let y=t.bold(`—`);s&&(y=t.blue(s.title||s.name));let b=t.bold(`—`);l&&(b=t.blue(l.title||l.name));let x=[`Run: ${v}`,`Actor: ${y}`,`Task: ${b}`].join(`
|
|
177
177
|
`);wi.pushRow({Row1:_,Row2:x});let S=wi.render(2).split(`
|
|
178
178
|
`).map(e=>e.trim());S.shift(),simpleLog({message:[`${t.bold(i.name||t.italic(`Unnamed`))}`,`${t.gray(i.name?`${a.username}/${i.name}`:i.id)} ${t.gray(`Owned by`)} ${t.blue(a.username)}`,``,S.join(`
|
|
179
179
|
`),``,g].join(`
|
|
180
|
-
`),stdout:!0})}};const Ti=new Q({allColumns:[`Key`,`Size`],mandatoryColumns:[`Key`,`Size`]});var KeyValueStoresKeysCommand=class extends ApifyCommand{static name=`keys`;static enableProfileFlag=!0;static description=`Lists all keys in a key-value store.`;static examples=[{description:`List the first 20 keys in a key-value store.`,command:`apify key-value-stores keys <storeId>`},{description:`Paginate keys past an exclusive start key.`,command:`apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys`;static flags={limit:Y.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":Y.string({description:`The key to start the list from.`})};static args={storeId:Z.string({description:`The key-value store ID to list keys for.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.listKeys({limit:t,exclusiveStartKey:n});if(this.flags.json)printJsonToStdout(a);else{for(let e of a.items)Ti.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Ti.render(1),stdout:!0})}}};const Ei=new Q({allColumns:[`Store ID`,`Name`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Store ID`,`Name`,`Size`]});var KeyValueStoresLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Lists all key-value stores on your account.`;static examples=[{description:`List your key-value stores.`,command:`apify key-value-stores ls`},{description:`List the next page of stores, sorted descending.`,command:`apify key-value-stores ls --limit 50 --offset 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls`;static flags={offset:Y.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:Y.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists key-value stores that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getCurrentUserInfo(),l=await s.keyValueStores().list({desc:e,offset:n,limit:r,unnamed:a});if(i)printJsonToStdout(l);else if(l.count===0)info({message:`You don't have any key-value stores on your account`,stdout:!0});else{for(let e of l.items){let n=Reflect.get(e,`stats`).s3StorageBytes;Ei.pushRow({"Store ID":e.id,Created:q.display(e.createdAt),Modified:q.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:Ei.render(1),stdout:!0})}}},KeyValueStoresRenameCommand=class extends ApifyCommand{static name=`rename`;static enableProfileFlag=!0;static description=`Renames a key-value store, or removes its unique name.`;static examples=[{description:`Rename a key-value store.`,command:`apify key-value-stores rename old-name new-name`},{description:`Remove the name from a key-value store.`,command:`apify key-value-stores rename my-store --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the key-value store.`})};async run(){let{unname:e}=this.flags,{newName:n,keyValueStoreNameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),r);if(!i){error({message:`Key-value store with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.keyValueStore,c=s?e?`The name of the key-value store with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the key-value store with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the key-value store with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.keyValueStoreClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename key-value store with ID ${t.yellow(a)}\n ${n.message||n}`})}}},KeyValueStoresRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Permanently removes a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a key-value store (prompts for confirmation).`,command:`apify key-value-stores rm my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm`;static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Key-value store?`,
|
|
180
|
+
`),stdout:!0})}};const Ti=new Q({allColumns:[`Key`,`Size`],mandatoryColumns:[`Key`,`Size`]});var KeyValueStoresKeysCommand=class extends ApifyCommand{static name=`keys`;static enableProfileFlag=!0;static description=`Lists all keys in a key-value store.`;static examples=[{description:`List the first 20 keys in a key-value store.`,command:`apify key-value-stores keys <storeId>`},{description:`Paginate keys past an exclusive start key.`,command:`apify key-value-stores keys <storeId> --exclusive-start-key last-seen-key --limit 100`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-keys`;static flags={limit:Y.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":Y.string({description:`The key to start the list from.`})};static args={storeId:Z.string({description:`The key-value store ID to list keys for.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:t,exclusiveStartKey:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=r,a=await i.listKeys({limit:t,exclusiveStartKey:n});if(this.flags.json)printJsonToStdout(a);else{for(let e of a.items)Ti.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:Ti.render(1),stdout:!0})}}};const Ei=new Q({allColumns:[`Store ID`,`Name`,`Size`,`Created`,`Modified`],mandatoryColumns:[`Store ID`,`Name`,`Size`]});var KeyValueStoresLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Lists all key-value stores on your account.`;static examples=[{description:`List your key-value stores.`,command:`apify key-value-stores ls`},{description:`List the next page of stores, sorted descending.`,command:`apify key-value-stores ls --limit 50 --offset 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-ls`;static flags={offset:Y.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:Y.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:Y.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:Y.boolean({description:`Lists key-value stores that don't have a name set.`,default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:n,limit:r,json:i,unnamed:a}=this.flags,s=await getLoggedClientOrThrow(),c=await getCurrentUserInfo(),l=await s.keyValueStores().list({desc:e,offset:n,limit:r,unnamed:a});if(i)printJsonToStdout(l);else if(l.count===0)info({message:`You don't have any key-value stores on your account`,stdout:!0});else{for(let e of l.items){let n=Reflect.get(e,`stats`).s3StorageBytes;Ei.pushRow({"Store ID":e.id,Created:q.display(e.createdAt),Modified:q.display(e.modifiedAt),Name:e.name?`${c.username}/${e.name}`:``,Size:typeof n==`number`?prettyPrintBytes({bytes:n,shortBytes:!0,colorFunc:t.gray,precision:0}):t.gray(`N/A`)})}simpleLog({message:Ei.render(1),stdout:!0})}}},KeyValueStoresRenameCommand=class extends ApifyCommand{static name=`rename`;static enableProfileFlag=!0;static description=`Renames a key-value store, or removes its unique name.`;static examples=[{description:`Rename a key-value store.`,command:`apify key-value-stores rename old-name new-name`},{description:`Remove the name from a key-value store.`,command:`apify key-value-stores rename my-store --unname`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rename`;static flags={unname:Y.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Z.string({description:`The new name for the key-value store.`})};async run(){let{unname:e}=this.flags,{newName:n,keyValueStoreNameOrId:r}=this.args;if(!n&&!e){error({message:`You must provide either a new name or the --unname flag.`});return}if(n&&e){error({message:`You cannot provide a new name and the --unname flag.`});return}let i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),r);if(!i){error({message:`Key-value store with ID or name "${r}" not found.`});return}let{id:a,name:s}=i.keyValueStore,c=s?e?`The name of the key-value store with ID ${t.yellow(a)} has been removed (was ${t.yellow(s)} previously).`:`The name of the key-value store with ID ${t.yellow(a)} was changed from ${t.yellow(s)} to ${t.yellow(n)}.`:`The name of the key-value store with ID ${t.yellow(a)} has been set to: ${t.yellow(n)}`;try{await i.keyValueStoreClient.update({name:e?null:n}),success({message:c,stdout:!0})}catch(e){let n=e;error({message:`Failed to rename key-value store with ID ${t.yellow(a)}\n ${n.message||n}`})}}},KeyValueStoresRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Permanently removes a key-value store.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a key-value store (prompts for confirmation).`,command:`apify key-value-stores rm my-store`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-rm`;static args={keyValueStoreNameOrId:Z.string({description:`The key-value store ID or name to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{keyValueStoreNameOrId:e}=this.args,{yes:n}=this.flags,r=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await X({message:`Are you sure you want to delete this Key-value store?`,preAnswered:n||void 0})){info({message:`Key-value store deletion has been aborted.`});return}let{id:i,name:a}=r.keyValueStore;try{await r.keyValueStoreClient.delete(),success({message:`Key-value store with ID ${t.yellow(i)}${a?` (called ${t.yellow(a)})`:``} has been deleted.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to delete key-value store with ID ${t.yellow(i)}\n ${n.message||n}`})}}},KeyValueStoresSetValueCommand=class extends ApifyCommand{static name=`set-value`;static enableProfileFlag=!0;static description=`Stores value with specified key. Set content-type with --content-type flag.`;static examples=[{description:`Store a JSON value under a key.`,command:`apify key-value-stores set-value <storeId> OUTPUT '{"status":"done"}'`},{description:`Store a plain-text file read from stdin.`,command:`cat ./report.txt | apify key-value-stores set-value <storeId> REPORT --content-type text/plain`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores-set-value`;static flags={"content-type":Y.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Z.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Z.string({description:`The key of the item in the key-value store.`,required:!0}),value:Z.string({description:`The value to set.`})};async run(){let{storeId:e,itemKey:t,value:n}=this.args,{contentType:r}=this.flags,i=await tryToGetKeyValueStore(await getLoggedClientOrThrow(),e);if(!i){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=i;try{await a.setRecord({key:t,value:n||process.stdin,contentType:r}),success({message:`Value with key "${t}" set in the key-value store.`,stdout:!0})}catch(e){let n=e;error({message:`Failed to set value with key "${t}" in the key-value store.\n ${n.message||n}`})}}},KeyValueStoresIndexCommand=class extends ApifyCommand{static name=`key-value-stores`;static description=`Manage Apify key-value stores — create, list, rename, delete stores, and get/set/delete individual records.
|
|
181
181
|
|
|
182
|
-
Alias: kvs.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores`;static hiddenAliases=[`kvs`];static subcommands=[KeyValueStoresCreateCommand,KeyValueStoresDeleteValueCommand,KeyValueStoresGetValueCommand,KeyValueStoresInfoCommand,KeyValueStoresKeysCommand,KeyValueStoresLsCommand,KeyValueStoresRenameCommand,KeyValueStoresRmCommand,KeyValueStoresSetValueCommand];async run(){this.printHelp()}},LoginCommand=class extends AuthLoginCommand{static name=`login`},LogoutCommand=class extends AuthLogoutCommand{static name=`logout`};async function confirmOverwrite({filePath:e,entryKey:t,yes:n}){return X({message:`A server entry named '${t}' already exists in ${tildify(e)}. Overwrite it?`,default:!1,
|
|
182
|
+
Alias: kvs.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-key-value-stores`;static hiddenAliases=[`kvs`];static subcommands=[KeyValueStoresCreateCommand,KeyValueStoresDeleteValueCommand,KeyValueStoresGetValueCommand,KeyValueStoresInfoCommand,KeyValueStoresKeysCommand,KeyValueStoresLsCommand,KeyValueStoresRenameCommand,KeyValueStoresRmCommand,KeyValueStoresSetValueCommand];async run(){this.printHelp()}},LoginCommand=class extends AuthLoginCommand{static name=`login`},LogoutCommand=class extends AuthLogoutCommand{static name=`logout`};async function confirmOverwrite({filePath:e,entryKey:t,yes:n}){return X({message:`A server entry named '${t}' already exists in ${tildify(e)}. Overwrite it?`,default:!1,preAnswered:n||void 0,errorMessageForStdin:`An '${t}' entry already exists in ${tildify(e)}. Re-run with --yes to overwrite.`})}async function mergeServerEntry({filePath:t,topLevelKey:n,entryKey:r,serverEntry:i,yes:a}){let s=p(t)?await V(t,`utf-8`):``,c=s.trim(),l;if(c){let e;try{e=Ot.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
|
|
183
183
|
`)[0]:`invalid JSON`;throw Error(`Cannot install: ${tildify(t)} is not valid JSON (${n}). Fix the file manually and re-run.`)}if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Cannot install: ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let c=e[n];if(c!=null&&(typeof c!=`object`||Array.isArray(c)))throw Error(`Cannot install: '${n}' in ${tildify(t)} is not a JSON object. Fix the file manually and re-run.`);let u=c??{};if(Object.prototype.hasOwnProperty.call(u,r)&&!await confirmOverwrite({filePath:t,entryKey:r,yes:a}))return simpleLog({message:`No changes written.`}),!1;u[r]=i,e[n]=u,l=Ot.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Ot.stringify(e,{mode:`json`,indent:2})}\n`}await B(L(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await U(u,l,`utf-8`),await xe(u,t)}catch(e){throw await Se(u,{force:!0}),e}return!0}function buildMcpUrl(e,t){if(!t)return e;let n=t.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`);if(!n)return e;let r=new URL(e);return r.searchParams.set(`tools`,n),r.toString()}function maskToken(e){return e.length<=14?`***`:`${e.slice(0,10)}...${e.slice(-4)}`}function maskSecret(e,t){return t?e.split(t).join(maskToken(t)):e}const Di=`apify`,bearer=e=>({Authorization:`Bearer ${e}`});function printResult(e){success({message:`Apify MCP server configured for ${e.clientLabel}.`});let n=[``,` ${t.yellow(`Server URL:`)} ${e.serverUrl}`,` ${t.yellow(`Auth:`)} ${e.authDescription}`];e.configPath&&n.push(` ${t.yellow(`Config:`)} ${tildify(e.configPath)}`),e.nextSteps&&n.push(``,e.nextSteps),simpleLog({message:n.join(`
|
|
184
184
|
`)})}function isExecaError(e){return typeof e==`object`&&!!e&&`shortMessage`in e&&`command`in e}function describeExecaError(e,t){return isExecaError(e)?e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage??e.message:`${t} exited with code ${e.exitCode}`:e instanceof Error?e.message:String(e)}async function runCliInstall({binary:t,clientLabel:n,token:r,args:i,maskedCommand:a,missingMessage:s}){if(!await Le(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await Pe(t,i,{stdio:[`ignore`,`ignore`,`pipe`]})}catch(i){let a=isExecaError(i)?String(i.stderr??``).trim():``;return error({message:maskSecret(`Failed to add the MCP server via ${n}: ${a?`${describeExecaError(i,t)}\n${a}`:describeExecaError(i,t)}`,r)}),e.exitCode=1,!1}return!0}function fileClient({label:t,segments:n,entry:r}){return async({url:i,token:a,yes:s})=>{let c=userHomeDir();if(!c){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let l=R(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:Di,serverEntry:r(i,a),yes:s})&&printResult({clientLabel:t,serverUrl:i,authDescription:`Bearer ${maskToken(a)}`,configPath:l})}}const claudeCodeHandler=async({url:e,token:t})=>{let command=t=>`claude mcp add --transport http --scope user ${Di} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,Di,e,`--header`,`Authorization: Bearer ${t}`],maskedCommand:command(maskToken(t)),missingMessage:`The 'claude' CLI was not found on PATH. Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) and re-run, or add the server manually:\n\n ${command(`<your-token>`)}`})&&printResult({clientLabel:`Claude Code`,serverUrl:e,authDescription:`Bearer ${maskToken(t)} (stored by Claude Code)`})};function vscodeHandler(e,t){return async({url:n,token:r})=>{let serverJson=e=>JSON.stringify({name:Di,type:`http`,url:n,headers:{Authorization:e}});await runCliInstall({binary:e,clientLabel:t,token:r,args:[`--add-mcp`,serverJson(`Bearer ${r}`)],maskedCommand:`${e} --add-mcp '${serverJson(`Bearer ${maskToken(r)}`)}'`,missingMessage:`The '${e}' CLI was not found on PATH. Install ${t} and re-run, or add the server manually:\n\n ${e} --add-mcp '${serverJson(`Bearer <your-token>`)}'`})&&printResult({clientLabel:t,serverUrl:n,authDescription:`Bearer ${maskToken(r)} (stored by ${t})`})}}const codexHandler=async({url:n})=>{let r=userHomeDir();if(!r){error({message:`User home directory could not be determined. Set the HOME environment variable and re-run.`}),e.exitCode=5;return}let i=R(r,`.codex`,`config.toml`),a=[`mcp`,`add`,Di,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${Di}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
|
|
185
|
-
`);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},Oi={"claude-code":claudeCodeHandler,cursor:fileClient({label:`Cursor`,segments:[`.cursor`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t)})}),vscode:vscodeHandler(`code`,`VS Code`),"vscode-insiders":vscodeHandler(`code-insiders`,`VS Code Insiders`),codex:codexHandler,kiro:fileClient({label:`Kiro`,segments:[`.kiro`,`settings`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t),disabled:!1,autoApprove:[]})}),antigravity:fileClient({label:`Antigravity`,segments:[`.gemini`,`antigravity`,`mcp_config.json`],entry:(e,t)=>({serverUrl:e,headers:bearer(t)})})},ki=Object.keys(Oi);function isSupportedClient(e){return e in Oi}const Ai=/* @__PURE__ */ new Set([`codex`]);function clientNeedsToken(e){return!Ai.has(e)}function getClientHandler(e){return Oi[e]}
|
|
185
|
+
`);await runCliInstall({binary:`codex`,clientLabel:`Codex CLI`,token:``,args:a,maskedCommand:`codex ${a.join(` `)}`,missingMessage:`The 'codex' CLI was not found on PATH. Install Codex (https://developers.openai.com/codex) and re-run, or add this entry manually to ${tildify(i)}:\n\n${s}\n\nThen, before launching codex, export your Apify token in the same shell:\n\n export APIFY_TOKEN=<your-token>`})&&printResult({clientLabel:`Codex CLI`,serverUrl:n,authDescription:`Bearer token from APIFY_TOKEN environment variable`,configPath:i,nextSteps:` ${t.yellow(`Next:`)} Codex reads APIFY_TOKEN from the environment. Before launching codex, run:\n\n export APIFY_TOKEN=<your-token>`})},Oi={"claude-code":claudeCodeHandler,cursor:fileClient({label:`Cursor`,segments:[`.cursor`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t)})}),vscode:vscodeHandler(`code`,`VS Code`),"vscode-insiders":vscodeHandler(`code-insiders`,`VS Code Insiders`),codex:codexHandler,kiro:fileClient({label:`Kiro`,segments:[`.kiro`,`settings`,`mcp.json`],entry:(e,t)=>({url:e,headers:bearer(t),disabled:!1,autoApprove:[]})}),antigravity:fileClient({label:`Antigravity`,segments:[`.gemini`,`antigravity`,`mcp_config.json`],entry:(e,t)=>({serverUrl:e,headers:bearer(t)})})},ki=Object.keys(Oi);function isSupportedClient(e){return e in Oi}const Ai=/* @__PURE__ */ new Set([`codex`]);function clientNeedsToken(e){return!Ai.has(e)}function getClientHandler(e){return Oi[e]}const ji=6e4,Mi=60*ji,Ni=24*Mi;function plural(e,t){return`${e} ${e===1?t:`${t}s`}`}function describeExpiry(e){return e<=0?`has already expired`:e<ji?`expires in under a minute`:e<Mi?`expires in about ${plural(Math.round(e/ji),`minute`)}`:e<Ni?`expires in about ${plural(Math.round(e/Mi),`hour`)}`:`expires in about ${plural(Math.round(e/Ni),`day`)}`}async function confirmExpiringToken(t,n){if(!t.profile)return!0;let{profile:r}=lookUpProfile(t.profile.id);if(r?.authMethod!==`oauth2`||!r.expiresAt)return!0;let i=Date.parse(r.expiresAt)-Date.now();if(!Number.isFinite(i)||i>864e5)return!0;let a=`You're logged in through your Apify account, and that login's API token ${describeExpiry(i)}. The MCP client reads the token from its config file and can't refresh it, so the server stops working once the token expires.
|
|
186
|
+
Pass --token with an API token from Apify Console (${getConsoleIntegrationsUrl({id:t.profile.id,organizationOwnerUserId:r.organizationOwnerUserId})}) to configure a client that keeps working.`;if(n)return warning({message:a}),!0;let{isTTY:s}=await useStdin();if(_e||!s)throw e.exitCode=5,Error(`${a}\nRe-run with --yes to write the expiring token anyway.`);return warning({message:a}),X({message:`Write the expiring token to the client config anyway?`,default:!1})}var MCPInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Configure a local MCP client to use the Apify MCP server. Writes or merges a server entry named 'apify' into the client's config file, or runs the client's own 'mcp add' command when available.`;static group=`MCP`;static interactive=!0;static interactiveNote=`Prompts before overwriting an existing JSON config entry (cursor, kiro, antigravity), and before embedding a token that expires within a day. Pass --yes to confirm without prompting. For clients delegated to their own CLI (claude-code, vscode, vscode-insiders, codex), overwrite behavior is controlled by that CLI.`;static examples=[{description:`Add Apify to Claude Code using the stored API token.`,command:`apify mcp install claude-code`},{description:`Add Apify to Cursor.`,command:`apify mcp install cursor`},{description:`Add only the 'search-actors' tool and the 'apify/rag-web-browser' Actor to VS Code.`,command:`apify mcp install vscode --tools search-actors,apify/rag-web-browser`},{description:`Add Apify to Codex CLI with an explicit token (non-interactive).`,command:`apify mcp install codex --token apify_api_xxxxx --yes`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp-install`;static args={client:Z.string({required:!0,description:`Target MCP client. One of: ${ki.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry, and accept a token that's about to expire, without prompting.`),token:Y.string({char:`t`,description:`Apify API token to embed in the config. Defaults to APIFY_TOKEN, then the token from 'apify login'. A token from an OAuth 'apify login' expires after about an hour, so pass a long-lived one from Apify Console.`}),url:Y.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:Y.string({description:`Comma-separated tool IDs or Actor full names to expose. Forwarded as a '?tools=' query parameter.`})};async run(){let{client:t}=this.args,{token:n,url:r,tools:i,yes:a}=this.flags;if(!isSupportedClient(t)){error({message:`Unknown MCP client '${t}'. Supported clients: ${ki.join(`, `)}.`}),e.exitCode=5;return}let s=n??``;if(clientNeedsToken(t)&&!n){let t=await resolveAuth();if(!t){error({message:`You are not logged in to Apify. Run 'apify login' first, or pass --token <api-token>.`}),e.exitCode=1;return}if(!await confirmExpiringToken(t,a)){simpleLog({message:`No changes written.`});return}s=t.token}await getClientHandler(t)({url:buildMcpUrl(r,i),token:s,yes:a})}},MCPIndexCommand=class extends ApifyCommand{static name=`mcp`;static description=`Configure the Apify MCP server in your AI client: Claude Code, Cursor, VS Code, Codex CLI, Kiro, or Antigravity.`;static group=`MCP`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-mcp`;static subcommands=[MCPInstallCommand];async run(){this.printHelp()}},TopLevelPullCommand=class extends ActorsPullCommand{static name=`pull`},ToplevelPushCommand=class extends ActorsPushCommand{static name=`push`},RequestQueuesIndexCommand=class extends ApifyCommand{static name=`request-queues`;static description=`Manage Apify request queues. No subcommands are available yet.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-request-queues`;async run(){this.printHelp()}};const jsScript=e=>`
|
|
186
187
|
(async () => {
|
|
187
188
|
const [nodeModule, process, path, fs] = await Promise.all([
|
|
188
189
|
import('node:module'),
|
|
@@ -220,25 +221,25 @@ try:
|
|
|
220
221
|
print(${e}.__version__)
|
|
221
222
|
except:
|
|
222
223
|
print('n/a')
|
|
223
|
-
`,
|
|
224
|
+
`,Pi={node(e){return[`-e`,`"${jsScript(e)}"`]},deno(e){return[`eval`,`"${jsScript(e)}"`]},bun(e){return[`--eval`,`"${jsScript(e)}"`]},python(e){return[`-c`,`"${pyScript(e)}"`]}};async function useModuleVersion({moduleName:t,project:n}){if(!n.runtime)return cliDebugPrint(`useModuleVersion`,{status:`no_runtime_found`,project:n,moduleName:t}),W;let r;if(n.type===0)r=n.runtime.runtimeShorthand||`node`;else if(n.type===1||n.type===2)r=`python`;else return cliDebugPrint(`useModuleVersion`,{status:`unsupported_project_type`,project:n,moduleName:t}),W;let i=Pi[r]?.(t);if(!i)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:n,moduleName:t}),W;try{let r=await Pe(n.runtime.executablePath,i,{cwd:e.cwd(),shell:!0,windowsHide:!0,verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0});return r.stdout.trim()===`n/a`?(cliDebugPrint(`useModuleVersion`,{status:`no_version_found`,project:n,moduleName:t}),W):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:n,moduleName:t,version:r.stdout.trim()}),Ne(r.stdout.trim()))}catch(e){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:n,moduleName:t,error:e}),W}}const writeInputRecord=async(e,t,n)=>writeKvsRecord({storePath:e,key:t,fileName:`${t}.json`,contentType:`application/json; charset=utf-8`,body:JSON.stringify(n,null,2)}),Fi=27e5;async function resolveTokenForLocalRun(e){let t=e?.profile?.id;if(!t||lookUpProfile(t).profile?.authMethod!==`oauth2`)return e?.token;let n=await getAccessToken(t,{minRemainingMs:Fi}),r=Date.parse(lookUpProfile(t).profile?.expiresAt??``)-Date.now();return Number.isFinite(r)&&r<Fi&&warning({message:`Your login session token expires in about ${Math.max(0,Math.round(r/6e4))} minutes and could not be refreshed; a local run longer than that loses Apify API access. For long runs, set the APIFY_TOKEN environment variable to an API token from Apify Console.`}),n}var RunCommand=class extends ApifyCommand{static name=`run`;static enableProfileFlag=!0;static description=`Executes Actor locally with simulated Apify environment variables.
|
|
224
225
|
Stores data in local '${Kt}' directory.\n\nNOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static group=`Local Actor Development`;static examples=[{description:`Run the Actor in the current directory with the stored input.`,command:`apify run`},{description:`Run and purge the default storage first (dataset, request queue, key-value store).`,command:`apify run --purge`},{description:`Run with inline JSON input (overrides the stored INPUT).`,command:`apify run --input '{"startUrls":[{"url":"https://example.com"}]}'`},{description:`Run with input from a file.`,command:`apify run --input-file ./input.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-run`;static flags={purge:Y.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
|
|
225
226
|
For crawlee projects, this is the default behavior, and the flag is optional.
|
|
226
227
|
Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:Y.boolean({description:`Whether to keep the default request queue, dataset and key-value store before the run starts.`,required:!1,default:!1,exclusive:[`purge`]}),entrypoint:Y.string({description:[`Optional entrypoint for running with injected environment variables.`,`
|
|
227
228
|
`,`For Python, it is the module name, or a path to a file.`,`
|
|
228
|
-
`,`For Node.js, it is the npm script name, or a path to a JS/MJS file.`,`You can also pass in a directory name, provided that directory contains an "index.js" file.`].join(` `),required:!1}),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a file with
|
|
229
|
+
`,`For Node.js, it is the npm script name, or a path to a JS/MJS file.`,`You can also pass in a directory name, provided that directory contains an "index.js" file.`].join(` `),required:!1}),input:Y.string({char:`i`,description:`Optional JSON input to be given to the Actor.`,required:!1,stdin:2,exclusive:[`input-file`]}),"input-file":Y.string({aliases:[`if`],description:"Optional path to a JSON file with input for the Actor. To read from standard input and wait until all input arrives, use `-`. Without this flag or `--input`, the CLI still reads standard input, but stops waiting if input is slow to start or pauses.",required:!1,stdin:2,exclusive:[`input`]}),"allow-missing-secrets":Y.boolean({description:`Allow the command to continue even when secret values are not found in the local secrets storage.`,required:!1,default:!1})};async run(){let t=e.cwd(),n,r=await resolveAuth().catch(e=>{if(!(e instanceof OAuthSessionError))throw e;n=e.message}),i=await resolveTokenForLocalRun(r),{proxy:a,id:s}=await getCurrentUserInfo().catch(e=>(cliDebugPrint(`[run] could not resolve the account behind the token`,{error:e}),{})),c=await useActorConfig({cwd:t});if(c.isErr()){let{message:t,cause:n}=c.unwrapErr();error({message:`${t}${n?`\n ${n.message}`:``}`}),e.exitCode=5;return}let{config:l}=c.unwrap(),u=getLocalStorageDir(),f=resolveInputKey(),m=await useCwdProject({cwd:t});if(m.isErr()){error({message:m.unwrapErr().message}),e.exitCode=5;return}let h=m.unwrap(),{type:g,entrypoint:_,runtime:v}=h;if(h.warnings?.length)for(let e of h.warnings)warning({message:e});if(g===3)throw Error(`Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.`);if(!v){switch(g){case 0:error({message:`No Node.js detected! Please install Node.js ${Zt} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:error({message:`No Python detected! Please install Python ${en} (or higher) to be able to run Python Actors locally.`});break;default:error({message:`No runtime detected! Make sure you have Python ${en} (or higher) or Node.js ${Zt} (or higher) installed.`})}return}let y,x;if(this.flags.entrypoint){x=this.flags.entrypoint;let e=R(t,this.flags.entrypoint),n=await H(e).catch(()=>null);y=n?.isDirectory()?1:n?.isFile()?0:2}else if(_?.script)y=2,x=_.script;else if(_?.path)y=g===0?0:1,x=_.path;else{error({message:`No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint.`});return}let S=z(t,`apify_storage`),C=z(t,u);p(S)&&!p(C)&&(b(S,C),warning({message:`The legacy 'apify_storage' directory was renamed to '${u}' to align it with Apify SDK v3. Contents were left intact.`}));let w=await useModuleVersion({moduleName:`crawlee`,project:h}),T=`0`;this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(T=`1`,w.isNone()&&(await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(f),purgeDefaultDataset()]),info({message:`All default local stores were purged.`}))),this.flags.purge||!await checkIfStorageIsEmpty(f)&&!this.flags.resurrect&&warning({message:`The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory.`});let E=await getInputOverride(t,this.flags.input,this.flags.inputFile);if(E===!1)return;let D=await this.validateAndStoreInput(E,f),O=f;D&&`tempInputKey`in D&&(this.flags.purge&&w.isSome()&&await Promise.all([purgeDefaultQueue(),purgeDefaultKeyValueStore(f,D.tempInputKey),purgeDefaultDataset()]),T=`0`,O=D.tempInputKey);let k={[F.LOCAL_STORAGE_DIR]:u,CRAWLEE_STORAGE_DIR:u,CRAWLEE_PURGE_ON_START:T,[j.INPUT_KEY]:O,[F.INPUT_KEY]:O,CRAWLEE_INPUT_KEY:O};if(a&&a.password&&(k[F.PROXY_PASSWORD]=a.password),s&&(k[F.USER_ID]=s),i&&(k[F.TOKEN]=i),l.environmentVariables){let e=replaceSecretsValue(l.environmentVariables,void 0,{allowMissing:this.flags.allowMissingSecrets});Object.assign(k,e)}let A={...e.env,...k};r||warning({message:n??`You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.`});try{switch(g){case 0:{let e=Be(Zt);if(isNodeVersionSupported(v.version)?A.NODE_OPTIONS=A.NODE_OPTIONS?`${A.NODE_OPTIONS} --max-http-header-size=80000`:`--max-http-header-size=80000`:warning({message:`You are running Node.js version ${v.version}, which is no longer supported. Please upgrade to Node.js version ${e} or later.`}),y===0||y===1)await execWithLog({cmd:v.executablePath,args:[x],opts:{env:A,cwd:t},forwardSignals:Yt});else{let e=await V(R(t,`package.json`),`utf8`).catch(()=>`{}`),n=JSON.parse(e);if(!n.scripts)throw Error(`No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!n.scripts[x])throw Error(`The script "${x}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!v.pmPath)throw Error(`No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.`);await execWithLog({cmd:v.pmPath,args:[`run`,x],opts:{env:A,cwd:t},overrideCommand:v.pmName,forwardSignals:Yt})}break}case 1:case 2:if(!isPythonVersionSupported(v.version)){error({message:`Python Actors require Python ${en} or higher, but you have Python ${v.version}!`}),error({message:`Please install Python ${en} or higher to be able to run Python Actors locally.`});return}y===1?await execWithLog({cmd:v.executablePath,args:[`-m`,x],opts:{env:A,cwd:t},forwardSignals:Yt}):await execWithLog({cmd:v.executablePath,args:[x],opts:{env:A,cwd:t},forwardSignals:Yt});break;default:error({message:`Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues`})}}catch(t){e.exitCode=t.exitCode??1}finally{if(D){if(`tempInputKey`in D)await deleteKvsRecord(D.tempInputFilePath,D.tempInputKey);else if(D.existingInput){let e=await H(D.inputFilePath);if(Math.trunc(e.mtimeMs)-D.writtenAt>=5){warning({message:`The "${D.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await U(D.inputFilePath,D.existingInput.body)}else await deleteKvsRecord(D.inputFilePath,D.inputKey)}}}async validateAndStoreInput(t,n=`INPUT`){let{inputSchema:r}=await readInputSchema({cwd:e.cwd()}),i=z(e.cwd(),getLocalKeyValueStorePath());if(!r){if(!t)return null;await B(i,{recursive:!0});let e=`${Zn}${n}`,r=R(i,`${e}.json`);return await writeInputRecord(i,e,t.input),{tempInputKey:e,tempInputFilePath:r}}let a=new tr({strict:!1,unicodeRegExp:!1});yt(a,r);let s=getDefaultsFromInputSchema(r),c=getAjvValidator(r,a),l=getLocalInput(e.cwd(),n),u=R(i,l?.fileName??`${n}.json`),f;switch(t?.source){case`stdin`:f=`The input provided through standard input is invalid. Please fix the following errors:
|
|
229
230
|
`;break;case`input`:f=`The input provided through the --input flag is invalid. Please fix the following errors:
|
|
230
231
|
`;break;default:f=t?`The input provided through the ${t.source} file is invalid. Please fix the following errors:\n`:`The input in your storage is invalid. Please fix the following errors:
|
|
231
232
|
`}if(t){let e={...s,...t.input},a=bt(c,r,e);if(a.length>0)throw Error(`${f}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
|
|
232
233
|
`)}`);let l=`${Zn}${n}`,u=R(i,`${l}.json`);return await B(i,{recursive:!0}),await writeInputRecord(i,l,e),{tempInputKey:l,tempInputFilePath:u}}if(!l)return await B(i,{recursive:!0}),await writeInputRecord(i,n,s),{existingInput:l,inputKey:n,inputFilePath:u,writtenAt:Date.now()};if(at.getExtension(l.contentType)===`json`){let e=JSON.parse(l.body.toString(`utf-8`));if(Array.isArray(e))throw Error(`The input in your storage is invalid. It should be an object, not an array.`);let t={...s,...e},a=bt(c,r,t);if(a.length>0)throw Error(`${f}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
|
|
233
|
-
`)}`);let u=`${Zn}${n}`,p=R(i,`${u}.json`);return await writeInputRecord(i,u,t),{tempInputKey:u,tempInputFilePath:p}}return null}};const
|
|
234
|
-
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n)for(let e of Object.keys(
|
|
235
|
-
`),stdout:!0})}};const
|
|
234
|
+
`)}`);let u=`${Zn}${n}`,p=R(i,`${u}.json`);return await writeInputRecord(i,u,t),{tempInputKey:u,tempInputFilePath:p}}return null}};const Ii=[M.READY,M.RUNNING],Li=[M.ABORTING,M.TIMING_OUT];var RunsAbortCommand=class extends ApifyCommand{static name=`abort`;static enableProfileFlag=!0;static description=`Aborts an Actor run.`;static examples=[{description:`Abort a running Actor gracefully (up to 30s drain).`,command:`apify runs abort <runId>`},{description:`Force-abort a running Actor immediately.`,command:`apify runs abort <runId> --force`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-abort`;static args={runId:Z.string({required:!0,description:`The run ID to abort.`})};static flags={force:Y.boolean({description:`Whether to force the run to abort immediately, instead of gracefully.`,default:!1,char:`f`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n)error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});else if(!Ii.includes(n.status))Li.includes(n.status)?error({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):error({message:`Run with ID "${e}" is already aborted.`,stdout:!0});else try{let n=await t.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){printJsonToStdout(n);return}this.flags.force?success({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):success({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to abort run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Ri=new Q({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),zi={"Actor compute units":`ACTOR_COMPUTE_UNITS`,"Dataset reads":`DATASET_READS`,"Dataset writes":`DATASET_WRITES`,"Key-value store reads":`KEY_VALUE_STORE_READS`,"Key-value store writes":`KEY_VALUE_STORE_WRITES`,"Key-value store lists":`KEY_VALUE_STORE_LISTS`,"Request queue reads":`REQUEST_QUEUE_READS`,"Request queue writes":`REQUEST_QUEUE_WRITES`,"Data transfer internal":`DATA_TRANSFER_INTERNAL_GBYTES`,"Data transfer external":`DATA_TRANSFER_EXTERNAL_GBYTES`,"Proxy residential data transfer":`PROXY_RESIDENTIAL_TRANSFER_GBYTES`,"Proxy SERPs":`PROXY_SERPS`};var RunsInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Prints information about an Actor run.`;static examples=[{description:`Show a summary of a run.`,command:`apify runs info <runId>`},{description:`Show verbose details including usage breakdown.`,command:`apify runs info <runId> --verbose`},{description:`Emit the full run object as JSON.`,command:`apify runs info <runId> --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-info`;static args={runId:Z.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:Y.boolean({char:`v`,description:`Prints more in-depth information about the Actor run.`,default:!1})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r){error({message:`Run with ID "${e}" was not found on your account.`});return}let[i,a,s,c,l]=await Promise.all([n.actor(r.actId).get(),n.build(r.buildId).get(),r.actorTaskId?n.task(r.actorTaskId).get():Promise.resolve(void 0),n.dataset(r.defaultDatasetId).get(),n.requestQueue(r.defaultRequestQueueId).get()]);if(this.flags.json){printJsonToStdout({...r,actor:i,build:a,task:s,defaultDataset:c,defaultRequestQueue:l});return}this.addDetailedUsage(r);let u=i?.username?`${i.username}/${i.name}`:i?.name??`unknown-actor`,f=[`${t.yellow(`Actor`)}: ${u} (${t.grey(r.actId)})`];s?f.push(`└─ ${t.yellow(`Task`)}: ${s.title??s.name} (${t.gray(r.actorTaskId)})`,``):r.actorTaskId?f.push(`└─ ${t.yellow(`Task`)}: unknown-task (${t.gray(r.actorTaskId)})`,``):f.push(``);let p=` (exit code: ${t.gray(r.exitCode===null?`N/A`:r.exitCode)})`;f.push(`${t.yellow(`Status`)}: ${prettyPrintStatus(r.status)}${p}`),r.statusMessage&&f.push(`└─ ${t.yellow(`Status Message:`)} ${r.statusMessage}`);let m=c?.itemCount??0;f.push(`${t.yellow(`Results`)}: ${t.cyan(m.toLocaleString(`en-US`))}`),l?f.push(`${t.yellow(`Requests`)}: ${t.cyan(l.handledRequestCount.toLocaleString(`en-US`))} out of ${t.cyan(l.totalRequestCount.toLocaleString(`en-US`))} handled`):f.push(`${t.yellow(`Requests`)}: ${t.gray(`unknown handled`)}`);let h=this.flags.verbose?``:t.gray(` (run with ${t.yellow(`--verbose`)} for a detailed breakdown)`);if(r.usageTotalUsd?f.push(`${t.yellow(`Usage`)}: ${t.cyan(this.formatUsd(r.usageTotalUsd))}${h}`):f.push(`${t.yellow(`Usage`)}: $${t.gray(`0.000`)}${h}`),this.flags.verbose&&f.push(Ri.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${q.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${q.display(r.finishedAt)} (took ${t.gray(cr.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${cr.format(e)}`)}`)}if(f.push(``),r.stats.resurrectCount?f.push(`${t.yellow(`Resurrected`)}: Yes, ${t.cyan(r.stats.resurrectCount.toLocaleString(`en-US`))} ${this.pluralString(r.stats.resurrectCount,`time`,`times`)}`):f.push(`${t.yellow(`Resurrected`)}: No`),r.containerUrl&&f.push(`${t.yellow(`Container URL`)}: ${t.blue(r.containerUrl)}`),f.push(`${t.yellow(`Origin`)}: ${r.meta.origin}`),i){let e=r.buildNumber.split(`.`).slice(0,2).join(`.`),n=i.versions.find(t=>t.versionNumber===e),a=Object.entries(i.taggedBuilds??{}).find(([,e])=>e.buildNumber===r.buildNumber)?.[0],s=[`${t.yellow(`Build`)}:`,t.cyan(r.buildNumber)];a?s.push(`(${t.yellow(a)})`):s.push(`(${t.gray(`N/A`)})`),n&&s.push(`| ${t.gray(`Actor version:`)} ${t.cyan(n.versionNumber)} (${t.yellow(n.buildTag)})`),f.push(s.join(` `))}else f.push(`${t.yellow(`Build`)}: ${t.cyan(r.buildNumber)}`);f.push(`${t.yellow(`Timeout`)}: ${r.options.timeoutSecs.toLocaleString(`en-US`)} seconds`),f.push(`${t.yellow(`Memory`)}: ${r.options.memoryMbytes} MB`),f.push(``),f.push(`${t.yellow(`CPU`)}: ${t.gray(`Average:`)} ${r.stats.cpuAvgUsage.toFixed(2)}% | ${t.gray(`Maximum:`)} ${r.stats.cpuMaxUsage.toFixed(2)}%`),f.push(`${t.yellow(`Memory`)}: ${t.gray(`Average:`)} ${prettyPrintBytes({bytes:r.stats.memAvgBytes,shortBytes:!0})} | ${t.gray(`Maximum:`)} ${prettyPrintBytes({bytes:r.stats.memMaxBytes,shortBytes:!0})}`),f.push(``);let g=consoleRunUrl(r.actId,r.id),_=consoleDatasetUrl(r.defaultDatasetId),v=consoleKeyValueStoreUrl(r.defaultKeyValueStoreId);f.push(`${t.blue(`Export results`)}: ${_}`),f.push(`${t.blue(`View saved items`)}: ${v}`),f.push(`${t.blue(`View in Apify Console`)}: ${g}`),simpleLog({message:f.join(`
|
|
235
|
+
`),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n)for(let e of Object.keys(zi))Ri.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});else for(let[e,r]of Object.entries(zi)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:Ri.pushRow({"":e,Unit:i.toFixed(4),"USD Amount":this.formatUsd(a)});break;case`DATA_TRANSFER_INTERNAL_GBYTES`:case`DATA_TRANSFER_EXTERNAL_GBYTES`:case`PROXY_RESIDENTIAL_TRANSFER_GBYTES`:Ri.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:Ri.pushRow({"":e,Unit:i.toLocaleString(`en-US`),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}},RunsLogCommand=class extends ApifyCommand{static name=`log`;static enableProfileFlag=!0;static description=`Prints the log of a specific run.`;static examples=[{description:`Print the log of a specific run to stdout.`,command:`apify runs log <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-log`;static args={runId:Z.string({required:!0,description:`The run ID to get the log from.`})};async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n)error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});else{info({message:`Log for run with ID "${e}":\n`,stdout:!0});try{await outputJobLog({job:n,apifyClient:t})}catch(t){error({message:`Failed to get log for run with ID "${e}": ${t.message}`})}}}};const Bi=new Q({allColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`,`Build No.`,`Origin`],mandatoryColumns:[`ID`,`Status`,`Results`,`Usage`,`Started At`,`Took`],columnAlignments:{Results:`right`,Usage:`right`,Took:`right`,"Build No.":`right`}});var RunsLsCommand=class extends ApifyCommand{static name=`ls`;static enableProfileFlag=!0;static description=`Lists all runs of the Actor.`;static examples=[{description:`List runs of the Actor in the current directory.`,command:`apify runs ls`},{description:`List runs of a specific Actor.`,command:`apify runs ls apify/hello-world`},{description:`List the 50 most recent runs in descending order.`,command:`apify runs ls --limit 50 --desc`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-ls`;static flags={offset:Y.integer({description:`Number of runs that will be skipped.`,default:0}),limit:Y.integer({description:`Number of runs that will be listed.`,default:10}),desc:Y.boolean({description:`Sort runs in descending order.`,default:!1}),compact:Y.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Z.string({description:`Optional Actor ID or Name to list runs for. By default, it will use the Actor from the current directory.`})};static enableJsonFlag=!0;async run(){let{desc:e,limit:n,offset:r,compact:i,json:a}=this.flags,{actorId:s}=this.args,c=await getLoggedClientOrThrow(),l=await resolveActorContext({providedActorNameOrId:s,client:c});if(!l.valid){error({message:`${l.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let u=await c.actor(l.id).runs().list({desc:e,limit:n,offset:r});if(a){printJsonToStdout(u);return}if(!u.items.length){simpleLog({message:`There are no recent runs found for this Actor.`});return}let f=[`${t.reset(`Showing`)} ${t.yellow(u.items.length)} out of ${t.yellow(u.total)} runs for Actor ${t.yellow(l.userFriendlyId)} (${t.gray(l.id)})`],p=new Map(await Promise.all(u.items.map(async e=>c.dataset(e.defaultDatasetId).get().then(n=>[e.id,t.yellow(n?.itemCount??0)],()=>[e.id,t.gray(`N/A`)]))));for(let e of u.items){let n;if(e.finishedAt){let r=e.finishedAt.getTime()-e.startedAt.getTime();n=t.gray(`${cr.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${cr.format(r,void 0,{left:``})}`)}Bi.pushRow({ID:t.gray(e.id),Status:prettyPrintStatus(e.status),Results:p.get(e.id)||t.gray(`N/A`),Usage:t.cyan(`$${(e.usageTotalUsd??0).toFixed(3)}`),"Started At":ar.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Bi.render(+!i)),simpleLog({message:f.join(`
|
|
236
|
+
`),stdout:!0})}};const Vi=[M.SUCCEEDED,M.FAILED,M.ABORTED,M.TIMED_OUT];var RunsResurrectCommand=class extends ApifyCommand{static name=`resurrect`;static enableProfileFlag=!0;static description=`Resurrects an aborted or finished Actor Run.`;static examples=[{description:`Resurrect a finished or aborted run.`,command:`apify runs resurrect <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-resurrect`;static args={runId:Z.string({required:!0,description:`The run ID to resurrect.`})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,t=await getLoggedClientOrThrow(),n=await t.run(e).get();if(!n)error({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});else if(!Vi.includes(n.status))error({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});else try{let n=await t.run(e).resurrect();if(this.flags.json){printJsonToStdout(n);return}success({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(t){let n=t;error({message:`Failed to resurrect run "${e}".\n ${n.message||n}`,stdout:!0})}}};const Hi=[M.SUCCEEDED,M.FAILED,M.ABORTED,M.TIMED_OUT];var RunsRmCommand=class extends ApifyCommand{static name=`rm`;static enableProfileFlag=!0;static description=`Deletes an Actor Run.`;static interactive=!0;static interactiveNote=`Prompts for confirmation before deleting. Cannot be bypassed; deletion is irreversible.`;static examples=[{description:`Delete a finished or aborted run (prompts for confirmation).`,command:`apify runs rm <runId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-rm`;static args={runId:Z.string({description:`The run ID to delete.`,required:!0})};static flags={...YesFlag()};async run(){let{runId:e}=this.args,{yes:t}=this.flags,n=await getLoggedClientOrThrow(),r=await n.run(e).get();if(!r)error({message:`Run with ID "${e}" was not found on your account.`});else if(!Hi.includes(r.status))error({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});else if(!await X({message:`Are you sure you want to delete this Actor Run?`,preAnswered:t||void 0}))info({message:`Deletion of run "${e}" was canceled.`});else try{await n.run(e).delete(),success({message:`Run with ID "${e}" was deleted.`})}catch(t){let n=t;error({message:`Failed to delete run "${e}".\n ${n.message||n}`})}}},RunsWaitCommand=class extends ApifyCommand{static name=`wait`;static enableProfileFlag=!0;static description=`Waits for an Actor run to reach a terminal status (SUCCEEDED, FAILED, ABORTED, TIMED-OUT).
|
|
236
237
|
Returns exit code 0 only when the run SUCCEEDED. Designed for CI and agentic workflows.`;static examples=[{description:`Wait for a run to finish and return a non-zero exit code on failure.`,command:`apify runs wait <runId>`},{description:`Wait for a run and emit a structured JSON result.`,command:`apify runs wait <runId> --json`},{description:`Give up waiting after 5 minutes. Reports the real current status and exits with code 6 if the run is still running.`,command:`apify runs wait <runId> --timeout 300`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs-wait`;static enableJsonFlag=!0;static args={runId:Z.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:Y.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":Y.integer({description:`How often to poll the platform, in seconds. Defaults to 2.`,required:!1})};async run(){let{runId:t}=this.args,{timeout:n,pollInterval:r,json:i}=this.flags,a=await getLoggedClientOrThrow(),{job:s,timedOutWaiting:c}=await waitForTerminalStatus({apifyClient:a,jobId:t,kind:N.RUN,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleRunUrl(l.actId,l.id),f=l.status===M.SUCCEEDED,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},N.RUN),m=`Gave up waiting after ${n}s; run is still ${l.status}`,h=[];if(f||(h=await fetchLogTail(a,l.id)),i){printJsonToStdout({ok:f,operation:`runs.wait`,timedOutWaiting:c,run:{id:l.id,status:l.status,exitCode:l.exitCode??null,url:u},...f?{}:{error:{phase:`run`,message:c?m:`Actor run did not succeed`,logTail:h}},exitCode:p}),e.exitCode=p;return}let g=[{label:`Run`,value:l.status},{label:`Run ID`,value:l.id},{label:`Actor ID`,value:l.actId}];l.buildNumber&&g.push({label:`Build number`,value:l.buildNumber}),typeof l.exitCode==`number`&&g.push({label:`Exit code`,value:String(l.exitCode)});let _=[{label:`Run URL`,url:u}];simpleLog({message:formatResultSummary({resultLabel:`Apify run result`,overallStatus:l.status,lines:g,links:_,errorReason:f?void 0:h}),stdout:!0}),c?error({message:`${m}.`}):f||error({message:`Run ended with status ${l.status}.`}),e.exitCode=p}},RunsIndexCommand=class extends ApifyCommand{static name=`runs`;static description=`Inspect, abort, resurrect, or delete existing Actor runs.
|
|
237
|
-
Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const
|
|
238
|
+
Does not start new runs — use 'apify call' (synchronous) or 'apify actors start' (asynchronous) for that.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runs`;static subcommands=[RunsAbortCommand,RunsInfoCommand,RunsLogCommand,RunsLsCommand,RunsResurrectCommand,RunsRmCommand,RunsWaitCommand];async run(){this.printHelp()}},SecretsAddCommand=class extends ApifyCommand{static name=`add`;static description=`Adds a new secret to '~/.apify' for use in Actor environment variables.`;static examples=[{description:`Add a secret named "mySecret". Reference it in .actor/actor.json as "@mySecret".`,command:`apify secrets add mySecret TopSecretValue123`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-add`;static args={name:Z.string({required:!0,description:`Name of the secret.`}),value:Z.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Ui=new Q({allColumns:[`Secret Name`],mandatoryColumns:[`Secret Name`],columnAlignments:{"Secret Name":`left`}});var SecretsLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Lists all secret keys stored in your local configuration.`;static examples=[{description:`List the names of all locally stored secrets.`,command:`apify secrets ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-ls`;static enableJsonFlag=!0;async run(){let{json:e}=this.flags,n=getSecretsFile(),r=Object.keys(n);if(e)printJsonToStdout({keys:r});else if(r.length===0)info({message:`You don't have any secrets stored locally. Use 'apify secrets add' to add a secret.`,stdout:!0});else{for(let e of r)Ui.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Ui.render(1),stdout:!0})}}},SecretsRmCommand=class extends ApifyCommand{static name=`rm`;static description=`Permanently deletes a secret from your stored credentials.`;static examples=[{description:`Delete a locally stored secret by name.`,command:`apify secrets rm mySecret`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets-rm`;static args={name:Z.string({required:!0,description:`Name of the secret.`})};async run(){let{name:e}=this.args;removeSecret(e)}},SecretsIndexCommand=class extends ApifyCommand{static name=`secrets`;static description=`Manage locally stored secrets that can be referenced from '${G}' environment variables using the "@" prefix (e.g. "@mySecret"). Secrets are uploaded alongside the Actor and stored encrypted on the Apify platform.`;static group=`Authentication`;static examples=[{description:`Store a secret called "mySecret".`,command:`apify secrets add mySecret TopSecretValue123`},{description:`Reference the secret from .actor/actor.json using the "@" prefix, e.g. "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" }, then push as usual.`,command:`apify push`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-secrets`;static subcommands=[SecretsAddCommand,SecretsLsCommand,SecretsRmCommand];async run(){this.printHelp()}},TaskPublishCommand=class extends ApifyCommand{static name=`publish`;static enableProfileFlag=!0;static description=`Publishes the task on its public landing page.
|
|
238
239
|
The task must belong to a public Actor and have its public display configuration set up on the task Publication tab in Apify Console. Requires write access to the task and to its Actor.`;static examples=[{description:`Publish a task by name.`,command:`apify task publish my-task`},{description:`Publish a task by full name.`,command:`apify task publish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-publish`;static args={taskId:Z.string({required:!0,description:`Name of the task to publish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getCurrentUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l)error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;else try{await c.publish(),success({message:`Task ${t.yellow(l.name)} has been published.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to publish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TaskRunCommand=class extends ApifyCommand{static name=`run`;static enableProfileFlag=!0;static description=`Executes predefined Actor task remotely using local key-value store for input.
|
|
239
240
|
Customize with --memory and --timeout flags.
|
|
240
241
|
`;static examples=[{description:`Run a task by name.`,command:`apify task run my-task`},{description:`Run a task by full ID with custom memory and timeout.`,command:`apify task run username/my-task --memory 4096 --timeout 600`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-run`;static flags=SharedRunOnCloudFlags(`Task`);static enableJsonFlag=!0;static args={taskId:Z.string({required:!0,description:`Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").`})};async run(){let e=await getLoggedClientOrThrow(),t=await getCurrentUserInfo(),n=t.username||t.id,{id:r,userFriendlyId:i,title:a}=await this.resolveTaskId(e,n),s={waitForFinish:2};this.flags.build&&(s.build=this.flags.build),this.flags.timeout!==void 0&&(s.timeout=this.flags.timeout),this.flags.memory&&(s.memory=this.flags.memory);let c,l=runActorOrTaskOnCloud(e,{actorOrTaskData:{id:r,userFriendlyId:i,title:a},runOptions:s,type:`Task`,waitForRunToFinish:!0,printRunLogs:!0,suppressFinalStatus:!0});for await(let e of l)c=e;await finalizeRun({apifyClient:e,run:c,operation:`task-run`,json:this.flags.json})}async resolveTaskId(e,t){let{taskId:n}=this.args;if(n?.includes(`/`)){let r=await e.task(n).get();if(!r)throw Error(`Cannot find Task with ID '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}if(n){let r=await e.task(`${t}/${n.toLowerCase()}`).get();if(!r)throw Error(`Cannot find Task with name '${n}' in your account.`);return{id:r.id,userFriendlyId:`${t}/${r.name}`,title:r.title,task:r}}throw Error(`Please provide a valid Task ID or name.`)}},TaskUnpublishCommand=class extends ApifyCommand{static name=`unpublish`;static enableProfileFlag=!0;static description=`Unpublishes the task from its public landing page.
|
|
241
|
-
The public display configuration is preserved, so the task can be published again later. Requires write access to the task and to its Actor.`;static examples=[{description:`Unpublish a task by name.`,command:`apify task unpublish my-task`},{description:`Unpublish a task by full name.`,command:`apify task unpublish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-unpublish`;static args={taskId:Z.string({required:!0,description:`Name of the task to unpublish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getCurrentUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l)error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;else try{await c.unpublish(),success({message:`Task ${t.yellow(l.name)} has been unpublished.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to unpublish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run and publish saved Apify tasks (named Actor configurations). Create and manage tasks in Apify Console.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task`;static subcommands=[TaskRunCommand,TaskPublishCommand,TaskUnpublishCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{static name=`disable`;static description=`Disables telemetry.`;static examples=[{description:`Opt out of anonymous telemetry.`,command:`apify telemetry disable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{static name=`enable`;static description=`Enables telemetry.`;static examples=[{description:`Opt in to anonymous telemetry.`,command:`apify telemetry enable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{static name=`telemetry`;static description=`Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.`;static group=`Utilities`;static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;static subcommands=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}};const
|
|
242
|
+
The public display configuration is preserved, so the task can be published again later. Requires write access to the task and to its Actor.`;static examples=[{description:`Unpublish a task by name.`,command:`apify task unpublish my-task`},{description:`Unpublish a task by full name.`,command:`apify task unpublish username/my-task`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task-unpublish`;static args={taskId:Z.string({required:!0,description:`Name of the task to unpublish. For example, "my-task" or "username/my-task".`})};async run(){let n=await getLoggedClientOrThrow(),r=await getCurrentUserInfo(),i=r.username||r.id,{taskId:a}=this.args,s=a.includes(`/`)?a:`${i}/${a.toLowerCase()}`,c=n.task(s),l=await c.get();if(!l)error({message:`Cannot find Task with name '${a}' in your account.`}),e.exitCode=250;else try{await c.unpublish(),success({message:`Task ${t.yellow(l.name)} has been unpublished.`,stdout:!0})}catch(n){let r=n;error({message:`Failed to unpublish task ${t.yellow(l.name)}\n ${r.message||r}`}),e.exitCode=1}}},TasksIndexCommand=class extends ApifyCommand{static name=`task`;static description=`Run and publish saved Apify tasks (named Actor configurations). Create and manage tasks in Apify Console.`;static group=`Apify Console`;static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-task`;static subcommands=[TaskRunCommand,TaskPublishCommand,TaskUnpublishCommand];async run(){this.printHelp()}},TelemetryDisableCommand=class extends ApifyCommand{static name=`disable`;static description=`Disables telemetry.`;static examples=[{description:`Opt out of anonymous telemetry.`,command:`apify telemetry disable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?(await updateTelemetryEnabled(!1),success({message:`Telemetry disabled.`})):info({message:`Telemetry is already disabled.`})}},TelemetryEnableCommand=class extends ApifyCommand{static name=`enable`;static description=`Enables telemetry.`;static examples=[{description:`Opt in to anonymous telemetry.`,command:`apify telemetry enable`}];static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;async run(){(await useTelemetryState()).enabled?info({message:`Telemetry is already enabled.`}):(await updateTelemetryEnabled(!0),success({message:`Telemetry enabled.`}))}},TelemetryIndexCommand=class extends ApifyCommand{static name=`telemetry`;static description=`Enable or disable anonymous telemetry. We use this data to improve the CLI and the Apify platform.`;static group=`Utilities`;static docsUrl=`https://docs.apify.com/cli/docs/telemetry`;static subcommands=[TelemetryEnableCommand,TelemetryDisableCommand];async run(){this.printHelp()}};const Wi=new Q({allColumns:[`Template`,`Label`,`Language`,`Use cases`],mandatoryColumns:[`Template`,`Language`,`Use cases`]});var TemplatesLsCommand=class extends ApifyCommand{static name=`ls`;static description=`Prints all available Actor templates, including the use cases and language each one supports.`;static examples=[{description:`List all available templates.`,command:`apify templates ls`},{description:`List templates as JSON (includes the use-case tags for scripting).`,command:`apify templates ls --json`}];static enableJsonFlag=!0;async run(){let{json:e}=this.flags,t=await At().catch(e=>{throw Error(`Could not fetch template list from server. Cause: ${e?.message}`)});if(e)printJsonToStdout(t.templates);else if(t.templates.length===0)info({message:`There are no templates available.`,stdout:!0});else{for(let e of t.templates)Wi.pushRow({Template:e.name,Label:e.label,Language:languageLabel(e.category),"Use cases":(e.useCases??[]).join(`, `)});simpleLog({message:Wi.render(1),stdout:!0})}}},TemplatesIndexCommand=class extends ApifyCommand{static name=`templates`;static description=`Explore the Actor templates used by "apify create".`;static group=`Local Actor Development`;static subcommands=[TemplatesLsCommand];async run(){this.printHelp()}},ValidateSchemaCommand=class extends ApifyCommand{static name=`validate-schema`;static description=`Validates Actor schemas.
|
|
242
243
|
|
|
243
244
|
When a path argument is provided, validates only the input schema at that path.
|
|
244
245
|
|
|
@@ -246,5 +247,5 @@ When no path is provided, validates all schemas found in '${G}':
|
|
|
246
247
|
- Input schema (from "input" key or default locations)
|
|
247
248
|
- Dataset schema (from "storages.dataset")
|
|
248
249
|
- Output schema (from "output")
|
|
249
|
-
- 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 '${G}'.`})};static hiddenAliases=[`vis`];async run(){this.args.path?await this.validateInputSchemaAtPath(this.args.path):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 '${G}'`}`});let t=new tr({strict:!1});yt(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 '${G}'`}`}),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 '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const
|
|
250
|
-
//# sourceMappingURL=_register-
|
|
250
|
+
- 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 '${G}'.`})};static hiddenAliases=[`vis`];async run(){this.args.path?await this.validateInputSchemaAtPath(this.args.path):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 '${G}'`}`});let t=new tr({strict:!1});yt(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 '${G}'`}`}),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 '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Gi=[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],Ki=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Gi as n,processVersionCheck as r,Ki as t};
|
|
251
|
+
//# sourceMappingURL=_register-VGkGlYJW.js.map
|