apify-cli 1.13.1-beta.11 → 1.13.1-beta.12

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,7 +1,7 @@
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,lstatSync as h,mkdirSync as g,openSync as _,readFileSync as v,readdirSync as y,readlinkSync as b,realpathSync as x,renameSync as S,rmSync as C,statSync as w,unlinkSync as T,writeFileSync as E,writeSync as D}from"node:fs";import{ApifyApiError as O,ApifyClient as k,DownloadItemsFormat as A}from"apify-client";import j,{AxiosHeaders as M}from"axios";import{ACTOR_ENV_VARS as N,ACTOR_JOB_STATUSES as P,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as F,ACTOR_NAME as te,ACTOR_SOURCE_TYPES as ne,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as re,LOCAL_ACTOR_ENV_VARS as ie,LOCAL_STORAGE_SUBDIRS as ae,MAX_MULTIFILE_BYTES as oe,META_ORIGINS as se,SOURCE_FILE_FORMATS as ce}from"@apify/consts";import{createHmacSignature as le,cryptoRandomObjectId as L}from"@apify/utilities";import{homedir as ue,platform as de,tmpdir as fe}from"node:os";import R,{basename as pe,dirname as z,isAbsolute as me,join as B,posix as he,relative as V,resolve as H,sep as ge}from"node:path";import _e,{isCI as ve}from"ci-info";import{access as ye,appendFile as be,mkdir as U,mkdtemp as xe,readFile as Se,readdir as Ce,rename as we,rm as Te,stat as W,symlink as Ee,unlink as De,writeFile as G}from"node:fs/promises";import{setTimeout as Oe}from"node:timers/promises";import{execa as K}from"execa";import ke from"which";import{once as Ae}from"node:events";import{inspect as je,parseArgs as Me,promisify as Ne}from"node:util";import{Result as Pe,err as Fe,none as Ie,ok as Le,some as Re}from"@sapphire/result";import{gt as ze,gte as Be,minVersion as Ve,satisfies as He}from"semver";import Ue from"string-width";import We from"strip-ansi";import{jaroWinkler as Ge}from"@skyra/jaro-winkler";import Ke from"js-levenshtein";import{execFileSync as qe,execSync as Je,spawn as Ye}from"node:child_process";import{finished as Xe,pipeline as Ze}from"node:stream/promises";import{DurationFormatter as Qe,Time as $e,TimeTypes as et}from"@sapphire/duration";import{Timestamp as tt}from"@sapphire/timestamp";import nt from"adm-zip";import rt from"ajv/dist/2019.js";import{TarArchive as it,ZipArchive as at}from"archiver";import ot from"escape-string-regexp";import st from"ignore";import{getEncoding as ct}from"istextorbinary";import lt,{Mime as ut}from"mime";import dt from"mime/types/other.js";import ft from"mime/types/standard.js";import{glob as pt}from"tinyglobby";import mt from"configparser";import ht from"@inquirer/input";import{Separator as gt,createPrompt as _t,isEnterKey as vt,makeTheme as yt,useKeypress as bt,usePrefix as xt,useState as St}from"@inquirer/core";import{compile as Ct}from"json-schema-to-typescript";import{validateInputSchema as wt,validateInputUsingValidator as Tt}from"@apify/input_schema";import{getDatasetSchemaValidator as Et,getKeyValueStoreSchemaValidator as Dt,getOutputSchemaValidator as Ot}from"@apify/json_schemas";import{MemoryStorage as kt}from"@crawlee/memory-storage";import At from"cli-table3";import{downloadTemplate as jt}from"giget";import Mt from"jju";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"open";import{fetchManifest as Lt,manifestUrl as Rt,wrapperManifestUrl as zt}from"@apify/actor-templates";import Bt from"@inquirer/checkbox";import Vt from"computer-name";import Ht from"@inquirer/password";import{createServer as Ut}from"node:http";import Wt from"@inquirer/select";import Gt from"node:assert";import{ReadStream as Kt}from"node:tty";import qt from"detect-indent";import{fileURLToPath as Jt}from"node:url";import Yt from"@root/walk";import Xt from"handlebars";var Zt={node:`>=22`};const Qt=`storage`,$t={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=B(ue(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?B(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),ACTOR_RUNTIME_CONFIG_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`actor-runtime`,`config.json`),nn=`apify.json`,rn=`.actor`,q=B(rn,`actor.json`),an=Zt.node,on=_e.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,sn={"X-Apify-Request-Origin":_e.isCI?se.CI:se.CLI,...on&&{"X-Apify-Github-Actions-Run-Url":on}},cn=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await Se(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await G(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(ge).reduce((e,t)=>(e=B(e,t),p(e)||g(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Te(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await W(e)).isFile()&&await De(e)};function ensureApifyDirectory(e){let t=z(e);g(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>W(B(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 ln;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(v(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-${L(8)}`;try{E(n,JSON.stringify(t,null,` `),{mode:384}),S(n,e)}catch(e){throw C(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 un={1:toV2};async function migrateAuthFile(){return ln??=(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=un[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.`})}})(),ln}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(){C(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=x(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 dn=null;function useCLIMetadata(){if(dn)return dn;let e=detectInstallMethod(),t=getRuntimeInfo();return dn={version:`1.13.1-beta.11`,hash:`bd14f86a87cf9e7961eda5ebf2a33bd9e40977bb`,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`&&(dn.installPath=z(process.execPath)),dn}const fn=`com.apify.cli`,pn=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${fn}.${t}`,account:e}}function legacyKeyringKey(e){return{service:fn,account:e}}let mn,hn,gn,_n;async function loadKeyringModule(){return mn===void 0&&(mn=await importKeyringModule()),mn}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 hn||(hn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),hn)}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 pn){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 pn)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 gn||(gn=(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)}})(),gn)}async function dropUnkeyedSecrets(e){for(let e of pn)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 pn){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 _n??=(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)}})(),_n}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const vn=`full_api_access`,yn=3e5,bn=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`,...sn},body:new URLSearchParams(t),signal:AbortSignal.timeout(bn)}),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 xn=/* @__PURE__ */ new Map;function sessionOf(e){let t=xn.get(e);return t||(t={refreshAttempted:!1},xn.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){xn.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=B(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{T(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=_(n,`wx`);return D(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-w(n).mtimeMs>3e4){T(n);continue}}catch{continue}await Oe(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const Sn=`apify-actor-runtime`,Cn=`https://podman.io/docs/installation`,wn=`NOTE: This command is experimental and might change in future releases.`,Tn=3333,En=3e3,Dn={api:Tn,console:En},runtimeApiUrl=e=>`http://localhost:${e}`,runtimeConsoleUrl=e=>`http://localhost:${e}`,On=runtimeApiUrl(Tn),kn=runtimeConsoleUrl(En),An=[`docker`,`podman`],jn=`APIFY_CONTAINER_ENGINE`,Mn=`/var/run/docker.sock`,Nn=`/data`;function runtimeEnvExportLines(e=Dn){return[`export APIFY_CLIENT_BASE_URL=${runtimeApiUrl(e.api)}`,`export APIFY_CONSOLE_URL=${runtimeConsoleUrl(e.console)}`]}function requestedContainerEngine(t=e.env){let n=t[jn]?.trim().toLowerCase();return An.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:An,i=[];for(let e of r)await ke(e,{nothrow:!0})&&i.push(e);return i}async function findContainerEngine(t=e.env){let n=await installedContainerEngines(t);for(let e of n)if(await isEngineReady(e))return{engine:e,ready:!0};return n[0]?{engine:n[0],ready:!1}:null}async function findRunningRuntimeEngine(t=e.env){for(let e of await installedContainerEngines(t))if(await isRuntimeContainerRunning(e))return e;return null}function engineInstallHint(t,n=e.platform){if(t===`podman`)return`Install Podman: ${Cn}`;switch(n){case`darwin`:return`Install Docker Desktop for Mac: https://docs.docker.com/desktop/setup/install/mac-install/`;case`win32`:return`Install Docker Desktop for Windows (WSL 2 backend): https://docs.docker.com/desktop/setup/install/windows-install/`;default:return`Install Docker Engine: https://docs.docker.com/engine/install/`}}function engineDaemonHint(t,n=e.platform){if(t===`podman`)switch(n){case`darwin`:case`win32`:return`Start the Podman machine: 'podman machine start'.`;default:return`Serve Podman's API socket: 'systemctl --user enable --now podman.socket' (rootless) or 'sudo systemctl enable --now podman.socket' (rootful); without systemd, 'podman system service --time=0 &'.`}switch(n){case`darwin`:case`win32`:return`Start Docker Desktop and wait until it reports "Docker Desktop is running".`;default:return`Start the Docker daemon, e.g. 'sudo systemctl start docker'.`}}async function isEngineReady(e){try{if(e===`podman`){let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await K(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}function isDigestPinned(e){return e.includes(`@`)}async function imageExistsLocally(e,t){try{return await K(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await K(e,[`ps`,`--filter`,`name=^${Sn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}catch{return!1}}async function waitForRuntimeContainer(e,t,n=3e4){let r=Date.now()+n;for(;!t.aborted&&Date.now()<r;){if(await isRuntimeContainerRunning(e)&&!t.aborted)return!0;await Oe(250,void 0,{signal:t}).catch(()=>{})}return!1}function parsePublishedPorts(e){let t=e.NetworkSettings?.Ports??e.HostConfig?.PortBindings??{},n=[];for(let[e,r]of Object.entries(t)){let[t,i=`tcp`]=e.split(`/`),a=Number(t);if(Number.isInteger(a))for(let e of r??[])e?.HostPort&&n.push({containerPort:a,protocol:i,hostAddress:`${e.HostIp||`0.0.0.0`}:${e.HostPort}`})}return n.sort((e,t)=>e.containerPort-t.containerPort)}function parseRuntimeContainerInfo(e,t){let n;try{n=JSON.parse(t)}catch{return null}return!n||typeof n!=`object`?null:{engine:e,image:n.Config?.Image??n.ImageName,status:n.State?.Status,startedAt:n.State?.StartedAt,dataDir:n.Mounts?.find(e=>e.Destination===Nn)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await K(e,[`inspect`,Sn,`--format`,`{{json .}}`]);return parseRuntimeContainerInfo(e,t)}catch{return null}}function unixSocketPath(e){return e?.startsWith(`unix://`)?e.slice(7):void 0}async function resolveEngineSocketPath(t,n=e.env,r=e.platform){if(t===`docker`)return r===`linux`?unixSocketPath(n.DOCKER_HOST)??Mn:Mn;try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function parsePodmanInfo(e){let[t,n,r]=e.trim().split(/\s+/),i=Number(r?.match(/^(\d+)\./)?.[1]);return{rootless:t===`true`,selinux:n===`true`,...Number.isInteger(i)?{majorVersion:i}:{}}}async function podmanInfo(){try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.Security.Rootless}} {{.Host.Security.SELinuxEnabled}} {{.Version.Version}}`]);return parsePodmanInfo(e)}catch{return}}function runtimeNetworkMode(e,t){if(e===`podman`&&t?.rootless&&t.majorVersion===3)return`slirp4netns:allow_host_loopback=true`}function runtimeSecurityOptions(e,t){return e!==`podman`||!t?.selinux?[]:[`label=disable`]}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:${Mn}`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,ports:a=Dn,platform:s=e.platform,networkMode:c,securityOptions:l=[]}){let u=[`run`,`--rm`,`--init`,`--name`,Sn];r&&u.push(`--detach`),a.api!==3333&&u.push(`-e`,`ACTOR_RUNTIME_API_PORT=${a.api}`),a.console!==3e3&&u.push(`-e`,`ACTOR_RUNTIME_CONSOLE_PORT=${a.console}`),c&&u.push(`--network`,c);for(let e of l)u.push(`--security-opt`,e);return u.push(`-p`,`${a.api}:${a.api}`,`-p`,`${a.console}:${a.console}`,`-v`,socketMountArg(i,s),`-v`,`${n}:${Nn}`,t),u}function runtimeSkillHintLines(){return[`Agents: run 'apify runtime skill --install' to install this runtime's Agent Skill,`,` or 'apify runtime skill' to read it now.`]}function readActorRuntimeConfig(){try{let e=JSON.parse(v(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),E(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Pn=[`APIFY_CLIENT_BASE_URL`,`APIFY_CONSOLE_URL`];function isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function configuredRuntimePorts(){let{apiPort:e,consolePort:t}=readActorRuntimeConfig();return{api:e??Dn.api,console:t??Dn.console}}function overridingRuntimeEnvVars(t=e.env){return Pn.filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?runtimeApiUrl(configuredRuntimePorts().api):void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?runtimeConsoleUrl(configuredRuntimePorts().console):void 0)}var ActorRuntimeNotRunningError=class extends Error{constructor(e){super(`The Apify CLI is connected to the local Actor runtime at ${runtimeApiUrl(e)}, but the runtime isn't running. Start it with 'apify runtime start --detach', or run 'apify runtime disconnect' to target the Apify platform.`),this.name=`ActorRuntimeNotRunningError`}};function targetsConnectedRuntime(t,n=e.env){return!n.APIFY_CLIENT_BASE_URL&&isConnectedToActorRuntime()&&t===runtimeApiUrl(configuredRuntimePorts().api)}const runtimeDownInterceptor=e=>{let t=j.getAdapter(e.adapter??j.defaults.adapter);return e.adapter=async e=>{try{return await t(e)}catch(e){throw e.code===`ECONNREFUSED`&&!await findRunningRuntimeEngine()?new ActorRuntimeNotRunningError(configuredRuntimePorts().api):e}},e},Fn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[I.TOKEN]?.trim();return t?Fn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${I.TOKEN} is set to "${e}", which is not an API token. Unset ${I.TOKEN} and try again.`}const In={env:`${I.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let Ln,Rn;const zn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${I.TOKEN} is set, so commands ignore ${e}. Unset ${I.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 Rn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));Rn=await requireProfile(t),Ln=void 0}const resolveAuth=async()=>{Ln??=(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 ${I.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),Rn){let t=await getAccessToken(Rn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(Rn));return{token:t,source:`profile`,profile:profileRef(Rn)}}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 Ln}catch(e){throw Ln=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.`;if(t instanceof ActorRuntimeNotRunningError)return t.message;let n=t instanceof O?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 ${I.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=e=>{let t=e||resolveApiBaseUrl();return{baseUrl:t,requestInterceptors:[e=>{e.headers??=new M;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e},...targetsConnectedRuntime(t)?[runtimeDownInterceptor]:[]]}},getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new k(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=Ne(m);let Vn;async function useStdin(){if(Vn)return Vn;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),Vn=n,n}const Hn=5e3;let Un,Wn,Gn=!1,Kn=!1;async function readStdin(e={}){return Un??=_readStdin(e).then(e=>(Wn=e,Gn=!0,e)),Un}function stdinWasCutShort(){return Kn}function describeStdinRead(){return Gn?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||Hn: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 Ae(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;Kn=a.length>0||i===Hn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}let qn=`inherit`;function keepStdoutClean(){qn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{cliDebugPrint(`spawnPromised`,{cmd:t,args:n,opts:r,forwardSignals:i});let a=K(t,n,{windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,qn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(i?.length)for(let t of i){let handler=()=>{a.kill(t)};e.on(t,handler),s.push(()=>e.off(t,handler))}try{return await Pe.fromAsync(a.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const Jn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of Jn)if(process.env[e])return t}function detectCi(){return _e.isCI?{isCi:!0,ciProvider:_e.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const Yn=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
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,lstatSync as h,mkdirSync as g,openSync as _,readFileSync as v,readdirSync as y,readlinkSync as b,realpathSync as x,renameSync as S,rmSync as C,statSync as w,unlinkSync as T,writeFileSync as E,writeSync as D}from"node:fs";import{ApifyApiError as O,ApifyClient as k,DownloadItemsFormat as A}from"apify-client";import j,{AxiosHeaders as M}from"axios";import{ACTOR_ENV_VARS as N,ACTOR_JOB_STATUSES as P,ACTOR_JOB_TERMINAL_STATUSES as ee,ACTOR_JOB_TYPES as F,ACTOR_NAME as te,ACTOR_SOURCE_TYPES as ne,APIFY_ENV_VARS as I,KEY_VALUE_STORE_KEYS as re,LOCAL_ACTOR_ENV_VARS as ie,LOCAL_STORAGE_SUBDIRS as ae,MAX_MULTIFILE_BYTES as oe,META_ORIGINS as se,SOURCE_FILE_FORMATS as ce}from"@apify/consts";import{createHmacSignature as le,cryptoRandomObjectId as L}from"@apify/utilities";import{homedir as ue,platform as de,tmpdir as fe}from"node:os";import R,{basename as pe,dirname as z,isAbsolute as me,join as B,posix as he,relative as V,resolve as H,sep as ge}from"node:path";import _e,{isCI as ve}from"ci-info";import{access as ye,appendFile as be,mkdir as U,mkdtemp as xe,readFile as Se,readdir as Ce,rename as we,rm as Te,stat as W,symlink as Ee,unlink as De,writeFile as G}from"node:fs/promises";import{setTimeout as Oe}from"node:timers/promises";import{execa as K}from"execa";import ke from"which";import{once as Ae}from"node:events";import{inspect as je,parseArgs as Me,promisify as Ne}from"node:util";import{Result as Pe,err as Fe,none as Ie,ok as Le,some as Re}from"@sapphire/result";import{gt as ze,gte as Be,minVersion as Ve,satisfies as He}from"semver";import Ue from"string-width";import We from"strip-ansi";import{jaroWinkler as Ge}from"@skyra/jaro-winkler";import Ke from"js-levenshtein";import{execFileSync as qe,execSync as Je,spawn as Ye}from"node:child_process";import{finished as Xe,pipeline as Ze}from"node:stream/promises";import{DurationFormatter as Qe,Time as $e,TimeTypes as et}from"@sapphire/duration";import{Timestamp as tt}from"@sapphire/timestamp";import nt from"adm-zip";import rt from"ajv/dist/2019.js";import{TarArchive as it,ZipArchive as at}from"archiver";import ot from"escape-string-regexp";import st from"ignore";import{getEncoding as ct}from"istextorbinary";import lt,{Mime as ut}from"mime";import dt from"mime/types/other.js";import ft from"mime/types/standard.js";import{glob as pt}from"tinyglobby";import mt from"configparser";import ht from"@inquirer/input";import{Separator as gt,createPrompt as _t,isEnterKey as vt,makeTheme as yt,useKeypress as bt,usePrefix as xt,useState as St}from"@inquirer/core";import{compile as Ct}from"json-schema-to-typescript";import{validateInputSchema as wt,validateInputUsingValidator as Tt}from"@apify/input_schema";import{getDatasetSchemaValidator as Et,getKeyValueStoreSchemaValidator as Dt,getOutputSchemaValidator as Ot}from"@apify/json_schemas";import{MemoryStorage as kt}from"@crawlee/memory-storage";import At from"cli-table3";import{downloadTemplate as jt}from"giget";import Mt from"jju";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"open";import{fetchManifest as Lt,manifestUrl as Rt,wrapperManifestUrl as zt}from"@apify/actor-templates";import Bt from"@inquirer/checkbox";import Vt from"computer-name";import Ht from"@inquirer/password";import{createServer as Ut}from"node:http";import Wt from"@inquirer/select";import Gt from"node:assert";import{ReadStream as Kt}from"node:tty";import qt from"detect-indent";import{fileURLToPath as Jt}from"node:url";import Yt from"@root/walk";import Xt from"handlebars";var Zt={node:`>=22`};const Qt=`storage`,$t={$schema:`https://apify.com/schemas/v1/actor.ide.json`,actorSpecification:1,name:null,version:`0.0`,buildTag:`latest`,environmentVariables:{}},en=Date.UTC(2026,9,1),tn=[`SIGINT`,`SIGTERM`,`SIGHUP`],GLOBAL_CONFIGS_FOLDER=()=>{let t=B(ue(),`.apify`);return e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?B(t,e.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},AUTH_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`auth.json`),SECRETS_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`secrets.json`),STATE_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`state.json`),TELEMETRY_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`telemetry.json`),ACTOR_RUNTIME_CONFIG_FILE_PATH=()=>B(GLOBAL_CONFIGS_FOLDER(),`actor-runtime`,`config.json`),nn=`apify.json`,rn=`.actor`,q=B(rn,`actor.json`),an=Zt.node,on=_e.GITHUB_ACTIONS?`${e.env.GITHUB_SERVER_URL}/${e.env.GITHUB_REPOSITORY}/actions/runs/${e.env.GITHUB_RUN_ID}`:void 0,sn={"X-Apify-Request-Origin":_e.isCI?se.CI:se.CLI,...on&&{"X-Apify-Github-Actions-Run-Url":on}},cn=`3.11.0`,updateLocalJson=async(e,t={},n=null)=>{let r=await Se(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await G(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(ge).reduce((e,t)=>(e=B(e,t),p(e)||g(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Te(e,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})))},deleteFile=async e=>{(await W(e)).isFile()&&await De(e)};function ensureApifyDirectory(e){let t=z(e);g(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>W(B(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 ln;function parseAuthFile(){if(!p(AUTH_FILE_PATH()))return{};try{let e=JSON.parse(v(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-${L(8)}`;try{E(n,JSON.stringify(t,null,` `),{mode:384}),S(n,e)}catch(e){throw C(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 un={1:toV2};async function migrateAuthFile(){return ln??=(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=un[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.`})}})(),ln}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(){C(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=x(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 dn=null;function useCLIMetadata(){if(dn)return dn;let e=detectInstallMethod(),t=getRuntimeInfo();return dn={version:`1.13.1-beta.12`,hash:`f51538f59e77b961e6de2f08583ea77c8499c2b9`,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`&&(dn.installPath=z(process.execPath)),dn}const fn=`com.apify.cli`,pn=[`token`,`proxy-password`,`refresh-token`];function keyringKey(e,t){return{service:`${fn}.${t}`,account:e}}function legacyKeyringKey(e){return{service:fn,account:e}}let mn,hn,gn,_n;async function loadKeyringModule(){return mn===void 0&&(mn=await importKeyringModule()),mn}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 hn||(hn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`?`file`:await loadKeyringModule()?`keyring`:`file`)(),hn)}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 pn){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 pn)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 gn||(gn=(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)}})(),gn)}async function dropUnkeyedSecrets(e){for(let e of pn)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 pn){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 _n??=(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)}})(),_n}async function ensureCredentialsCurrent(){await ensureMigrated(),await ensureAuthFileCurrent(),await ensureSecretsKeyed()}const vn=`full_api_access`,yn=3e5,bn=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`,...sn},body:new URLSearchParams(t),signal:AbortSignal.timeout(bn)}),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 xn=/* @__PURE__ */ new Map;function sessionOf(e){let t=xn.get(e);return t||(t={refreshAttempted:!1},xn.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){xn.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=B(GLOBAL_CONFIGS_FOLDER(),`oauth-refresh-${t}.lock`),release=()=>{try{T(n)}catch{}},noop=()=>{};try{ensureApifyDirectory(AUTH_FILE_PATH())}catch{return noop}for(let t=0;t<50;t++){try{let t=_(n,`wx`);return D(t,`${e.pid}`),c(t),release}catch(e){if(e.code!==`EEXIST`)return noop}try{if(Date.now()-w(n).mtimeMs>3e4){T(n);continue}}catch{continue}await Oe(100)}return cliDebugPrint(`oauth`,`refresh lock wait timed out; continuing without it`),noop}const Sn=`apify-actor-runtime`,Cn=`https://podman.io/docs/installation`,wn=`NOTE: This command is experimental and might change in future releases.`,Tn=3333,En=3e3,Dn={api:Tn,console:En},runtimeApiUrl=e=>`http://localhost:${e}`,runtimeConsoleUrl=e=>`http://localhost:${e}`,On=runtimeApiUrl(Tn),kn=runtimeConsoleUrl(En),An=[`docker`,`podman`],jn=`APIFY_CONTAINER_ENGINE`,Mn=`/var/run/docker.sock`,Nn=`/data`;function runtimeEnvExportLines(e=Dn){return[`export APIFY_CLIENT_BASE_URL=${runtimeApiUrl(e.api)}`,`export APIFY_CONSOLE_URL=${runtimeConsoleUrl(e.console)}`]}function requestedContainerEngine(t=e.env){let n=t[jn]?.trim().toLowerCase();return An.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:An,i=[];for(let e of r)await ke(e,{nothrow:!0})&&i.push(e);return i}async function findContainerEngine(t=e.env){let n=await installedContainerEngines(t);for(let e of n)if(await isEngineReady(e))return{engine:e,ready:!0};return n[0]?{engine:n[0],ready:!1}:null}async function findRunningRuntimeEngine(t=e.env){for(let e of await installedContainerEngines(t))if(await isRuntimeContainerRunning(e))return e;return null}function engineInstallHint(t,n=e.platform){if(t===`podman`)return`Install Podman: ${Cn}`;switch(n){case`darwin`:return`Install Docker Desktop for Mac: https://docs.docker.com/desktop/setup/install/mac-install/`;case`win32`:return`Install Docker Desktop for Windows (WSL 2 backend): https://docs.docker.com/desktop/setup/install/windows-install/`;default:return`Install Docker Engine: https://docs.docker.com/engine/install/`}}function engineDaemonHint(t,n=e.platform){if(t===`podman`)switch(n){case`darwin`:case`win32`:return`Start the Podman machine: 'podman machine start'.`;default:return`Serve Podman's API socket: 'systemctl --user enable --now podman.socket' (rootless) or 'sudo systemctl enable --now podman.socket' (rootful); without systemd, 'podman system service --time=0 &'.`}switch(n){case`darwin`:case`win32`:return`Start Docker Desktop and wait until it reports "Docker Desktop is running".`;default:return`Start the Docker daemon, e.g. 'sudo systemctl start docker'.`}}async function isEngineReady(e){try{if(e===`podman`){let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await K(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}function isDigestPinned(e){return e.includes(`@`)}async function imageExistsLocally(e,t){try{return await K(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await K(e,[`ps`,`--filter`,`name=^${Sn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}catch{return!1}}async function waitForRuntimeContainer(e,t,n=3e4){let r=Date.now()+n;for(;!t.aborted&&Date.now()<r;){if(await isRuntimeContainerRunning(e)&&!t.aborted)return!0;await Oe(250,void 0,{signal:t}).catch(()=>{})}return!1}function parsePublishedPorts(e){let t=e.NetworkSettings?.Ports??e.HostConfig?.PortBindings??{},n=[];for(let[e,r]of Object.entries(t)){let[t,i=`tcp`]=e.split(`/`),a=Number(t);if(Number.isInteger(a))for(let e of r??[])e?.HostPort&&n.push({containerPort:a,protocol:i,hostAddress:`${e.HostIp||`0.0.0.0`}:${e.HostPort}`})}return n.sort((e,t)=>e.containerPort-t.containerPort)}function parseRuntimeContainerInfo(e,t){let n;try{n=JSON.parse(t)}catch{return null}return!n||typeof n!=`object`?null:{engine:e,image:n.Config?.Image??n.ImageName,status:n.State?.Status,startedAt:n.State?.StartedAt,dataDir:n.Mounts?.find(e=>e.Destination===Nn)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await K(e,[`inspect`,Sn,`--format`,`{{json .}}`]);return parseRuntimeContainerInfo(e,t)}catch{return null}}function unixSocketPath(e){return e?.startsWith(`unix://`)?e.slice(7):void 0}async function resolveEngineSocketPath(t,n=e.env,r=e.platform){if(t===`docker`)return r===`linux`?unixSocketPath(n.DOCKER_HOST)??Mn:Mn;try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function parsePodmanInfo(e){let[t,n,r]=e.trim().split(/\s+/),i=Number(r?.match(/^(\d+)\./)?.[1]);return{rootless:t===`true`,selinux:n===`true`,...Number.isInteger(i)?{majorVersion:i}:{}}}async function podmanInfo(){try{let{stdout:e}=await K(`podman`,[`info`,`--format`,`{{.Host.Security.Rootless}} {{.Host.Security.SELinuxEnabled}} {{.Version.Version}}`]);return parsePodmanInfo(e)}catch{return}}function runtimeNetworkMode(e,t){if(e===`podman`&&t?.rootless&&t.majorVersion===3)return`slirp4netns:allow_host_loopback=true`}function runtimeSecurityOptions(e,t){return e!==`podman`||!t?.selinux?[]:[`label=disable`]}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:${Mn}`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,ports:a=Dn,platform:s=e.platform,networkMode:c,securityOptions:l=[]}){let u=[`run`,`--rm`,`--init`,`--name`,Sn];r&&u.push(`--detach`),a.api!==3333&&u.push(`-e`,`ACTOR_RUNTIME_API_PORT=${a.api}`),a.console!==3e3&&u.push(`-e`,`ACTOR_RUNTIME_CONSOLE_PORT=${a.console}`),c&&u.push(`--network`,c);for(let e of l)u.push(`--security-opt`,e);return u.push(`-p`,`${a.api}:${a.api}`,`-p`,`${a.console}:${a.console}`,`-v`,socketMountArg(i,s),`-v`,`${n}:${Nn}`,t),u}function runtimeSkillHintLines(){return[`Agents: run 'apify runtime skill --install' to install this runtime's Agent Skill,`,` or 'apify runtime skill' to read it now.`]}function readActorRuntimeConfig(){try{let e=JSON.parse(v(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),E(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Pn=[`APIFY_CLIENT_BASE_URL`,`APIFY_CONSOLE_URL`];function isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function configuredRuntimePorts(){let{apiPort:e,consolePort:t}=readActorRuntimeConfig();return{api:e??Dn.api,console:t??Dn.console}}function overridingRuntimeEnvVars(t=e.env){return Pn.filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?runtimeApiUrl(configuredRuntimePorts().api):void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?runtimeConsoleUrl(configuredRuntimePorts().console):void 0)}var ActorRuntimeNotRunningError=class extends Error{constructor(e){super(`The Apify CLI is connected to the local Actor runtime at ${runtimeApiUrl(e)}, but the runtime isn't running. Start it with 'apify runtime start --detach', or run 'apify runtime disconnect' to target the Apify platform.`),this.name=`ActorRuntimeNotRunningError`}};function targetsConnectedRuntime(t,n=e.env){return!n.APIFY_CLIENT_BASE_URL&&isConnectedToActorRuntime()&&t===runtimeApiUrl(configuredRuntimePorts().api)}const runtimeDownInterceptor=e=>{let t=j.getAdapter(e.adapter??j.defaults.adapter);return e.adapter=async e=>{try{return await t(e)}catch(e){throw e.code===`ECONNREFUSED`&&!await findRunningRuntimeEngine()?new ActorRuntimeNotRunningError(configuredRuntimePorts().api):e}},e},Fn=/* @__PURE__ */ new Set([`undefined`,`null`,`nil`,`none`,`nan`,`false`,`0`,`-`]);function readEnvToken(){let t=e.env[I.TOKEN]?.trim();return t?Fn.has(t.toLowerCase())?{kind:`invalid`,raw:t}:{kind:`token`,token:t}:{kind:`unset`}}function invalidEnvTokenMessage(e){return`${I.TOKEN} is set to "${e}", which is not an API token. Unset ${I.TOKEN} and try again.`}const In={env:`${I.TOKEN} environment variable`,stored:`apify login`,profile:`--profile flag`};let Ln,Rn;const zn=`No accounts are stored. Run "apify login" to add one.`;function envTokenOverridesProfileMessage(e){return`${I.TOKEN} is set, so commands ignore ${e}. Unset ${I.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 Rn??getActiveProfile()}async function selectProfile(t){if(readEnvToken().kind!==`unset`)throw e.exitCode=5,Error(envTokenOverridesProfileMessage(`--profile`));Rn=await requireProfile(t),Ln=void 0}const resolveAuth=async()=>{Ln??=(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 ${I.TOKEN}.`}),{token:t.token,source:`env`};if(await ensureCredentialsCurrent(),Rn){let t=await getAccessToken(Rn.id);if(!t)throw e.exitCode=1,Error(missingProfileTokenMessage(Rn));return{token:t,source:`profile`,profile:profileRef(Rn)}}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 Ln}catch(e){throw Ln=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.`;if(t instanceof ActorRuntimeNotRunningError)return t.message;let n=t instanceof O?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 ${I.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=e=>{let t=e||resolveApiBaseUrl();return{baseUrl:t,requestInterceptors:[e=>{e.headers??=new M;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e},...targetsConnectedRuntime(t)?[runtimeDownInterceptor]:[]]}},getApifyClientOptionsForToken=(e,t)=>({...getAnonymousApifyClientOptions(t),token:e});async function loginWithToken(e,t){let n=new k(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=Ne(m);let Vn;async function useStdin(){if(Vn)return Vn;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),Vn=n,n}const Hn=5e3;let Un,Wn,Gn=!1,Kn=!1;async function readStdin(e={}){return Un??=_readStdin(e).then(e=>(Wn=e,Gn=!0,e)),Un}function stdinWasCutShort(){return Kn}function describeStdinRead(){return Gn?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||Hn: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 Ae(r,`end`,{signal:s.signal})}catch(t){if(t.name===`AbortError`){if(!e)return;Kn=a.length>0||i===Hn}}finally{r.off(`data`,onData),r.pause()}disarmTimeout();let l=Buffer.concat(a);if(l.length)return l}let qn=`inherit`;function keepStdoutClean(){qn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{cliDebugPrint(`spawnPromised`,{cmd:t,args:n,opts:r,forwardSignals:i});let a=K(t,n,{windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,qn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),s=[];if(i?.length)for(let t of i){let handler=()=>{a.kill(t)};e.on(t,handler),s.push(()=>e.off(t,handler))}try{return await Pe.fromAsync(a.catch(e=>{let n;throw n=e.exitCode==null?e.signal?`${t} exited due to signal ${e.signal}`:e.shortMessage:`${t} exited with code ${e.exitCode}`,Error(n,{cause:e})}))}finally{for(let e of s)e()}};async function execWithLog({cmd:e,args:t=[],opts:n={},overrideCommand:r,forwardSignals:i}){run({message:`${r||e} ${t.join(` `)}`});let a=await spawnPromised(e,t,n,{forwardSignals:i});if(a.isErr()){let e=a.unwrapErr();if(error({message:e.message}),e.cause)throw e.cause}}const Jn=[[`CLAUDECODE`,`claude_code`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CURSOR_AGENT`,`cursor`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`]];function detectAiAgent(){for(let[e,t]of Jn)if(process.env[e])return t}function detectCi(){return _e.isCI?{isCi:!0,ciProvider:_e.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const Yn=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
2
2
  `)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
3
3
  `)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
4
- `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{E(i,n),r!==void 0&&s(i,r),S(i,t)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{u(t,i),r!==void 0&&s(i,r),S(i,n)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Yn)atomicWriteSync(B(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(B(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(B(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=z(e.execPath),i=pe(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Yn){let t=B(r,`${e}.exe.old`);if(p(t))try{C(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Yn.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=B(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Yn){let n=B(r,`${t}.exe`);if(p(n))try{H(n)===H(e.execPath)?(S(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):C(n,{force:!0})}catch(e){try{S(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=B(r,`upgrade.ps1`);try{C(t,{force:!0}),cliDebugPrint(`[migration] removed upgrade script, it will be re-downloaded on the next upgrade`)}catch(e){cliDebugPrint(`[migration] failed to remove upgrade script`,{upgradeScriptPath:t,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Xn;function getMaxLineWidth(){if(Xn)return Xn;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Xn=e;else if(!process.stdout.isTTY)Xn=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Xn=e<1?80:e<40?40:e}return Xn}function experimentalLabel(e){return e.experimental?`${t.yellow(`[EXPERIMENTAL]`)} `:``}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=`${experimentalLabel(this.command)}${this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``}`;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
4
+ `)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{E(i,n),r!==void 0&&s(i,r),S(i,t)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{u(t,i),r!==void 0&&s(i,r),S(i,n)}catch(e){try{C(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Yn)atomicWriteSync(B(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(B(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(B(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=z(e.execPath),i=pe(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Yn){let t=B(r,`${e}.exe.old`);if(p(t))try{C(t,{force:!0}),cliDebugPrint(`[migration] removed stale legacy binary`,t)}catch(e){cliDebugPrint(`[migration] failed to remove stale legacy binary`,{stalePath:t,err:e})}}if(i===`apify-cli`||!Yn.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=B(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n)for(let t of Yn){let n=B(r,`${t}.exe`);if(p(n))try{H(n)===H(e.execPath)?(S(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):C(n,{force:!0})}catch(e){try{S(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}cliDebugPrint(`[migration] migration to single bundle complete`)}let Xn;function getMaxLineWidth(){if(Xn)return Xn;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Xn=e;else if(!process.stdout.isTTY)Xn=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Xn=e<1?80:e<40?40:e}return Xn}function experimentalLabel(e){return e.experimental?`${t.yellow(`[EXPERIMENTAL]`)} `:``}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=`${experimentalLabel(this.command)}${this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``}`;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
5
5
  `)[0]}`,``)}pushDescription(e){if(!this.command.description)return;e.push(t.bold(`DESCRIPTION`));let r=i(this.command.description,getMaxLineWidth()-2,{trim:!1}),a=n(r,2);e.push(a),e.push(``)}pushExamples(e){let{examples:r}=this.command;if(r?.length){e.push(t.bold(`EXAMPLES`));for(let a of r){if(a.description){let r=i(a.description,getMaxLineWidth()-4,{trim:!1}).split(`
6
6
  `).map(e=>`# ${e}`).join(`
7
7
  `),s=n(r,2);e.push(t.dim(s))}e.push(` $ ${this.normalizeExampleCommand(a.command)}`),e.push(``)}}}normalizeExampleCommand(e){let t=this.entrypoint.split(` `);if(t.length<2)return e;let n=t[t.length-1],r=`${t.slice(0,-1).join(` `)} `,i=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=e;return a.startsWith(`${n} `)&&(a=`${r}${a}`),a=a.replace(RegExp(`\\|\\s+${i}\\s`,`g`),`| ${r}${n} `),a}pushInteractiveNote(e){if(!this.command.interactive)return;e.push(t.bold(`NOTE`));let r=this.command.interactiveNote||`This command prompts the user for input. To run non-interactively (e.g. in CI or from an AI agent), pass all required arguments and flags explicitly.`,a=i(r,getMaxLineWidth()-2,{trim:!1}),s=n(a,2);e.push(s),e.push(``)}pushLearnMore(e){this.command.docsUrl&&(e.push(t.bold(`LEARN MORE`)),e.push(` ${this.command.docsUrl}`),e.push(``))}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:t,indentSize:n}){Ue(e.join(` `).split(`
@@ -140,31 +140,30 @@ Returns exit code 0 only when the build SUCCEEDED. Designed for CI and agentic w
140
140
  `)}\n`;try{await U(z(m),{recursive:!0}),await G(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(`
141
141
  `)});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(`
142
142
  `)})}else info({message:[t.gray(`Manually add the following lines to ${v} or similar:`),...g.map(e=>t.white.bold(` ${e}`))].join(`
143
- `)})}};const Hi=useCLIMetadata();function isInstalledOnMusl(){return Hi.platform===`linux`&&p(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Hi.platform===`darwin`&&Hi.arch===`x64`?!Je(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Hi.platform===`linux`&&Hi.arch===`x64`?!v(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Hi.platform===`windows`&&Hi.arch!==`arm64`&&Je(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:`utf-8`,windowsHide:!0}).trim().toLowerCase()===`true`}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":lr}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Hi.platform&&i===Hi.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Ui={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},Wi=`1.0.1`,Gi=`https://raw.githubusercontent.com/apify/apify-cli/refs/heads/master/scripts/install/upgrade.ps1`;var UpgradeCommand=class extends ApifyCommand{static name=`upgrade`;static description=`Checks that installed Apify CLI version is up to date.`;static group=`Utilities`;static examples=[{description:`Check for a newer CLI version and upgrade if available.`,command:`apify upgrade`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-upgrade`;static hidden=!0;static aliases=[`cv`,`check-version`];static flags={force:X.boolean({description:`[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.`,required:!1,char:`f`}),version:X.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":X.boolean({description:`Whether the command was called automatically by the CLI for a version check.`,hidden:!0,default:!1})};get cliName(){return this.entrypoint===`apify`?`Apify CLI`:`Actor CLI`}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=Ui[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
143
+ `)})}};const Hi=useCLIMetadata();function isInstalledOnMusl(){return Hi.platform===`linux`&&p(`/etc/alpine-release`)}function isInstalledOnBaseline(){return Hi.platform===`darwin`&&Hi.arch===`x64`?!Je(`sysctl -a`,{encoding:`utf-8`}).includes(`AVX2`):Hi.platform===`linux`&&Hi.arch===`x64`?!v(`/proc/cpuinfo`,`utf-8`).includes(`avx2`):Hi.platform===`windows`&&Hi.arch!==`arm64`&&Je(`pwsh -c "!(Add-Type -MemberDefinition '[DllImport(\\"kernel32.dll\\")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru)::IsProcessorFeaturePresent(40)"`,{encoding:`utf-8`,windowsHide:!0}).trim().toLowerCase()===`true`}async function useCLIVersionAssets(e){let t=e.replace(/^v(\d+)/,`$1`),n=t===`latest`?`latest`:`tags/v${t}`,r=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${n}`,{headers:{"User-Agent":lr}});if(!r.ok)return cliDebugPrint(`useCLIVersionAssets`,`Failed to fetch release`,{statusCode:r.status,body:await r.text(),version:e,tag:n}),null;let i=await r.json(),a=isInstalledOnMusl(),s=isInstalledOnBaseline(),c=i.assets.filter(e=>{if(!e.name.startsWith(`apify-cli-`))return!1;let[n,r,i,...c]=e.name.slice(10).replace(t,`version`).replace(`.exe`,``).split(`-`);return r===Hi.platform&&i===Hi.arch&&c.includes(`musl`)===a&&c.includes(`baseline`)===s});return cliDebugPrint(`useCLIVersionAssets`,`Fetched release`,{version:i.tag_name,filteredAssets:c}),{assets:c,version:i.tag_name.replace(/^v(\d+)/,`$1`)}}const Ui={bundle:(e,t)=>[`${t}`,`upgrade`],npm:e=>[`npm`,`install`,`-g`,`apify-cli@${e}`],pnpm:e=>[`pnpm`,`install`,`-g`,`apify-cli@${e}`],bun:e=>[`bun`,`install`,`-g`,`apify-cli@${e}`],homebrew:()=>[`brew`,`upgrade`,`apify-cli`],volta:e=>[`volta`,`install`,`apify-cli@${e}`]},Wi=`1.0.1`;function resolveSystemExecutable(...t){let n=e.env.SystemRoot;if(!n||!me(n))return;let r=B(n,`System32`,...t);return p(r)?r:void 0}var UpgradeCommand=class extends ApifyCommand{static name=`upgrade`;static description=`Checks that installed Apify CLI version is up to date.`;static group=`Utilities`;static examples=[{description:`Check for a newer CLI version and upgrade if available.`,command:`apify upgrade`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-upgrade`;static hidden=!0;static aliases=[`cv`,`check-version`];static flags={force:X.boolean({description:`[DEPRECATED] This flag is now ignored, as running the command manually will always check for the latest version.`,required:!1,char:`f`}),version:X.string({description:`The version of the CLI to upgrade to. If not provided, the latest version will be used.`,required:!1}),"internal-automatic-call":X.boolean({description:`Whether the command was called automatically by the CLI for a version check.`,hidden:!0,default:!1})};get cliName(){return this.entrypoint===`apify`?`Apify CLI`:`Actor CLI`}async run(){if(this.flags.version){await this.handleInstallSpecificVersion(this.flags.version);return}let e=await useCLIVersionCheck(!this.flags.internalAutomaticCall),{installMethod:n}=useCLIMetadata();if(!e.shouldUpdate||e.currentVersion===`0.0.0`){cliDebugPrint(`[upgrade] no update needed`,{shouldUpdate:e.shouldUpdate,currentVersion:e.currentVersion}),this.flags.internalAutomaticCall||info({message:`${this.cliName} is up to date 👍 \n`});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion(`latest`);return}let r=Ui[n](`latest`,this.entrypoint).join(` `);simpleLog({message:``}),warning({message:[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` ↪ Run ${t.bgWhite(t.black(r))} to update! 👍 \n`].join(`
144
144
  `)})}async handleInstallSpecificVersion(t){if(t!==`latest`&&!Be(t,Wi)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Wi}.`});return}let n=await useCLIVersionAssets(t);if(!n){error({message:`The provided version does not exist. Please check the version number and try again.`});return}let{assets:r,version:i}=n;if(!Be(i,Wi)){error({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Wi}.`});return}let a=useCLIMetadata();if(a.installMethod===`bundle`){if(!r.length){error({message:[`Failed to find the assets for your system and the provided version. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`].join(`
145
145
  `)});return}let t=z(e.execPath);cliDebugPrint(`[upgrade] bundleDirectory`,t);let n=await Ce(t);if(!n.some(e=>e.startsWith(`apify`)||e.startsWith(`actor`))){cliDebugPrint(`[upgrade] directoryEntries`,n),error({message:[`Failed to find the currently installed ${this.cliName} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${i}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${t}`].join(`
146
- `)});return}if(a.platform===`windows`)return this.startUpgradeProcess(t,i,r);await this.handleUnixUpgrade(t,i,r)&&this.successMessage(i);return}let s=Ui[a.installMethod](t,this.entrypoint);if(e.env.APIFY_CLI_DEBUG)info({message:`Would run command: ${s.join(` `)}`});else try{await execWithLog({cmd:s[0],args:s.slice(1)}),this.successMessage(i)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${s.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(t,n,r){await this.upsertUpgradeScript(t);let i=[`-ExecutionPolicy`,`Bypass`,`-File`,`"${B(t,`upgrade.ps1`)}"`,`-ProcessId`,e.pid.toString(),`-InstallLocation`,`"${t}"`,`-Version`,`"${n}"`],a=r.map(e=>e.browser_download_url).join(`,`);i.push(`-AllUrls`,`"${a}"`),cliDebugPrint(`[upgrade] starting upgrade process with args`,i),info({message:`Starting upgrade process...`});let s=Ye(`powershell.exe`,i,{detached:!0,shell:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});s.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),s.unref(),e.exit(0)}),s.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async upsertUpgradeScript(t){let n=B(t,`upgrade.ps1`);if(p(n))return;let r=useCLIMetadata(),i=await fetch(Gi,{headers:{"User-Agent":lr}});i.ok||(error({message:[`Failed to fetch the upgrade script. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The system you are running on: ${r.platform} ${r.arch}`,`- The URL of the asset that failed to fetch: ${Gi}`,`- The status code of the response: ${i.status}`].join(`
147
- `)}),e.exit(1));let a=await i.arrayBuffer();await G(n,Buffer.from(a)),cliDebugPrint(`[upgrade] downloaded upgrade script to`,n)}async handleUnixUpgrade(n,r,i){let a=useCLIMetadata();for(let s of i){let i=`apify-cli`,c=B(n,i);info({message:`Downloading \`${i}\` binary of the Apify CLI...`});let l=await fetch(s.browser_download_url,{headers:{"User-Agent":lr}});if(!l.ok){let t=await l.text();return cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:s,status:l.status,body:t}),error({message:[`Failed to fetch the ${i} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The URL of the asset that failed to fetch: ${s.browser_download_url}`,`- The status code of the response: ${l.status}`,`- The body of the response: ${t}`].join(`
146
+ `)});return}if(a.platform===`windows`)return this.startUpgradeProcess(t,i,r);await this.handleUnixUpgrade(t,i,r)&&this.successMessage(i);return}let s=Ui[a.installMethod](t,this.entrypoint);if(e.env.APIFY_CLI_DEBUG)info({message:`Would run command: ${s.join(` `)}`});else try{await execWithLog({cmd:s[0],args:s.slice(1)}),this.successMessage(i)}catch{error({message:`Failed to upgrade the CLI. Please run the following command manually: ${s.join(` `)}`})}}successMessage(e){success({message:`Successfully upgraded to ${e} 👍`})}async startUpgradeProcess(t,n,r){if(typeof __APIFY_WINDOWS_UPGRADE_SCRIPT__!=`string`){error({message:`The Windows upgrade script is only available in CLI bundles.`});return}let i=B(t,`upgrade.ps1`);await G(i,__APIFY_WINDOWS_UPGRADE_SCRIPT__);let a=r.map(e=>e.browser_download_url).join(`,`),s=resolveSystemExecutable(`cmd.exe`),c=resolveSystemExecutable(`WindowsPowerShell`,`v1.0`,`powershell.exe`);if(!s||!c){error({message:`Couldn't find ${s?`powershell.exe`:`cmd.exe`} in the Windows system directory.`});return}let l=[`"${c}"`,`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,`"${i}"`,`-ProcessId`,e.pid.toString(),`-InstallLocation`,`"${t}"`,`-Version`,`"${n}"`,`-AllUrls`,`"${a}"`].join(` `);cliDebugPrint(`[upgrade] starting upgrade process with command`,l),info({message:`Starting upgrade process...`});let u=Ye(s,[`/d`,`/s`,`/c`,`"${l}"`],{detached:!0,stdio:`inherit`,windowsHide:!1,windowsVerbatimArguments:!0});u.on(`spawn`,()=>{cliDebugPrint(`[upgrade] upgrade process spawned`),u.unref(),e.exit(0)}),u.on(`error`,e=>{error({message:`Failed to start the upgrade process: ${e.message}`})})}async handleUnixUpgrade(n,r,i){let a=useCLIMetadata();for(let s of i){let i=`apify-cli`,c=B(n,i);info({message:`Downloading \`${i}\` binary of the Apify CLI...`});let l=await fetch(s.browser_download_url,{headers:{"User-Agent":lr}});if(!l.ok){let t=await l.text();return cliDebugPrint(`[upgrade] failed to fetch asset`,{asset:s,status:l.status,body:t}),error({message:[`Failed to fetch the ${i} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The URL of the asset that failed to fetch: ${s.browser_download_url}`,`- The status code of the response: ${l.status}`,`- The body of the response: ${t}`].join(`
148
147
  `)}),e.exitCode=1,!1}if(e.env.APIFY_CLI_DEBUG&&!e.env.APIFY_CLI_FORCE){info({message:`Would write asset ${i} to ${c}`});continue}info({message:t.gray(`Writing ${i} to ${c}...`)});let u=await l.arrayBuffer(),f=`${c}.${e.pid}.tmp`;try{await G(f,Buffer.from(u),{mode:493}),await we(f,c),writeEntrypointShims(n,!1),cliDebugPrint(`[upgrade ${i}] wrote asset to`,c)}catch(t){return await Te(f,{force:!0}).catch(()=>{}),cliDebugPrint(`[upgrade] failed to write asset`,{error:t}),error({message:[`Failed to write the ${i} bundle. Please open an issue on https://github.com/apify/apify-cli/issues/new and provide the following information:`,`- The version you are trying to upgrade to: ${r}`,`- The system you are running on: ${a.platform} ${a.arch}`,`- The URL of the asset that failed to fetch: ${s.browser_download_url}`,`- The error: ${t.message}`].join(`
149
- `)}),e.exitCode=1,!1}}return!0}};const Ki={STARTER:`STARTER`,WEB_SCRAPING:`WEB_SCRAPING`,INTEGRATION:`INTEGRATION`,AUTOMATION:`AUTOMATION`,AI:`AI`},qi={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},Ji=`any-language`,Yi=`any-use-case`,Xi={[qi.TYPESCRIPT]:`ts-crawlee-cheerio`,[qi.JAVASCRIPT]:`js-crawlee-cheerio`,[qi.PYTHON]:`python-crawlee-beautifulsoup`},Zi={[qi.TYPESCRIPT]:`ts-empty`,[qi.JAVASCRIPT]:`js-empty`,[qi.PYTHON]:`python-empty`},Qi=[{cliFlag:`web-scraper`,templateTag:Ki.WEB_SCRAPING,label:`Web scraper`},{cliFlag:`ai-agent`,templateTag:Ki.AI,label:`AI agent`},{cliFlag:`data-pipeline`,templateTag:Ki.INTEGRATION,label:`API & data pipeline`},{cliFlag:`browser-automation`,templateTag:Ki.AUTOMATION,label:`Browser automation`}],$i=[{cliFlag:qi.JAVASCRIPT,templateTag:qi.JAVASCRIPT,label:`JavaScript`,aliases:[`js`]},{cliFlag:qi.TYPESCRIPT,templateTag:qi.TYPESCRIPT,label:`TypeScript`,aliases:[`ts`]},{cliFlag:qi.PYTHON,templateTag:qi.PYTHON,label:`Python`,aliases:[`py`]}],ea=$i.flatMap(e=>[e.cliFlag,...e.aliases]),ta=Qi.map(e=>e.cliFlag);function useCaseFlagToTag(e){return Qi.find(t=>t.cliFlag===e)?.templateTag}function languageFlagToTag(e){return $i.find(t=>t.cliFlag===e||t.aliases.includes(e))?.templateTag}function useCaseLabel(e){return Qi.find(t=>t.templateTag===e)?.label??e}function languageLabel(e){return e===`any-language`?`any language`:$i.find(t=>t.templateTag===e)?.label??e}function getTemplateRecommendation(e,t,n){let r=n!==Ji,i=t!==Yi,matchesLanguage=e=>!r||e.category===n,matchesUseCase=e=>!i||!!e.useCases?.includes(t),isExactMatch=e=>matchesLanguage(e)&&matchesUseCase(e),a=/* @__PURE__ */ new Set,s=[],addCandidates=e=>{for(let t of e)a.has(t.id)||(a.add(t.id),s.push(t))},addCuratedTemplates=t=>{let i=r?[t[n]]:Object.values(t);addCandidates(e.filter(e=>i.includes(e.id)))};return(r||i)&&addCandidates(e.filter(isExactMatch)),addCuratedTemplates(Xi),addCuratedTemplates(Zi),r&&addCandidates(e.filter(matchesLanguage)),i&&addCandidates(e.filter(matchesUseCase)),addCandidates(e),s.map(e=>({template:e,isExactMatch:isExactMatch(e)}))}function buildTemplateChoiceList(e,t,n){let r=e.some(e=>e.isExactMatch),i=e.map(({template:e,isExactMatch:t})=>({template:e,label:formatTemplateLabel(e,n),isExactMatch:t})),a=i.findIndex(e=>!e.isExactMatch);return{rows:i,separatorIndex:r&&a>0?a:null,noExactMatchHint:!r&&i.length>0?`No template matches ${describeSelection(t,n)} exactly — showing the closest alternatives.`:null}}function formatTemplateLabel(e,t){let n=$i.find(t=>t.templateTag===e.category)?.label,r=t===`any-language`||e.category!==t;return n&&r?`${e.label} (${n})`:e.label}function describeSelection(e,t){let n=[];return e!==`any-use-case`&&n.push(useCaseLabel(e)),n.push(languageLabel(t)),n.join(` + `)}async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t,n={}){let r=await t;if(r instanceof Error)throw r;if(e){let t=r.templates.find(t=>t.name===e||t.id===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(r,n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await j.get(n.localReadmeSuffixUrl,{responseType:`text`});await be(e,`\n\n${t.data}`)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function buildNextSteps(e){let{actorName:t,dependenciesInstalled:n,installCommandSuggestion:r,usesStandbyMode:i}=e,a=[`cd "${t}"`];return n||a.push(r||`install dependencies with your package manager`),a.push(i?`apify run --server`:`apify run`),a}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a,usesStandbyMode:s,gitRemote:c}=e,l=`✅ Actor '${t}' created successfully!`,u=buildNextSteps({actorName:t,dependenciesInstalled:n,installCommandSuggestion:a,usesStandbyMode:s});return l+=`\n\nNext steps:\n\n${u.join(`
148
+ `)}),e.exitCode=1,!1}}return!0}};const Gi={STARTER:`STARTER`,WEB_SCRAPING:`WEB_SCRAPING`,INTEGRATION:`INTEGRATION`,AUTOMATION:`AUTOMATION`,AI:`AI`},Ki={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},qi=`any-language`,Ji=`any-use-case`,Yi={[Ki.TYPESCRIPT]:`ts-crawlee-cheerio`,[Ki.JAVASCRIPT]:`js-crawlee-cheerio`,[Ki.PYTHON]:`python-crawlee-beautifulsoup`},Xi={[Ki.TYPESCRIPT]:`ts-empty`,[Ki.JAVASCRIPT]:`js-empty`,[Ki.PYTHON]:`python-empty`},Zi=[{cliFlag:`web-scraper`,templateTag:Gi.WEB_SCRAPING,label:`Web scraper`},{cliFlag:`ai-agent`,templateTag:Gi.AI,label:`AI agent`},{cliFlag:`data-pipeline`,templateTag:Gi.INTEGRATION,label:`API & data pipeline`},{cliFlag:`browser-automation`,templateTag:Gi.AUTOMATION,label:`Browser automation`}],Qi=[{cliFlag:Ki.JAVASCRIPT,templateTag:Ki.JAVASCRIPT,label:`JavaScript`,aliases:[`js`]},{cliFlag:Ki.TYPESCRIPT,templateTag:Ki.TYPESCRIPT,label:`TypeScript`,aliases:[`ts`]},{cliFlag:Ki.PYTHON,templateTag:Ki.PYTHON,label:`Python`,aliases:[`py`]}],$i=Qi.flatMap(e=>[e.cliFlag,...e.aliases]),ea=Zi.map(e=>e.cliFlag);function useCaseFlagToTag(e){return Zi.find(t=>t.cliFlag===e)?.templateTag}function languageFlagToTag(e){return Qi.find(t=>t.cliFlag===e||t.aliases.includes(e))?.templateTag}function useCaseLabel(e){return Zi.find(t=>t.templateTag===e)?.label??e}function languageLabel(e){return e===`any-language`?`any language`:Qi.find(t=>t.templateTag===e)?.label??e}function getTemplateRecommendation(e,t,n){let r=n!==qi,i=t!==Ji,matchesLanguage=e=>!r||e.category===n,matchesUseCase=e=>!i||!!e.useCases?.includes(t),isExactMatch=e=>matchesLanguage(e)&&matchesUseCase(e),a=/* @__PURE__ */ new Set,s=[],addCandidates=e=>{for(let t of e)a.has(t.id)||(a.add(t.id),s.push(t))},addCuratedTemplates=t=>{let i=r?[t[n]]:Object.values(t);addCandidates(e.filter(e=>i.includes(e.id)))};return(r||i)&&addCandidates(e.filter(isExactMatch)),addCuratedTemplates(Yi),addCuratedTemplates(Xi),r&&addCandidates(e.filter(matchesLanguage)),i&&addCandidates(e.filter(matchesUseCase)),addCandidates(e),s.map(e=>({template:e,isExactMatch:isExactMatch(e)}))}function buildTemplateChoiceList(e,t,n){let r=e.some(e=>e.isExactMatch),i=e.map(({template:e,isExactMatch:t})=>({template:e,label:formatTemplateLabel(e,n),isExactMatch:t})),a=i.findIndex(e=>!e.isExactMatch);return{rows:i,separatorIndex:r&&a>0?a:null,noExactMatchHint:!r&&i.length>0?`No template matches ${describeSelection(t,n)} exactly — showing the closest alternatives.`:null}}function formatTemplateLabel(e,t){let n=Qi.find(t=>t.templateTag===e.category)?.label,r=t===`any-language`||e.category!==t;return n&&r?`${e.label} (${n})`:e.label}function describeSelection(e,t){let n=[];return e!==`any-use-case`&&n.push(useCaseLabel(e)),n.push(languageLabel(t)),n.join(` + `)}async function ensureValidActorName(e){return e?(validateActorName(e),e):promptActorName()}async function getTemplateDefinition(e,t,n={}){let r=await t;if(r instanceof Error)throw r;if(e){let t=r.templates.find(t=>t.name===e||t.id===e);if(!t)throw Error(`Could not find the selected template: ${e} in the list of templates.`);return t}return executePrompts(r,n)}async function enhanceReadmeWithLocalSuffix(e,t){let n=await t;if(n instanceof Error)throw n;try{let t=await j.get(n.localReadmeSuffixUrl,{responseType:`text`});await be(e,`\n\n${t.data}`)}catch(e){warning({message:`Could not append local development instructions to README.md. Cause: ${e.message}`})}}function buildNextSteps(e){let{actorName:t,dependenciesInstalled:n,installCommandSuggestion:r,usesStandbyMode:i}=e,a=[`cd "${t}"`];return n||a.push(r||`install dependencies with your package manager`),a.push(i?`apify run --server`:`apify run`),a}function formatCreateSuccessMessage(e){let{actorName:t,dependenciesInstalled:n,postCreate:r,gitRepositoryInitialized:i,installCommandSuggestion:a,usesStandbyMode:s,gitRemote:c}=e,l=`✅ Actor '${t}' created successfully!`,u=buildNextSteps({actorName:t,dependenciesInstalled:n,installCommandSuggestion:a,usesStandbyMode:s});return l+=`\n\nNext steps:\n\n${u.join(`
150
149
  `)}`,c?(l+=`\n\n🌱 Connected to ${c.remoteUrl} — Actor ${c.actorId} builds from this repository.`,c.automaticBuilds===`on`?l+=`
151
150
  🔁 Every push to this repository rebuilds the Actor.`:c.automaticBuilds===`failed`&&(l+=`
152
151
  💡 Tip: Turn on Automatic builds in the Actor's Source settings to rebuild on every push.`)):(l+=`
153
152
 
154
153
  💡 Tip: Use 'apify push' to deploy your Actor to the Apify platform`,i&&(l+=`\n🌱 Git repository initialized in '${t}'. You can now commit and push your Actor to Git.`)),l+=`
155
- 📖 Docs: https://docs.apify.com/platform/actors/development`,r&&(l+=`\n\n${r}`),l}async function executePrompts(e,t){return promptTemplate(e,t.useCase?useCaseFlagToTag(t.useCase)??`any-use-case`:await promptUseCase(),t.language?languageFlagToTag(t.language)??t.language:await promptLanguage())}async function promptActorName(){return await Or({message:`Name of your new Actor:`,validate:validateActorNameForPrompt})}async function promptUseCase(){let e=[...Qi.map(e=>({name:e.label,value:e.templateTag})),new gt,{name:`Any use case`,value:Yi}];return Bi({message:`What do you want to build?`,choices:e,default:Qi[0].templateTag,loop:!1})}async function promptLanguage(){let e=[...$i.map(e=>({name:e.label,value:e.templateTag})),new gt,{name:`Any language`,value:Ji}];return Bi({message:`Choose the programming language of your new Actor:`,choices:e,default:$i[0].templateTag,loop:!1})}async function promptTemplate(e,t,n){let{rows:r,separatorIndex:i,noExactMatchHint:a}=buildTemplateChoiceList(getTemplateRecommendation(e.templates,t,n),t,n);if(r.length===0)throw Error(`No Actor templates are available right now. Please try again later.`);let s=[];return r.forEach((e,t)=>{t===i&&s.push(new gt(`── The templates below don't exactly match your selection ──`)),s.push({name:e.label,value:e.template})}),a&&info({message:a,stdout:!1}),Bi({message:`Choose a template for your new Actor. More info at https://apify.com/templates`,choices:s,default:r[0].template,loop:!1,pageSize:8})}const na=3e5,connectViaConsole=async(e,t,{abortSignal:n,account:r}={})=>{let i=getConsoleUrl(),a=L(),s,c=new Promise(e=>{s=e}),l=createLocalApiServer({corsOrigin:new URL(i).origin,authToken:a,routes:{"POST /api/v1/git-provider-connected":(e,t)=>{t.end(),cliDebugPrint(`git-source`,`connected`,e),s({connected:!0})},"POST /api/v1/exit":(e,n)=>{n.end(),s({stopReason:`connectCancelled`,message:e.isWindowClosed?`Connecting your ${t} account stopped: the Apify Console window was closed.`:`Connecting your ${t} account was canceled in Apify Console.`})}}}),u=setTimeout(()=>s({stopReason:`connectTimedOut`,message:`Connecting your ${t} account did not finish within ${na/6e4} minutes.`}),na);n?.addEventListener(`abort`,()=>s({abandoned:!0}),{once:!0}),l.listen(0);let{port:f}=l.address(),p=new URL(getConsoleIntegrationsUrl(r));p.searchParams.set(`localCliCommand`,`connect-git-provider`),p.searchParams.set(`gitProvider`,e),p.searchParams.set(`localCliPort`,`${f}`),p.searchParams.set(`localCliToken`,a),p.searchParams.set(`localCliApiVersion`,`v1`);try{p.searchParams.set(`localCliComputerName`,encodeURIComponent(Vt()))}catch{}info({message:`Connect your ${t} account to Apify: ${p.href}`}),It(p.href).catch(()=>void 0),info({message:`Waiting for the connection to complete in your browser...`});try{return await c}finally{clearTimeout(u),l.closeAllConnections(),l.close()}},ra=[`apify`,`github`,`gitlab`,`bitbucket`],ia={github:{label:`GitHub`,authorize:{endpoint:`https://github.com/login/oauth/authorize`,defaultClientId:`Iv1.e39b3ed87e74885f`,clientIdEnvVar:`APIFY_GITHUB_APP_CLIENT_ID`,defaultAppName:`apify`,appNameEnvVar:`APIFY_GITHUB_APP_NAME`,appInstallUrl:`https://github.com/apps/{app}/installations/new`,redirectPath:`/actors/new/git/connected?service=github`}},gitlab:{label:`GitLab`},bitbucket:{label:`Bitbucket`}},isGitProvider=e=>Object.hasOwn(ia,e),toGitAccount=({id:e,username:t,organizationOwnerUserId:n})=>({id:e,username:t,organizationOwnerUserId:n}),getGitConnectUrl=(t,n)=>{let{authorize:r}=ia[t];if(!r)return getConsoleIntegrationsUrl(n);let i=new URL(r.redirectPath,getConsoleUrl()),a=getConsoleRoutePrefix(n);a&&i.searchParams.set(`routePrefix`,encodeURIComponent(a));let s=new URL(r.endpoint);return s.searchParams.set(`client_id`,e.env[r.clientIdEnvVar]||r.defaultClientId),s.searchParams.set(`redirect_uri`,i.href),s.href},getAddWorkspaceUrl=(t,n)=>{let{authorize:r}=ia[t];return r?r.appInstallUrl.replace(`{app}`,e.env[r.appNameEnvVar]||r.defaultAppName):getConsoleIntegrationsUrl(n)},promptGitSource=async()=>Bi({message:`How do you want to set up the source code?`,choices:[{name:`Local only`,value:`apify`,description:`Everything stays on this machine and nothing is uploaded. Deploy with "apify push".`},...ra.filter(isGitProvider).map(e=>{let{label:t}=ia[e];return{name:`Host on ${t}`,value:e,description:`Apify creates a private repository on ${t}, clones it into the Actor directory, and creates an Actor that builds from it.`}})],default:`apify`,loop:!1}),parseGitRepoFlag=(e,t)=>{if(!e)return{workspace:void 0,repoName:t};let n=e.lastIndexOf(`/`);if(n===-1)return{workspace:void 0,repoName:e};let r=e.slice(0,n),i=e.slice(n+1);if(!r||!i)throw Error(`Invalid --git-repo "${e}". Use "workspace/name" or just "name".`);return{workspace:r,repoName:i}},apiUrl=({client:e},t)=>`${e.baseUrl}/${t}`,authHeader=({client:e})=>({Authorization:`Bearer ${e.token}`}),fetchGitIntegrations=async e=>{let t=apiUrl(e,`integrations/git`);cliDebugPrint(`git-source`,`GET`,t);let n=await fetch(t,{headers:authHeader(e)}),r=await n.text();if(cliDebugPrint(`git-source`,`GET`,t,`->`,n.status,r.slice(0,400)),!n.ok)throw Error(`Could not read your Git integrations (${n.status} ${n.statusText}).`);return(()=>{try{return JSON.parse(r)}catch{return null}})()?.data??[]},readProviderState=(e,t)=>{let n=e.filter(e=>e.provider===t);return{connected:n.length>0,workspaces:n.flatMap(e=>e.workspaces.map(t=>({...t,providerId:e.id}))),addWorkspaceUrl:n.find(({addWorkspaceUrl:e})=>e)?.addWorkspaceUrl}},aa=2e3,oa=18e4,pollForWorkspaces=async(e,{timeoutMs:t,abortSignal:n,onState:r})=>{let i=Date.now()+t,a=aa,s=null;for(;Date.now()<i;){try{await Oe(a,void 0,{signal:n})}catch{return s}a=Math.min(Math.round(a*1.5),1e4);try{s=await e()}catch(e){cliDebugPrint(`git-source`,`poll failed:`,e);continue}if(s.workspaces.length)return s;await r?.(s)}return s},ensureUsableIntegration=async(e,{client:t,isInteractive:n,account:r})=>{let load=async()=>readProviderState(await fetchGitIntegrations({client:t}),e),i=await load();if(cliDebugPrint(`git-source`,`integrations:`,e,i.connected,`workspaces=${i.workspaces.length}`),i.workspaces.length||!n)return i;let{label:a,authorize:s}=ia[e];if(!i.connected&&!s){let t=new AbortController,n=Date.now(),s=connectViaConsole(e,a,{abortSignal:t.signal,account:r}),c;try{c=await Promise.race([s.then(()=>null),pollForWorkspaces(load,{timeoutMs:na,abortSignal:t.signal})])}finally{t.abort()}if(c?.workspaces.length)return c;let l=await s;if(`stopReason`in l)return warning({message:l.message}),i;if(i=await load(),i.workspaces.length)return i;let u=Math.min(oa,na-(Date.now()-n));return u<aa?i:(info({message:`Waiting for Apify to finish connecting your ${a} account...`}),await pollForWorkspaces(load,{timeoutMs:u})??i)}let c=null,offer=async t=>{let n=t.connected?t.addWorkspaceUrl??getAddWorkspaceUrl(e,r):getGitConnectUrl(e,r);n!==c&&(c=n,info({message:`${t.connected?`Give Apify access to a ${a} account`:`Connect your ${a} account to Apify`}: ${n}`}),await It(n).catch(()=>void 0),info({message:r?.username?`Waiting for authorization to complete in your browser. It connects ${a} to the Apify account ${r.username}.`:`Waiting for authorization to complete in your browser...`}))};return await offer(i),await pollForWorkspaces(load,{timeoutMs:oa,onState:offer})??i},chooseWorkspace=async(e,t,n)=>{if(t){let n=t.toLowerCase(),r=e.find(({id:e,label:t})=>e.toLowerCase()===n||t.toLowerCase()===n);return r?{workspace:r}:{stopReason:`unknownWorkspace`}}return e.length===1?{workspace:e[0]}:n?{workspace:await Bi({message:`Which account should own the repository?`,choices:e.map(e=>({name:e.label,value:e})),loop:!1})}:{stopReason:`ambiguousWorkspace`}};var CreateRemoteRepoError=class extends Error{stopReason;constructor(e,t){super(e),this.stopReason=t,this.name=`CreateRemoteRepoError`}};const sa=/* @__PURE__ */ new Set([`integration-auth-error`,`invalid-git-auth-token`]),withoutUserInfo=e=>{if(!URL.canParse(e))return e;let t=new URL(e);return t.username=``,t.password=``,t.href},createRemoteRepo=async e=>{let{providerId:t,workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a}=e,s=apiUrl(e,`integrations/git/${t}/create-repo`),c=JSON.stringify({workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a});cliDebugPrint(`git-source`,`POST`,s,c);let l=await fetch(s,{method:`POST`,headers:{...authHeader(e),"Content-Type":`application/json`},body:c}),u=await l.text();cliDebugPrint(`git-source`,`POST`,s,`->`,l.status,u.slice(0,400));let f=(()=>{try{return JSON.parse(u)}catch{return null}})();if(l.ok&&f?.data)return{...f.data,httpsUrl:withoutUserInfo(f.data.httpsUrl)};let p=f?.error?.type,m=f?.error?.message||`${l.status} ${l.statusText}`;throw p&&sa.has(p)?new CreateRemoteRepoError(m,`notAuthorized`):p===`invalid-parameter`?new CreateRemoteRepoError(m,`repoNameRejected`):new CreateRemoteRepoError(m,`repoCreateFailed`)},cloneRepo=async(e,t,n)=>{await K(`git`,[`clone`,t,e],{env:n?void 0:{GIT_TERMINAL_PROMPT:`0`,GIT_SSH_COMMAND:`ssh -o BatchMode=yes`}})},createGitActor=async({client:e,actorName:t,gitRepoUrl:n})=>e.actors().create({name:t,versions:[{versionNumber:`0.0`,sourceType:ne.GIT_REPO,gitRepoUrl:n}]}),registerDeploymentKey=async({client:e,providerId:t,actorId:n,repoUrl:r})=>{let i=apiUrl({client:e},`integrations/git/${t}/register-deployment-key`),a=JSON.stringify({actorId:n,repoName:r});cliDebugPrint(`git-source`,`POST`,i,a);let s=await fetch(i,{method:`POST`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:a}),c=await s.text();if(cliDebugPrint(`git-source`,`POST`,i,`->`,s.status,c.slice(0,400)),s.ok)return;let l=(()=>{try{return JSON.parse(c).error?.message}catch{return null}})();throw Error(l||`${s.status} ${s.statusText}`)},enableAutomaticBuilds=async({client:e,providerId:t,actorId:n})=>{let r=apiUrl({client:e},`actors/${n}/versions/0.0/build-on-push`),i=JSON.stringify({providerId:t,enabled:!0});cliDebugPrint(`git-source`,`PUT`,r,i);let a=await fetch(r,{method:`PUT`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:i}),s=await a.text();if(cliDebugPrint(`git-source`,`PUT`,r,`->`,a.status,s.slice(0,400)),a.ok)return;let c=(()=>{try{return JSON.parse(s).error?.message}catch{return null}})();throw Error(c||`${a.status} ${a.statusText}`)},runGitSourceFlow=async({client:e,provider:t,actorDir:n,actorName:r,workspace:i,repoName:a,isPrivate:s,templateArchiveUrl:c,isInteractive:l,account:u,autoBuild:f,customize:p})=>{let m=!1,stopped=(e,t,n={})=>({remoteUrl:null,httpsUrl:null,actorId:null,workspaces:null,scaffolded:m,automaticBuilds:`off`,...n,stopReason:e,error:t instanceof Error?t.message:String(t)}),h;try{h=await ensureUsableIntegration(t,{client:e,isInteractive:l,account:u})}catch(e){return stopped(`lookupFailed`,e)}let{label:g}=ia[t],_=u?.username?`The Apify account ${u.username}`:`Apify`;if(!h.connected)return stopped(`notAuthorized`,/* @__PURE__ */ Error(`${_} is not authorized to access your ${g} account.`));if(!h.workspaces.length)return stopped(`noWorkspace`,/* @__PURE__ */ Error(`${_} has no ${g} account to create the repository in.`));let v=h.workspaces.map(({label:e})=>e),y=v.join(`, `),b=await chooseWorkspace(h.workspaces,i,l);if(`stopReason`in b)return stopped(b.stopReason,/* @__PURE__ */ Error(b.stopReason===`unknownWorkspace`?`"${i}" is not one of your connected accounts (${y}).`:`Several accounts are connected (${y}); pick one with --git-repo <account>/<name>.`),{workspaces:v});let{workspace:x}=b,S;for(;;)try{info({message:`Creating ${s?`private`:`public`} repository ${x.label}/${a} from the template...`}),S=await createRemoteRepo({client:e,providerId:x.providerId,workspace:x.id,repoName:a,isPrivate:s,templateArchiveUrl:c});break}catch(e){if(e instanceof CreateRemoteRepoError&&e.stopReason===`repoNameRejected`&&l){warning({message:e.message}),a=await Or({message:`Choose a different repository name:`,validate:e=>e.trim().length>0||`Enter a repository name.`});continue}return stopped(e instanceof CreateRemoteRepoError?e.stopReason:`repoCreateFailed`,e,{workspaces:v})}let C=null;try{info({message:`Cloning ${S.httpsUrl}...`}),await cloneRepo(n,S.httpsUrl,l),m=!0,await p(n)}catch(e){let t=e.stderr?.trim();C=t?Error(t):e}let w;try{let t=await createGitActor({client:e,actorName:r,gitRepoUrl:S.sshUrl});info({message:`Created Actor ${t.name} on Apify.`}),w=t.id}catch(e){return stopped(`actorCreateFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl})}try{await registerDeploymentKey({client:e,providerId:x.providerId,actorId:w,repoUrl:S.htmlUrl})}catch(e){return stopped(`deploymentKeyFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w})}let T=`off`;if(f)try{await enableAutomaticBuilds({client:e,providerId:x.providerId,actorId:w}),T=`on`,info({message:`Turned on automatic builds.`})}catch(e){T=`failed`,warning({message:`Automatic builds stay off: ${e instanceof Error?e.message:String(e)}`})}else info({message:`Automatic builds stay off, so a push does not rebuild the Actor.`});return C?stopped(`gitSetupFailed`,C,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,automaticBuilds:T}):{remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,workspaces:v,stopReason:null,error:null,scaffolded:!0,automaticBuilds:T}},getGitStopUrl=(e,t,n)=>t===`notAuthorized`?getGitConnectUrl(e,n):t===`noWorkspace`?getAddWorkspaceUrl(e,n):null,buildGitSourceNextSteps=({actorName:e,stopReason:t,provider:n,remoteUrl:r,httpsUrl:i,repoName:a,scaffolded:s,actorId:c,account:l})=>{let u=`cd "${e}"`;switch(t){case`lookupFailed`:return[`Re-run with APIFY_CLI_DEBUG=1 to see the failing request`];case`notAuthorized`:return[`Connect your ${ia[n].label} account to Apify: ${getGitConnectUrl(n,l)}`,`then re-run apify create`];case`noWorkspace`:return[`Give Apify access to a ${ia[n].label} account: ${getAddWorkspaceUrl(n,l)}`,`then re-run apify create`];case`unknownWorkspace`:case`ambiguousWorkspace`:return[`Re-run naming the account: --git-repo <account>/${a}`];case`repoNameRejected`:return[`Re-run with a different repository name: --git-repo <account>/<other-name>`,`The name has to be free, and to use only letters, numbers, hyphens and underscores`];case`repoCreateFailed`:return[`Re-run apify create to try again`];case`gitSetupFailed`:return s?[u,`Apply the local configuration by hand: the error above says what failed`]:[`git clone ${i} "${e}"`,`Or clone over SSH, if you have a key for the provider: git clone ${r} "${e}"`,u];case`actorCreateFailed`:return[u,`Create an Actor from ${r} in Apify Console`];case`deploymentKeyFailed`:return[...s?[u]:[`git clone ${i} "${e}"`,u],`Add the Apify deploy key in the Actor's Source settings before building: ${getConsoleUrl()}/actors/${c}`]}},logGitSourceOutcome=(e,t)=>{e.stopReason&&(warning({message:`${e.scaffolded?`Actor scaffolded, but the Git setup did not finish`:e.actorId?`Actor created, but the clone failed`:`The Actor was not created: the Git setup stopped`}: ${e.error}`}),info({message:`Next steps:\n${t.map(e=>` ${e}`).join(`
156
- `)}`}))};async function getInstallCommandSuggestion(e){let t=null;return await(await useCwdProject({cwd:e})).inspectAsync(async n=>{if(n.type===0){let[r,i,a,s]=await Promise.all([W(B(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),W(B(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),W(B(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),W(B(e,`bun.lock`)).then(()=>!0).catch(()=>!1)]);t=r?`yarn install`:i?`pnpm install`:a||s||n.runtime?.pmName===`bun`?`bun install`:n.runtime?.pmName===`deno`?`deno install --node-modules-dir`:`npm install`}else(n.type===1||n.type===2)&&(t=n.packageManager===`uv`?`uv sync`:`python -m pip install -r requirements.txt`)}),t}var CreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name, then guides you through what you want to build, a language, a template, and how the source code is set up when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively, with guided prompts for the name, use case, language, template, and source.`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{description:`Create non-interactively with explicit name and template.`,command:`apify create my-actor --template js-crawlee-cheerio`},{description:`Create without installing dependencies (faster; run install yourself later).`,command:`apify create my-actor --template python-start --skip-dependency-install`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:X.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Rt} to find available template names.`,required:!1}),"use-case":X.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:ta,required:!1}),language:X.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:ea,required:!1}),"skip-dependency-install":X.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":X.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":X.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":X.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:X.string({description:`Where the Actor source code lives. With "apify", the code stays on your machine and nothing is uploaded. You can still deploy your Actor with "apify push". With a Git provider, Apify creates a private repository from the template on your connected account, clones the repository into the Actor directory, and builds the Actor from it.`,choices:[...ra],required:!1}),"git-repo":X.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),"auto-build":X.string({description:`Whether a push to the repository rebuilds the Actor. On by default. Turning it on registers a push webhook on the new repository, which needs admin rights on it. Only used when --source is a Git provider.`,choices:[`on`,`off`],required:!1}),origin:X.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:Q.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:u}=this.flags,{templateArchiveUrl:f}=this.flags,p=!1,m=!n&&!f;if(l&&(!t||m)){let e=[...t?[]:[`the Actor name as an argument`],...m?[`--template <name>`]:[]],n=m?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let h=this.flags.source,g=Lt().catch(e=>/* @__PURE__ */ Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let _=e.cwd(),v=B(_,t);for(;;){let e=await W(v).catch(()=>null),n=e&&await Ce(v).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),v=B(_,t)}else{e||await U(v,{recursive:!0});break}}let y=null,b=null;if(this.telemetryData.create={fromArchiveUrl:!!f,origin:c},!f){let e=await getTemplateDefinition(n,g,{useCase:r,language:i});({archiveUrl:f,messages:y}=e),b=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(p=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(p=!0);let{isTTY:x}=await useStdin(),S=x&&!ve&&!l;h??=S?await promptGitSource():`apify`;let C=isGitProvider(h)?h:null;if(this.telemetryData.create.source=h,C&&s)throw Error(`--source ${h} clones a git repository, so --skip-git-init cannot apply.`);if(!C&&u)throw Error(`--git-repo only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(!C&&this.flags.autoBuild)throw Error(`--auto-build only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(C&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${h}.`);let w=C?{provider:C,client:await getLoggedClientOrThrow(),account:toGitAccount(await getCurrentUserInfo()),autoBuild:this.flags.autoBuild!==`off`,...parseGitRepoFlag(u,t)}:null,T=!1,applyLocalConfig=async e=>{let n=getJsonFileContent(B(e,q));T=!!n?.usesStandbyMode,await setLocalConfig(Object.assign(n||$t,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};C||(await downloadAndUnzip({url:f,pathTo:v}),await applyLocalConfig(v),await enhanceReadmeWithLocalSuffix(B(v,`README.md`),g));let E=B(v,`package.json`),D=null;w&&(D=await runGitSourceFlow({provider:w.provider,actorDir:v,actorName:t,workspace:w.workspace,repoName:w.repoName,isPrivate:!0,templateArchiveUrl:f,client:w.client,isInteractive:S,account:w.account,autoBuild:w.autoBuild,customize:applyLocalConfig}));let O=!1;a||await(await useCwdProject({cwd:v})).inspectAsync(async n=>{let r=Ve(an);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await ke(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:v}}),O=!0;return}if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${cn} or higher to be able to run Python Actors locally.`})}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(E,{name:t});let e=[`install`];if(p)switch(i.pmName){case`npm`:Be(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:v},overrideCommand:i.pmName}),O=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${cn} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${cn} or higher to be able to run Python Actors locally.`});return}let t=B(v,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:v}}),i=(await usePythonRuntime({cwd:v,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:v}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:v}}),O=!0;break}}});let k={success:!0},A=await W(B(_,`.git`)).catch(()=>null),j=await W(B(v,`.git`)).catch(()=>null),M=D!==null&&!D.scaffolded,N=!s&&!A&&!j&&!M;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:v}})}catch(e){k={success:!1,error:e}}let P=O?null:await getInstallCommandSuggestion(v),ee=N&&k.success||!!j;D?.stopReason&&(e.exitCode=1);let F=w&&D?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:D.stopReason,provider:w.provider,remoteUrl:D.remoteUrl,httpsUrl:D.httpsUrl,repoName:w.repoName,scaffolded:D.scaffolded,actorId:D.actorId,account:w.account}):buildNextSteps({actorName:t,dependenciesInstalled:O,installCommandSuggestion:P,usesStandbyMode:T}),te=!D?.stopReason;l?printJsonToStdout({dir:v,actorJsonPath:B(v,q),template:b,source:h,nextSteps:F,postCreate:y?.postCreate??null,gitRepositoryInitialized:ee,remote:D?.remoteUrl??null,automaticBuilds:D?.automaticBuilds??null,actorId:D?.actorId??null,stopReason:D?.stopReason??null,error:D?.error??null,gitConnectUrl:C?getGitStopUrl(C,D?.stopReason??null,w?.account):null,workspaces:D?.workspaces??null}):te&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:O,postCreate:y?.postCreate??null,gitRepositoryInitialized:ee,installCommandSuggestion:P,usesStandbyMode:T,gitRemote:D?.remoteUrl&&D.actorId?{remoteUrl:D.remoteUrl,actorId:D.actorId,automaticBuilds:D.automaticBuilds}:null})})),N&&!k.success&&(warning({message:`Failed to initialize git repository: ${k.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),D&&!l&&logGitSourceOutcome(D,F)}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getCurrentUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates a new dataset for storing structured data on your account.`;static examples=[{description:`Create an unnamed dataset.`,command:`apify datasets create`},{description:`Create a named dataset.`,command:`apify datasets create my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-create`;static args={datasetName:Q.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);this.flags.json?printJsonToStdout(r):success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const ca={[A.JSON]:`application/json`,[A.JSONL]:`application/jsonl`,[A.CSV]:`text/csv`,[A.HTML]:`text/html`,[A.RSS]:`application/rss+xml`,[A.XML]:`application/xml`,[A.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{static name=`get-items`;static enableProfileFlag=!0;static description=`Retrieves dataset items in specified format (JSON, CSV, etc).`;static examples=[{description:`Print all items from a dataset as JSON.`,command:`apify datasets get-items <datasetId>`},{description:`Export the first 100 items as CSV to a file.`,command:`apify datasets get-items <datasetId> --format csv --limit 100 > items.csv`},{description:`Paginate: skip the first 500 items, return the next 500.`,command:`apify datasets get-items <datasetId> --offset 500 --limit 500`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-get-items`;static flags={limit:X.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:X.integer({description:`The offset in the dataset where to start getting items.`}),format:X.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(ca),default:A.JSON})};static args={datasetId:Q.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:ca[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
157
- `)}async tryToGetDataset(e,t){let n=await e.dataset(t).get().catch(()=>void 0);if(n)return{dataset:n,datasetClient:e.dataset(n.id)};let r=await getCurrentUserInfo(),i=await e.dataset(`${r.username}/${t}`).get().catch(()=>void 0);return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};function getUserPlanPricing(e){let t=Reflect.get(e,`planPricing`);return t?Reflect.get(t,`chargeableServiceUnitPricesUsd`):null}const la=new $({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var DatasetsInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Prints information about a specific dataset.`;static examples=[{description:`Show dataset metadata (item count, size, timestamps).`,command:`apify datasets info <datasetId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-info`;static args={storeId:Q.string({description:`The dataset store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetDataset(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset: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.cleanItemCount||0).toLocaleString(`en-US`),h=(i.itemCount||0).toLocaleString(`en-US`),g=[`${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`))}`],_=`Items: ${t.bold(m)} ${t.gray(`clean`)} / ${t.bold(h)} ${t.gray(`total`)}\nOperations: ${g.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)}`;_+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else _+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})}`;let v=[`Dataset ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(J.display(i.createdAt))}`,`Modified: ${t.bold(J.display(i.modifiedAt))}`].join(`
154
+ 📖 Docs: https://docs.apify.com/platform/actors/development`,r&&(l+=`\n\n${r}`),l}async function executePrompts(e,t){return promptTemplate(e,t.useCase?useCaseFlagToTag(t.useCase)??`any-use-case`:await promptUseCase(),t.language?languageFlagToTag(t.language)??t.language:await promptLanguage())}async function promptActorName(){return await Or({message:`Name of your new Actor:`,validate:validateActorNameForPrompt})}async function promptUseCase(){let e=[...Zi.map(e=>({name:e.label,value:e.templateTag})),new gt,{name:`Any use case`,value:Ji}];return Bi({message:`What do you want to build?`,choices:e,default:Zi[0].templateTag,loop:!1})}async function promptLanguage(){let e=[...Qi.map(e=>({name:e.label,value:e.templateTag})),new gt,{name:`Any language`,value:qi}];return Bi({message:`Choose the programming language of your new Actor:`,choices:e,default:Qi[0].templateTag,loop:!1})}async function promptTemplate(e,t,n){let{rows:r,separatorIndex:i,noExactMatchHint:a}=buildTemplateChoiceList(getTemplateRecommendation(e.templates,t,n),t,n);if(r.length===0)throw Error(`No Actor templates are available right now. Please try again later.`);let s=[];return r.forEach((e,t)=>{t===i&&s.push(new gt(`── The templates below don't exactly match your selection ──`)),s.push({name:e.label,value:e.template})}),a&&info({message:a,stdout:!1}),Bi({message:`Choose a template for your new Actor. More info at https://apify.com/templates`,choices:s,default:r[0].template,loop:!1,pageSize:8})}const ta=3e5,connectViaConsole=async(e,t,{abortSignal:n,account:r}={})=>{let i=getConsoleUrl(),a=L(),s,c=new Promise(e=>{s=e}),l=createLocalApiServer({corsOrigin:new URL(i).origin,authToken:a,routes:{"POST /api/v1/git-provider-connected":(e,t)=>{t.end(),cliDebugPrint(`git-source`,`connected`,e),s({connected:!0})},"POST /api/v1/exit":(e,n)=>{n.end(),s({stopReason:`connectCancelled`,message:e.isWindowClosed?`Connecting your ${t} account stopped: the Apify Console window was closed.`:`Connecting your ${t} account was canceled in Apify Console.`})}}}),u=setTimeout(()=>s({stopReason:`connectTimedOut`,message:`Connecting your ${t} account did not finish within ${ta/6e4} minutes.`}),ta);n?.addEventListener(`abort`,()=>s({abandoned:!0}),{once:!0}),l.listen(0);let{port:f}=l.address(),p=new URL(getConsoleIntegrationsUrl(r));p.searchParams.set(`localCliCommand`,`connect-git-provider`),p.searchParams.set(`gitProvider`,e),p.searchParams.set(`localCliPort`,`${f}`),p.searchParams.set(`localCliToken`,a),p.searchParams.set(`localCliApiVersion`,`v1`);try{p.searchParams.set(`localCliComputerName`,encodeURIComponent(Vt()))}catch{}info({message:`Connect your ${t} account to Apify: ${p.href}`}),It(p.href).catch(()=>void 0),info({message:`Waiting for the connection to complete in your browser...`});try{return await c}finally{clearTimeout(u),l.closeAllConnections(),l.close()}},na=[`apify`,`github`,`gitlab`,`bitbucket`],ra={github:{label:`GitHub`,authorize:{endpoint:`https://github.com/login/oauth/authorize`,defaultClientId:`Iv1.e39b3ed87e74885f`,clientIdEnvVar:`APIFY_GITHUB_APP_CLIENT_ID`,defaultAppName:`apify`,appNameEnvVar:`APIFY_GITHUB_APP_NAME`,appInstallUrl:`https://github.com/apps/{app}/installations/new`,redirectPath:`/actors/new/git/connected?service=github`}},gitlab:{label:`GitLab`},bitbucket:{label:`Bitbucket`}},isGitProvider=e=>Object.hasOwn(ra,e),toGitAccount=({id:e,username:t,organizationOwnerUserId:n})=>({id:e,username:t,organizationOwnerUserId:n}),getGitConnectUrl=(t,n)=>{let{authorize:r}=ra[t];if(!r)return getConsoleIntegrationsUrl(n);let i=new URL(r.redirectPath,getConsoleUrl()),a=getConsoleRoutePrefix(n);a&&i.searchParams.set(`routePrefix`,encodeURIComponent(a));let s=new URL(r.endpoint);return s.searchParams.set(`client_id`,e.env[r.clientIdEnvVar]||r.defaultClientId),s.searchParams.set(`redirect_uri`,i.href),s.href},getAddWorkspaceUrl=(t,n)=>{let{authorize:r}=ra[t];return r?r.appInstallUrl.replace(`{app}`,e.env[r.appNameEnvVar]||r.defaultAppName):getConsoleIntegrationsUrl(n)},promptGitSource=async()=>Bi({message:`How do you want to set up the source code?`,choices:[{name:`Local only`,value:`apify`,description:`Everything stays on this machine and nothing is uploaded. Deploy with "apify push".`},...na.filter(isGitProvider).map(e=>{let{label:t}=ra[e];return{name:`Host on ${t}`,value:e,description:`Apify creates a private repository on ${t}, clones it into the Actor directory, and creates an Actor that builds from it.`}})],default:`apify`,loop:!1}),parseGitRepoFlag=(e,t)=>{if(!e)return{workspace:void 0,repoName:t};let n=e.lastIndexOf(`/`);if(n===-1)return{workspace:void 0,repoName:e};let r=e.slice(0,n),i=e.slice(n+1);if(!r||!i)throw Error(`Invalid --git-repo "${e}". Use "workspace/name" or just "name".`);return{workspace:r,repoName:i}},apiUrl=({client:e},t)=>`${e.baseUrl}/${t}`,authHeader=({client:e})=>({Authorization:`Bearer ${e.token}`}),fetchGitIntegrations=async e=>{let t=apiUrl(e,`integrations/git`);cliDebugPrint(`git-source`,`GET`,t);let n=await fetch(t,{headers:authHeader(e)}),r=await n.text();if(cliDebugPrint(`git-source`,`GET`,t,`->`,n.status,r.slice(0,400)),!n.ok)throw Error(`Could not read your Git integrations (${n.status} ${n.statusText}).`);return(()=>{try{return JSON.parse(r)}catch{return null}})()?.data??[]},readProviderState=(e,t)=>{let n=e.filter(e=>e.provider===t);return{connected:n.length>0,workspaces:n.flatMap(e=>e.workspaces.map(t=>({...t,providerId:e.id}))),addWorkspaceUrl:n.find(({addWorkspaceUrl:e})=>e)?.addWorkspaceUrl}},ia=2e3,aa=18e4,pollForWorkspaces=async(e,{timeoutMs:t,abortSignal:n,onState:r})=>{let i=Date.now()+t,a=ia,s=null;for(;Date.now()<i;){try{await Oe(a,void 0,{signal:n})}catch{return s}a=Math.min(Math.round(a*1.5),1e4);try{s=await e()}catch(e){cliDebugPrint(`git-source`,`poll failed:`,e);continue}if(s.workspaces.length)return s;await r?.(s)}return s},ensureUsableIntegration=async(e,{client:t,isInteractive:n,account:r})=>{let load=async()=>readProviderState(await fetchGitIntegrations({client:t}),e),i=await load();if(cliDebugPrint(`git-source`,`integrations:`,e,i.connected,`workspaces=${i.workspaces.length}`),i.workspaces.length||!n)return i;let{label:a,authorize:s}=ra[e];if(!i.connected&&!s){let t=new AbortController,n=Date.now(),s=connectViaConsole(e,a,{abortSignal:t.signal,account:r}),c;try{c=await Promise.race([s.then(()=>null),pollForWorkspaces(load,{timeoutMs:ta,abortSignal:t.signal})])}finally{t.abort()}if(c?.workspaces.length)return c;let l=await s;if(`stopReason`in l)return warning({message:l.message}),i;if(i=await load(),i.workspaces.length)return i;let u=Math.min(aa,ta-(Date.now()-n));return u<ia?i:(info({message:`Waiting for Apify to finish connecting your ${a} account...`}),await pollForWorkspaces(load,{timeoutMs:u})??i)}let c=null,offer=async t=>{let n=t.connected?t.addWorkspaceUrl??getAddWorkspaceUrl(e,r):getGitConnectUrl(e,r);n!==c&&(c=n,info({message:`${t.connected?`Give Apify access to a ${a} account`:`Connect your ${a} account to Apify`}: ${n}`}),await It(n).catch(()=>void 0),info({message:r?.username?`Waiting for authorization to complete in your browser. It connects ${a} to the Apify account ${r.username}.`:`Waiting for authorization to complete in your browser...`}))};return await offer(i),await pollForWorkspaces(load,{timeoutMs:aa,onState:offer})??i},chooseWorkspace=async(e,t,n)=>{if(t){let n=t.toLowerCase(),r=e.find(({id:e,label:t})=>e.toLowerCase()===n||t.toLowerCase()===n);return r?{workspace:r}:{stopReason:`unknownWorkspace`}}return e.length===1?{workspace:e[0]}:n?{workspace:await Bi({message:`Which account should own the repository?`,choices:e.map(e=>({name:e.label,value:e})),loop:!1})}:{stopReason:`ambiguousWorkspace`}};var CreateRemoteRepoError=class extends Error{stopReason;constructor(e,t){super(e),this.stopReason=t,this.name=`CreateRemoteRepoError`}};const oa=/* @__PURE__ */ new Set([`integration-auth-error`,`invalid-git-auth-token`]),withoutUserInfo=e=>{if(!URL.canParse(e))return e;let t=new URL(e);return t.username=``,t.password=``,t.href},createRemoteRepo=async e=>{let{providerId:t,workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a}=e,s=apiUrl(e,`integrations/git/${t}/create-repo`),c=JSON.stringify({workspace:n,repoName:r,isPrivate:i,templateArchiveUrl:a});cliDebugPrint(`git-source`,`POST`,s,c);let l=await fetch(s,{method:`POST`,headers:{...authHeader(e),"Content-Type":`application/json`},body:c}),u=await l.text();cliDebugPrint(`git-source`,`POST`,s,`->`,l.status,u.slice(0,400));let f=(()=>{try{return JSON.parse(u)}catch{return null}})();if(l.ok&&f?.data)return{...f.data,httpsUrl:withoutUserInfo(f.data.httpsUrl)};let p=f?.error?.type,m=f?.error?.message||`${l.status} ${l.statusText}`;throw p&&oa.has(p)?new CreateRemoteRepoError(m,`notAuthorized`):p===`invalid-parameter`?new CreateRemoteRepoError(m,`repoNameRejected`):new CreateRemoteRepoError(m,`repoCreateFailed`)},cloneRepo=async(e,t,n)=>{await K(`git`,[`clone`,t,e],{env:n?void 0:{GIT_TERMINAL_PROMPT:`0`,GIT_SSH_COMMAND:`ssh -o BatchMode=yes`}})},createGitActor=async({client:e,actorName:t,gitRepoUrl:n})=>e.actors().create({name:t,versions:[{versionNumber:`0.0`,sourceType:ne.GIT_REPO,gitRepoUrl:n}]}),registerDeploymentKey=async({client:e,providerId:t,actorId:n,repoUrl:r})=>{let i=apiUrl({client:e},`integrations/git/${t}/register-deployment-key`),a=JSON.stringify({actorId:n,repoName:r});cliDebugPrint(`git-source`,`POST`,i,a);let s=await fetch(i,{method:`POST`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:a}),c=await s.text();if(cliDebugPrint(`git-source`,`POST`,i,`->`,s.status,c.slice(0,400)),s.ok)return;let l=(()=>{try{return JSON.parse(c).error?.message}catch{return null}})();throw Error(l||`${s.status} ${s.statusText}`)},enableAutomaticBuilds=async({client:e,providerId:t,actorId:n})=>{let r=apiUrl({client:e},`actors/${n}/versions/0.0/build-on-push`),i=JSON.stringify({providerId:t,enabled:!0});cliDebugPrint(`git-source`,`PUT`,r,i);let a=await fetch(r,{method:`PUT`,headers:{...authHeader({client:e}),"Content-Type":`application/json`},body:i}),s=await a.text();if(cliDebugPrint(`git-source`,`PUT`,r,`->`,a.status,s.slice(0,400)),a.ok)return;let c=(()=>{try{return JSON.parse(s).error?.message}catch{return null}})();throw Error(c||`${a.status} ${a.statusText}`)},runGitSourceFlow=async({client:e,provider:t,actorDir:n,actorName:r,workspace:i,repoName:a,isPrivate:s,templateArchiveUrl:c,isInteractive:l,account:u,autoBuild:f,customize:p})=>{let m=!1,stopped=(e,t,n={})=>({remoteUrl:null,httpsUrl:null,actorId:null,workspaces:null,scaffolded:m,automaticBuilds:`off`,...n,stopReason:e,error:t instanceof Error?t.message:String(t)}),h;try{h=await ensureUsableIntegration(t,{client:e,isInteractive:l,account:u})}catch(e){return stopped(`lookupFailed`,e)}let{label:g}=ra[t],_=u?.username?`The Apify account ${u.username}`:`Apify`;if(!h.connected)return stopped(`notAuthorized`,/* @__PURE__ */ Error(`${_} is not authorized to access your ${g} account.`));if(!h.workspaces.length)return stopped(`noWorkspace`,/* @__PURE__ */ Error(`${_} has no ${g} account to create the repository in.`));let v=h.workspaces.map(({label:e})=>e),y=v.join(`, `),b=await chooseWorkspace(h.workspaces,i,l);if(`stopReason`in b)return stopped(b.stopReason,/* @__PURE__ */ Error(b.stopReason===`unknownWorkspace`?`"${i}" is not one of your connected accounts (${y}).`:`Several accounts are connected (${y}); pick one with --git-repo <account>/<name>.`),{workspaces:v});let{workspace:x}=b,S;for(;;)try{info({message:`Creating ${s?`private`:`public`} repository ${x.label}/${a} from the template...`}),S=await createRemoteRepo({client:e,providerId:x.providerId,workspace:x.id,repoName:a,isPrivate:s,templateArchiveUrl:c});break}catch(e){if(e instanceof CreateRemoteRepoError&&e.stopReason===`repoNameRejected`&&l){warning({message:e.message}),a=await Or({message:`Choose a different repository name:`,validate:e=>e.trim().length>0||`Enter a repository name.`});continue}return stopped(e instanceof CreateRemoteRepoError?e.stopReason:`repoCreateFailed`,e,{workspaces:v})}let C=null;try{info({message:`Cloning ${S.httpsUrl}...`}),await cloneRepo(n,S.httpsUrl,l),m=!0,await p(n)}catch(e){let t=e.stderr?.trim();C=t?Error(t):e}let w;try{let t=await createGitActor({client:e,actorName:r,gitRepoUrl:S.sshUrl});info({message:`Created Actor ${t.name} on Apify.`}),w=t.id}catch(e){return stopped(`actorCreateFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl})}try{await registerDeploymentKey({client:e,providerId:x.providerId,actorId:w,repoUrl:S.htmlUrl})}catch(e){return stopped(`deploymentKeyFailed`,e,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w})}let T=`off`;if(f)try{await enableAutomaticBuilds({client:e,providerId:x.providerId,actorId:w}),T=`on`,info({message:`Turned on automatic builds.`})}catch(e){T=`failed`,warning({message:`Automatic builds stay off: ${e instanceof Error?e.message:String(e)}`})}else info({message:`Automatic builds stay off, so a push does not rebuild the Actor.`});return C?stopped(`gitSetupFailed`,C,{workspaces:v,remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,automaticBuilds:T}):{remoteUrl:S.sshUrl,httpsUrl:S.httpsUrl,actorId:w,workspaces:v,stopReason:null,error:null,scaffolded:!0,automaticBuilds:T}},getGitStopUrl=(e,t,n)=>t===`notAuthorized`?getGitConnectUrl(e,n):t===`noWorkspace`?getAddWorkspaceUrl(e,n):null,buildGitSourceNextSteps=({actorName:e,stopReason:t,provider:n,remoteUrl:r,httpsUrl:i,repoName:a,scaffolded:s,actorId:c,account:l})=>{let u=`cd "${e}"`;switch(t){case`lookupFailed`:return[`Re-run with APIFY_CLI_DEBUG=1 to see the failing request`];case`notAuthorized`:return[`Connect your ${ra[n].label} account to Apify: ${getGitConnectUrl(n,l)}`,`then re-run apify create`];case`noWorkspace`:return[`Give Apify access to a ${ra[n].label} account: ${getAddWorkspaceUrl(n,l)}`,`then re-run apify create`];case`unknownWorkspace`:case`ambiguousWorkspace`:return[`Re-run naming the account: --git-repo <account>/${a}`];case`repoNameRejected`:return[`Re-run with a different repository name: --git-repo <account>/<other-name>`,`The name has to be free, and to use only letters, numbers, hyphens and underscores`];case`repoCreateFailed`:return[`Re-run apify create to try again`];case`gitSetupFailed`:return s?[u,`Apply the local configuration by hand: the error above says what failed`]:[`git clone ${i} "${e}"`,`Or clone over SSH, if you have a key for the provider: git clone ${r} "${e}"`,u];case`actorCreateFailed`:return[u,`Create an Actor from ${r} in Apify Console`];case`deploymentKeyFailed`:return[...s?[u]:[`git clone ${i} "${e}"`,u],`Add the Apify deploy key in the Actor's Source settings before building: ${getConsoleUrl()}/actors/${c}`]}},logGitSourceOutcome=(e,t)=>{e.stopReason&&(warning({message:`${e.scaffolded?`Actor scaffolded, but the Git setup did not finish`:e.actorId?`Actor created, but the clone failed`:`The Actor was not created: the Git setup stopped`}: ${e.error}`}),info({message:`Next steps:\n${t.map(e=>` ${e}`).join(`
155
+ `)}`}))};async function getInstallCommandSuggestion(e){let t=null;return await(await useCwdProject({cwd:e})).inspectAsync(async n=>{if(n.type===0){let[r,i,a,s]=await Promise.all([W(B(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),W(B(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),W(B(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),W(B(e,`bun.lock`)).then(()=>!0).catch(()=>!1)]);t=r?`yarn install`:i?`pnpm install`:a||s||n.runtime?.pmName===`bun`?`bun install`:n.runtime?.pmName===`deno`?`deno install --node-modules-dir`:`npm install`}else(n.type===1||n.type===2)&&(t=n.packageManager===`uv`?`uv sync`:`python -m pip install -r requirements.txt`)}),t}var CreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.`;static group=`Local Actor Development`;static interactive=!0;static interactiveNote=`Prompts for an Actor name, then guides you through what you want to build, a language, a template, and how the source code is set up when they are not provided. To run non-interactively, pass the name and --template; --source defaults to "apify". Use --use-case and --language to narrow the template list.`;static examples=[{description:`Create a new Actor project interactively, with guided prompts for the name, use case, language, template, and source.`,command:`apify create`},{description:`Narrow the guided template list by use case and language.`,command:`apify create my-actor --use-case web-scraper --language python`},{description:`Create non-interactively with explicit name and template.`,command:`apify create my-actor --template js-crawlee-cheerio`},{description:`Create without installing dependencies (faster; run install yourself later).`,command:`apify create my-actor --template python-start --skip-dependency-install`},{description:`Host the source code on GitHub. Apify creates the repository and builds the Actor from it.`,command:`apify create my-actor --template js-crawlee-cheerio --source github`},{description:`Name the account and the repository to create, instead of being asked.`,command:`apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-create`;static flags={template:X.string({char:`t`,description:`Template for the Actor. If not provided, the command will prompt for it. Visit ${Rt} to find available template names.`,required:!1}),"use-case":X.string({char:`u`,description:`Filter templates by use case. Ignored when --template is provided. To see the use cases each template supports, run "apify templates ls".`,choices:ea,required:!1}),language:X.string({char:`l`,description:`Filter templates by programming language. Ignored when --template is provided.`,choices:$i,required:!1}),"skip-dependency-install":X.boolean({description:`Skip installing Actor dependencies.`,required:!1}),"template-archive-url":X.string({description:`Actor template archive url. Useful for developing new templates.`,required:!1,hidden:!0}),"omit-optional-deps":X.boolean({aliases:[`no-optional`],description:`Skip installing optional dependencies.`,required:!1}),"skip-git-init":X.boolean({description:`Skip initializing a git repository in the Actor directory.`,required:!1}),source:X.string({description:`Where the Actor source code lives. With "apify", the code stays on your machine and nothing is uploaded. You can still deploy your Actor with "apify push". With a Git provider, Apify creates a private repository from the template on your connected account, clones the repository into the Actor directory, and builds the Actor from it.`,choices:[...na],required:!1}),"git-repo":X.string({description:`Repository to create, as "workspace/name" — a workspace being an account or organization you have given Apify access to. A bare value is read as the name, not the workspace. The name defaults to the Actor name, and the workspace is asked for when you have more than one. List yours with "apify api integrations/git". Only used when --source is a Git provider.`,required:!1}),"auto-build":X.string({description:`Whether a push to the repository rebuilds the Actor. On by default. Turning it on registers a push webhook on the new repository, which needs admin rights on it. Only used when --source is a Git provider.`,choices:[`on`,`off`],required:!1}),origin:X.string({description:`Where the command was invoked from. Used for funnel telemetry.`,choices:[`console`,`cli`],default:`cli`,required:!1,hidden:!0})};static args={actorName:Q.string({required:!1,description:`Name of the Actor and its directory.`})};static enableJsonFlag=!0;async run(){let{actorName:t}=this.args,{template:n,useCase:r,language:i,skipDependencyInstall:a,skipGitInit:s,origin:c,json:l,gitRepo:u}=this.flags,{templateArchiveUrl:f}=this.flags,p=!1,m=!n&&!f;if(l&&(!t||m)){let e=[...t?[]:[`the Actor name as an argument`],...m?[`--template <name>`]:[]],n=m?` Run "apify templates ls" to list template names.`:``;throw Error(`--json runs non-interactively. Pass ${e.join(` and `)}.${n}`)}let h=this.flags.source,g=Lt().catch(e=>/* @__PURE__ */ Error(`Could not fetch template list from server. Cause: ${e?.message}`));t=await ensureValidActorName(t);let _=e.cwd(),v=B(_,t);for(;;){let e=await W(v).catch(()=>null),n=e&&await Ce(v).then(e=>e.length>0).catch(()=>!1);if(e?.isDirectory()&&n){let e=`Cannot create new Actor, directory '${t}' already exists. Provide a different name. To create a local Actor environment inside an existing directory, use "apify init".`;if(l)throw Error(e);error({message:e}),t=await ensureValidActorName(),v=B(_,t)}else{e||await U(v,{recursive:!0});break}}let y=null,b=null;if(this.telemetryData.create={fromArchiveUrl:!!f,origin:c},!f){let e=await getTemplateDefinition(n,g,{useCase:r,language:i});({archiveUrl:f,messages:y}=e),b=e.id,this.telemetryData.create.templateId=e.id,this.telemetryData.create.templateName=e.name,this.telemetryData.create.templateLanguage=e.category,`skipOptionalDeps`in e&&(p=e.skipOptionalDeps)}this.flags.omitOptionalDeps&&(p=!0);let{isTTY:x}=await useStdin(),S=x&&!ve&&!l;h??=S?await promptGitSource():`apify`;let C=isGitProvider(h)?h:null;if(this.telemetryData.create.source=h,C&&s)throw Error(`--source ${h} clones a git repository, so --skip-git-init cannot apply.`);if(!C&&u)throw Error(`--git-repo only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(!C&&this.flags.autoBuild)throw Error(`--auto-build only applies to a Git source, so add --source github|gitlab|bitbucket or drop it.`);if(C&&this.flags.templateArchiveUrl)throw Error(`--template-archive-url is not supported with --source ${h}.`);let w=C?{provider:C,client:await getLoggedClientOrThrow(),account:toGitAccount(await getCurrentUserInfo()),autoBuild:this.flags.autoBuild!==`off`,...parseGitRepoFlag(u,t)}:null,T=!1,applyLocalConfig=async e=>{let n=getJsonFileContent(B(e,q));T=!!n?.usesStandbyMode,await setLocalConfig(Object.assign(n||$t,{name:t}),e),await setLocalEnv(e),await createPrefilledInputFileFromInputSchema(e)};C||(await downloadAndUnzip({url:f,pathTo:v}),await applyLocalConfig(v),await enhanceReadmeWithLocalSuffix(B(v,`README.md`),g));let E=B(v,`package.json`),D=null;w&&(D=await runGitSourceFlow({provider:w.provider,actorDir:v,actorName:t,workspace:w.workspace,repoName:w.repoName,isPrivate:!0,templateArchiveUrl:f,client:w.client,isInteractive:S,account:w.account,autoBuild:w.autoBuild,customize:applyLocalConfig}));let O=!1;a||await(await useCwdProject({cwd:v})).inspectAsync(async n=>{let r=Ve(an);if((n.type===1||n.type===2)&&n.packageManager===`uv`){let e=await ke(`uv`,{nothrow:!0});if(!e){warning({message:`This Actor uses uv to manage its dependencies, but the uv executable was not found. Install uv (https://docs.astral.sh/uv/getting-started/installation/), then run "uv sync" in the Actor directory.`});return}info({message:`Installing dependencies with "uv sync"...`}),await execWithLog({cmd:e,args:[`sync`],opts:{cwd:v}}),O=!0;return}if(!n.runtime){switch(n.type){case 0:warning({message:`No Node.js detected! Please install Node.js ${r} or higher to be able to run Node.js Actors locally.`});break;case 2:case 1:warning({message:`No Python detected! Please install Python ${cn} or higher to be able to run Python Actors locally.`})}return}let{runtime:i}=n;switch(n.type){case 0:{isNodeVersionSupported(i.version)||warning({message:`You are running Node.js version ${i.version}, which is no longer supported. Please upgrade to Node.js version ${r} or later.`}),await updateLocalJson(E,{name:t});let e=[`install`];if(p)switch(i.pmName){case`npm`:Be(i.pmVersion,`7.0.0`)?e.push(`--omit=optional`):e.push(`--no-optional`);break;case`bun`:e.push(`--omit=optional`);break;case`deno`:e.push(`--node-modules-dir`)}await execWithLog({cmd:i.pmPath,args:e,opts:{cwd:v},overrideCommand:i.pmName}),O=!0;break}case 1:case 2:{if(!isPythonVersionSupported(i.version)){warning({message:`Python Actors require Python ${cn} or higher, but you have Python ${i.version}!`}),warning({message:`Please install Python ${cn} or higher to be able to run Python Actors locally.`});return}let t=B(v,`.venv`);info({message:`Python version ${i.version} detected.`}),info({message:`Creating a virtual environment in "${t}" and installing dependencies from "requirements.txt"...`}),e.env.VIRTUAL_ENV||(await execWithLog({cmd:i.executablePath,args:[`-m`,`venv`,`--prompt`,`.`,`.venv`],opts:{cwd:v}}),i=(await usePythonRuntime({cwd:v,force:!0})).unwrap(),n.runtime=i),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`--upgrade`,`pip`,`setuptools`,`wheel`],opts:{cwd:v}}),await execWithLog({cmd:i.executablePath,args:[`-m`,`pip`,`install`,`--no-cache-dir`,`--no-warn-script-location`,`-r`,`requirements.txt`],opts:{cwd:v}}),O=!0;break}}});let k={success:!0},A=await W(B(_,`.git`)).catch(()=>null),j=await W(B(v,`.git`)).catch(()=>null),M=D!==null&&!D.scaffolded,N=!s&&!A&&!j&&!M;if(N)try{await execWithLog({cmd:`git`,args:[`init`],opts:{cwd:v}})}catch(e){k={success:!1,error:e}}let P=O?null:await getInstallCommandSuggestion(v),ee=N&&k.success||!!j;D?.stopReason&&(e.exitCode=1);let F=w&&D?.stopReason?buildGitSourceNextSteps({actorName:t,stopReason:D.stopReason,provider:w.provider,remoteUrl:D.remoteUrl,httpsUrl:D.httpsUrl,repoName:w.repoName,scaffolded:D.scaffolded,actorId:D.actorId,account:w.account}):buildNextSteps({actorName:t,dependenciesInstalled:O,installCommandSuggestion:P,usesStandbyMode:T}),te=!D?.stopReason;l?printJsonToStdout({dir:v,actorJsonPath:B(v,q),template:b,source:h,nextSteps:F,postCreate:y?.postCreate??null,gitRepositoryInitialized:ee,remote:D?.remoteUrl??null,automaticBuilds:D?.automaticBuilds??null,actorId:D?.actorId??null,stopReason:D?.stopReason??null,error:D?.error??null,gitConnectUrl:C?getGitStopUrl(C,D?.stopReason??null,w?.account):null,workspaces:D?.workspaces??null}):te&&(simpleLog({message:``}),success({message:formatCreateSuccessMessage({actorName:t,dependenciesInstalled:O,postCreate:y?.postCreate??null,gitRepositoryInitialized:ee,installCommandSuggestion:P,usesStandbyMode:T,gitRemote:D?.remoteUrl&&D.actorId?{remoteUrl:D.remoteUrl,actorId:D.actorId,automaticBuilds:D.automaticBuilds}:null})})),N&&!k.success&&(warning({message:`Failed to initialize git repository: ${k.error.message}`}),warning({message:`You can manually run "git init" in the Actor directory if needed.`})),D&&!l&&logGitSourceOutcome(D,F)}};async function tryToGetStorage(e,t,n){let r=await e[n](t).get().catch(()=>void 0);if(r)return{[n]:r,[`${n}Client`]:e[n](r.id)};let i=await getCurrentUserInfo(),a=await e[n](`${i.username}/${t}`).get().catch(()=>void 0);return a?{[n]:a,[`${n}Client`]:e[n](a.id)}:null}async function tryToGetDataset(e,t){return tryToGetStorage(e,t,`dataset`)}async function tryToGetKeyValueStore(e,t){return tryToGetStorage(e,t,`keyValueStore`)}var DatasetsCreateCommand=class extends ApifyCommand{static name=`create`;static enableProfileFlag=!0;static description=`Creates a new dataset for storing structured data on your account.`;static examples=[{description:`Create an unnamed dataset.`,command:`apify datasets create`},{description:`Create a named dataset.`,command:`apify datasets create my-dataset`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-create`;static args={datasetName:Q.string({description:`Optional name for the Dataset.`,required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,n=await getLoggedClientOrThrow();if(e&&await tryToGetDataset(n,e)){error({message:`A Dataset with this name already exists!`});return}let r=await n.datasets().getOrCreate(e);this.flags.json?printJsonToStdout(r):success({message:`Dataset with ID ${t.yellow(r.id)}${e?` (called ${t.yellow(e)})`:``} was created.`,stdout:!0})}};const sa={[A.JSON]:`application/json`,[A.JSONL]:`application/jsonl`,[A.CSV]:`text/csv`,[A.HTML]:`text/html`,[A.RSS]:`application/rss+xml`,[A.XML]:`application/xml`,[A.XLSX]:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};var DatasetsGetItems=class extends ApifyCommand{static name=`get-items`;static enableProfileFlag=!0;static description=`Retrieves dataset items in specified format (JSON, CSV, etc).`;static examples=[{description:`Print all items from a dataset as JSON.`,command:`apify datasets get-items <datasetId>`},{description:`Export the first 100 items as CSV to a file.`,command:`apify datasets get-items <datasetId> --format csv --limit 100 > items.csv`},{description:`Paginate: skip the first 500 items, return the next 500.`,command:`apify datasets get-items <datasetId> --offset 500 --limit 500`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-get-items`;static flags={limit:X.integer({description:`The amount of elements to get from the dataset. By default, it will return all available items.`}),offset:X.integer({description:`The offset in the dataset where to start getting items.`}),format:X.string({description:`The format of the returned output. By default, it is set to 'json'.`,choices:Object.keys(sa),default:A.JSON})};static args={datasetId:Q.string({description:`The ID of the Dataset to export the items for.`,required:!0})};async run(){let{limit:e,offset:t,format:n}=this.flags,{datasetId:r}=this.args,i=await getLoggedClientOrThrow(),a=await this.tryToGetDataset(i,r);if(!a){error({message:`Dataset with ID "${r}" not found.`});return}let{datasetClient:s}=a;process.stdout.write(``);let c=await s.downloadItems(n,{limit:e,offset:t});simpleLog({message:sa[n]??`application/octet-stream`}),process.stdout.write(c),process.stdout.write(`
156
+ `)}async tryToGetDataset(e,t){let n=await e.dataset(t).get().catch(()=>void 0);if(n)return{dataset:n,datasetClient:e.dataset(n.id)};let r=await getCurrentUserInfo(),i=await e.dataset(`${r.username}/${t}`).get().catch(()=>void 0);return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};function getUserPlanPricing(e){let t=Reflect.get(e,`planPricing`);return t?Reflect.get(t,`chargeableServiceUnitPricesUsd`):null}const ca=new $({allColumns:[`Row1`,`Row2`],mandatoryColumns:[`Row1`,`Row2`]});var DatasetsInfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Prints information about a specific dataset.`;static examples=[{description:`Show dataset metadata (item count, size, timestamps).`,command:`apify datasets info <datasetId>`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-datasets-info`;static args={storeId:Q.string({description:`The dataset store ID to print information about.`,required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,n=await getLoggedClientOrThrow(),r=await tryToGetDataset(n,e);if(!r){error({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset: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.cleanItemCount||0).toLocaleString(`en-US`),h=(i.itemCount||0).toLocaleString(`en-US`),g=[`${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`))}`],_=`Items: ${t.bold(m)} ${t.gray(`clean`)} / ${t.bold(h)} ${t.gray(`total`)}\nOperations: ${g.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)}`;_+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})} / ${t.gray(`${i} per month`)}`}}else _+=`\nStorage size: ${prettyPrintBytes({bytes:u,shortBytes:!0,precision:1})}`;let v=[`Dataset ID: ${t.bgGray(i.id)}`,`Name: ${i.name?t.bgGray(i.name):t.bold(t.italic(`Unnamed`))}`,`Created: ${t.bold(J.display(i.createdAt))}`,`Modified: ${t.bold(J.display(i.modifiedAt))}`].join(`
158
157
  `),y=t.bold(`—`);i.actRunId&&(y=c?t.bgBlue(c.id):t.italic(t.gray(`Run removed`)));let b=t.bold(`—`);s&&(b=t.blue(s.title||s.name));let x=t.bold(`—`);l&&(x=t.blue(l.title||l.name));let S=[`Run: ${y}`,`Actor: ${b}`,`Task: ${x}`].join(`
159
- `);la.pushRow({Row1:v,Row2:S});let C=la.render(2).split(`
158
+ `);ca.pushRow({Row1:v,Row2:S});let C=ca.render(2).split(`
160
159
  `).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(`
161
160
  `),``,_].join(`
162
- `),stdout:!0})}};const ua=new $({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:X.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:X.integer({description:`Number of datasets that will be listed.`,default:20}),desc:X.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:X.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`);ua.pushRow({"Dataset ID":e.id,Created:J.display(e.createdAt),Items:`${e.itemCount}`,Modified:J.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:ua.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:Q.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Q.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:X.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Q.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Q.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:Q.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 Z({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 da=`https://apify.github.io/input-schema-editor-react/`,fa=new URL(da).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:Q.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 '${q}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
163
- `}),info({message:`Editing input schema at "${t}"...`});let n=L(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:fa,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=p(t)?v(t,{encoding:`utf-8`}):`{}
161
+ `),stdout:!0})}};const la=new $({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:X.integer({description:`Number of datasets that will be skipped.`,default:0}),limit:X.integer({description:`Number of datasets that will be listed.`,default:20}),desc:X.boolean({description:`Sorts datasets in descending order.`,default:!1}),unnamed:X.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`);la.pushRow({"Dataset ID":e.id,Created:J.display(e.createdAt),Items:`${e.itemCount}`,Modified:J.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:la.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:Q.string({required:!0,description:`The dataset ID or name to push the objects to.`,ignoreStdin:!0}),item:Q.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:X.boolean({description:`Removes the unique name of the dataset.`})};static args={nameOrId:Q.string({description:`The dataset ID or name to delete.`,required:!0}),newName:Q.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:Q.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 Z({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 ua=`https://apify.github.io/input-schema-editor-react/`,da=new URL(ua).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:Q.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 '${q}' is not yet supported.`);warning({message:`This command is still experimental and might break at any time. Use at your own risk.
162
+ `}),info({message:`Editing input schema at "${t}"...`});let n=L(),r=` `,i=!0,a=createLocalApiServer({corsOrigin:da,authToken:n,routes:{"GET /api/v1/input-schema":(e,n)=>{let a;try{a=p(t)?v(t,{encoding:`utf-8`}):`{}
164
163
  `,a.length>3&&(r=qt(a).indent||r),a&&(i=a[a.length-1]===`
165
164
  `),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+=`
166
- `);let s=z(t);p(s)||g(s,{recursive:!0}),E(t,a,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let c=`${da}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${c}"...`}),await It(c)}};const pa=B(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=z(Jt(import.meta.url));for(;;){let t=B(e,pa);if(p(t))return v(t,`utf-8`);let n=z(e);if(n===e)return null;e=n}}var HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Q.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:X.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=Y.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
167
- `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getCurrentUserInfo(),n=await resolveAuth(),r={username:e.username,userId:e.id,"token source":In[n.source]};for(let[e,n]of Object.entries(r))console.log(`${t.gray(e)}: ${t.bold(n)}`)}};const ma=[`.dockerignore`,`.gitignore`],ha=Jt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Yt.walk(e,async(r,i,s)=>{if(i===e)return;let c=V(e,i),l=c.split(ge).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(ge),f=B(t,l);if(s.isDirectory())return p(f)||g(f),merge(i,f);c.includes(`.template`)?E(B(t,l.replace(`.template`,``)),Xt.compile(v(i,`utf8`))(n.bindings)):p(f)&&ma.includes(pe(l))?a(f,v(i)):u(i,f)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await Bi({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${V(e,t).split(ge).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await Lt(zt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);p(ha)&&C(ha,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:ha}),info({message:`Wrapping the Scrapy project...`}),await merge(ha,e,{bindings:r});let s=new mt;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=f(B(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
165
+ `);let s=z(t);p(s)||g(s,{recursive:!0}),E(t,a,{encoding:`utf-8`,flag:`w+`}),n.end(),info({message:`Input schema saved to disk.`})}catch(e){let t=`Saving input schema failed with error: ${e.message}`;error({message:t}),n.status(500),n.send(t)}},"POST /api/v1/exit":(e,t)=>{e.isWindowClosed?info({message:`Editor closed, finishing...`}):info({message:`Editing finished, you can close the editor.`}),t.end(),a.close(()=>success({message:`Done.`}))}}});a.listen(0);let{port:s}=a.address();info({message:`Listening for messages from input schema editor on port ${s}...`});let c=`${ua}?localCliPort=${s}&localCliToken=${n}&localCliApiVersion=v1`;info({message:`Opening input schema editor at "${c}"...`}),await It(c)}};const fa=B(`skills`,`apify`,`SKILL.md`);function readApifySkill(){if(typeof __APIFY_CLI_SKILL__==`string`&&__APIFY_CLI_SKILL__)return __APIFY_CLI_SKILL__;let e=z(Jt(import.meta.url));for(;;){let t=B(e,fa);if(p(t))return v(t,`utf-8`);let n=z(e);if(n===e)return null;e=n}}var HelpCommand=class extends ApifyCommand{static name=`help`;static description=`Prints out help about a command, or all available commands.`;static hidden=!0;static args={commandString:Q.string({required:!1,description:`The command to get help for.`,catchAll:!0})};static flags={skill:X.boolean({description:"Print the Apify CLI agent skill (guidance for driving `apify` from agents).",default:!1})};async run(){let{commandString:e}=this.args;if(this.flags.skill){let e=readApifySkill();if(!e){error({message:`Could not find the Apify CLI skill file.`});return}simpleLog({stdout:!0,message:e.trimEnd()});return}if(!e||e.toLowerCase().startsWith(`help`)){let e=renderMainHelpMenu(this.entrypoint);console.log(e);return}let n=e.toLowerCase(),r=Y.get(n);if(!r){let r=useCommandSuggestions(n),i=t.gray(`Command ${t.whiteBright(e)} not found`);r.length&&(i+=`
166
+ `,i+=t.gray(`Did you mean: ${r.map(e=>t.whiteBright(e)).join(`, `)}?`)),error({message:i});return}let i=renderHelpForCommand(r);console.log(i)}},InfoCommand=class extends ApifyCommand{static name=`info`;static enableProfileFlag=!0;static description=`Prints details about your currently authenticated Apify account.`;static group=`Apify Console`;static examples=[{description:`Print the currently logged-in account username and user ID.`,command:`apify info`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-info`;async run(){await getLoggedClientOrThrow();let e=await getCurrentUserInfo(),n=await resolveAuth(),r={username:e.username,userId:e.id,"token source":In[n.source]};for(let[e,n]of Object.entries(r))console.log(`${t.gray(e)}: ${t.bold(n)}`)}};const pa=[`.dockerignore`,`.gitignore`],ma=Jt(new URL(`./templates/python-scrapy`,import.meta.url));async function merge(e,t,n={bindings:{}}){await Yt.walk(e,async(r,i,s)=>{if(i===e)return;let c=V(e,i),l=c.split(ge).map(e=>{if(e.startsWith(`{`)&&e.endsWith(`}`)){e=e.replace(`{`,``).replace(`}`,``);let t=n.bindings[e];if(!t)throw Error(`Binding for ${e} not found.`);return t}return e}).join(ge),f=B(t,l);if(s.isDirectory())return p(f)||g(f),merge(i,f);c.includes(`.template`)?E(B(t,l.replace(`.template`,``)),Xt.compile(v(i,`utf8`))(n.bindings)):p(f)&&pa.includes(pe(l))?a(f,v(i)):u(i,f)})}async function wrapScrapyProject({projectPath:e}){e||=`.`;let t=new ScrapyProjectAnalyzer(e);if(t.configuration.hasSection(`apify`))throw Error(`The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?`);await t.init();let n=await Bi({message:`Pick the Scrapy spider you want to wrap:`,choices:t.getAvailableSpiders().map((e,t)=>({name:`${e.class_name} (${e.pathname})`,value:t}))});function translatePathToRelativeModuleName(t){return`.${V(e,t).split(ge).slice(1).join(`.`).replace(`.py`,``)}`}let r={botName:sanitizeActorName(t.settings.BOT_NAME),scrapy_settings_module:t.configuration.get(`settings`,`default`),apify_module_path:`${t.settings.BOT_NAME}.apify`,spider_class_name:t.getAvailableSpiders()[n].class_name,spider_module_name:`${translatePathToRelativeModuleName(t.getAvailableSpiders()[n].pathname)}`,projectFolder:t.settings.BOT_NAME},i=await Lt(zt);info({message:`Downloading the latest Scrapy wrapper template...`});let{archiveUrl:a}=i.templates.find(({id:e})=>e===`python-scrapy`);p(ma)&&C(ma,{recursive:!0}),await downloadAndUnzip({url:a,pathTo:ma}),info({message:`Wrapping the Scrapy project...`}),await merge(ma,e,{bindings:r});let s=new mt;s.addSection(`apify`),s.set(`apify`,`mainpy_location`,t.settings.BOT_NAME);let c=f(B(e,`scrapy.cfg`),{flags:`a`});await new Promise(e=>{c.on(`open`,t=>{c.write(`
168
167
  `,()=>{s.write(t),e()})})}),success({message:`The Scrapy project has been wrapped successfully.`})}var WrapScrapyCommand=class extends ApifyCommand{static name=`init-wrap-scrapy`;static description=`Wraps your existing Scrapy project to work like an Apify Actor.
169
168
 
170
169
  It adds the following features:
@@ -174,18 +173,18 @@ It adds the following features:
174
173
  ...
175
174
  `;static args={path:Q.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.
176
175
  If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
177
- Creates the '${q}' file and the '${Qt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Qt}' 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:Q.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:X.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=pe(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 Z({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 '${q}', 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 Or({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={...$t,...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":Q.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":Q.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Q.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 Z({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":X.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Q.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Q.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 ga=new $({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:Q.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(J.display(i.createdAt))}`,`Modified: ${t.bold(J.display(i.modifiedAt))}`].join(`
176
+ Creates the '${q}' file and the '${Qt}' directory in the current directory, but does not touch any other existing files or directories.\n\nWARNING: Overwrites existing '${Qt}' 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:Q.string({required:!1,description:`Name of the Actor. If not provided, you will be prompted for it.`})};static flags={...YesFlag(),dockerfile:X.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=pe(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 Z({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 '${q}', 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 Or({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={...$t,...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":Q.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":Q.string({description:`The key-value store ID to delete the value from.`,required:!0}),itemKey:Q.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 Z({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":X.boolean({description:`Only return the content type of the specified key.`,default:!1})};static args={keyValueStoreId:Q.string({description:`The key-value store ID to get the value from.`,required:!0}),itemKey:Q.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 ha=new $({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:Q.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(J.display(i.createdAt))}`,`Modified: ${t.bold(J.display(i.modifiedAt))}`].join(`
178
177
  `),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(`
179
- `);ga.pushRow({Row1:_,Row2:x});let S=ga.render(2).split(`
178
+ `);ha.pushRow({Row1:_,Row2:x});let S=ha.render(2).split(`
180
179
  `).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(`
181
180
  `),``,g].join(`
182
- `),stdout:!0})}};const _a=new $({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:X.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":X.string({description:`The key to start the list from.`})};static args={storeId:Q.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)_a.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:_a.render(1),stdout:!0})}}};const va=new $({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:X.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:X.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:X.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:X.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;va.pushRow({"Store ID":e.id,Created:J.display(e.createdAt),Modified:J.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:va.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:X.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Q.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Q.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:Q.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 Z({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":X.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Q.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Q.string({description:`The key of the item in the key-value store.`,required:!0}),value:Q.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
+ `),stdout:!0})}};const ga=new $({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:X.integer({description:`The maximum number of keys to return.`,default:20}),"exclusive-start-key":X.string({description:`The key to start the list from.`})};static args={storeId:Q.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)ga.pushRow({Key:e.key,Size:prettyPrintBytes({bytes:e.size,shortBytes:!0,precision:0})});simpleLog({message:ga.render(1),stdout:!0})}}};const _a=new $({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:X.integer({description:`Number of key-value stores that will be skipped.`,default:0}),limit:X.integer({description:`Number of key-value stores that will be listed.`,default:20}),desc:X.boolean({description:`Sorts key-value stores in descending order.`,default:!1}),unnamed:X.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;_a.pushRow({"Store ID":e.id,Created:J.display(e.createdAt),Modified:J.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:_a.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:X.boolean({description:`Removes the unique name of the key-value store.`})};static args={keyValueStoreNameOrId:Q.string({description:`The key-value store ID or name to delete.`,required:!0}),newName:Q.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:Q.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 Z({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":X.string({description:`The MIME content type of the value. By default, "application/json" is assumed.`,default:`application/json`})};static args={storeId:Q.string({description:`The key-value store ID to set the value in.`,required:!0}),itemKey:Q.string({description:`The key of the item in the key-value store.`,required:!0}),value:Q.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.
183
182
 
184
183
  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 Z({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 Se(t,`utf-8`):``,c=s.trim(),l;if(c){let e;try{e=Mt.parse(s)}catch(e){let n=e instanceof Error?e.message.split(`
185
- `)[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=Mt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Mt.stringify(e,{mode:`json`,indent:2})}\n`}await U(z(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await G(u,l,`utf-8`),await we(u,t)}catch(e){throw await Te(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 ya=`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(`
186
- `)})}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 ke(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await K(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=B(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:ya,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 ${ya} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,ya,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:ya,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=B(r,`.codex`,`config.toml`),a=[`mcp`,`add`,ya,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${ya}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
187
- `);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>`})},ba={"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)})})},xa=Object.keys(ba);function isSupportedClient(e){return e in ba}const Sa=/* @__PURE__ */ new Set([`codex`]);function clientNeedsToken(e){return!Sa.has(e)}function getClientHandler(e){return ba[e]}const Ca=6e4,wa=60*Ca,Ta=24*wa;function plural(e,t){return`${e} ${e===1?t:`${t}s`}`}function describeExpiry(e){return e<=0?`has already expired`:e<Ca?`expires in under a minute`:e<wa?`expires in about ${plural(Math.round(e/Ca),`minute`)}`:e<Ta?`expires in about ${plural(Math.round(e/wa),`hour`)}`:`expires in about ${plural(Math.round(e/Ta),`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.
188
- 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(ve||!s)throw e.exitCode=5,Error(`${a}\nRe-run with --yes to write the expiring token anyway.`);return warning({message:a}),Z({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:Q.string({required:!0,description:`Target MCP client. One of: ${xa.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry, and accept a token that's about to expire, without prompting.`),token:X.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 personal one from Apify Console.`}),url:X.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:X.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: ${xa.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=>`
184
+ `)[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=Mt.update(s,e)}else{let e={[n]:{[r]:i}};l=`${Mt.stringify(e,{mode:`json`,indent:2})}\n`}await U(z(t),{recursive:!0});let u=`${t}.${e.pid}.tmp`;try{await G(u,l,`utf-8`),await we(u,t)}catch(e){throw await Te(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 va=`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(`
185
+ `)})}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 ke(t,{nothrow:!0}))return error({message:s}),e.exitCode=250,!1;run({message:a});try{await K(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=B(c,...n);await mergeServerEntry({filePath:l,topLevelKey:`mcpServers`,entryKey:va,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 ${va} "${e}" --header "Authorization: Bearer ${t}"`;await runCliInstall({binary:`claude`,clientLabel:`Claude Code`,token:t,args:[`mcp`,`add`,`--transport`,`http`,`--scope`,`user`,va,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:va,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=B(r,`.codex`,`config.toml`),a=[`mcp`,`add`,va,`--url`,n,`--bearer-token-env-var`,`APIFY_TOKEN`],s=[`[mcp_servers.${va}]`,`url = "${n}"`,`bearer_token_env_var = "APIFY_TOKEN"`].join(`
186
+ `);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>`})},ya={"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)})})},ba=Object.keys(ya);function isSupportedClient(e){return e in ya}const xa=/* @__PURE__ */ new Set([`codex`]);function clientNeedsToken(e){return!xa.has(e)}function getClientHandler(e){return ya[e]}const Sa=6e4,Ca=60*Sa,wa=24*Ca;function plural(e,t){return`${e} ${e===1?t:`${t}s`}`}function describeExpiry(e){return e<=0?`has already expired`:e<Sa?`expires in under a minute`:e<Ca?`expires in about ${plural(Math.round(e/Sa),`minute`)}`:e<wa?`expires in about ${plural(Math.round(e/Ca),`hour`)}`:`expires in about ${plural(Math.round(e/wa),`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.
187
+ 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(ve||!s)throw e.exitCode=5,Error(`${a}\nRe-run with --yes to write the expiring token anyway.`);return warning({message:a}),Z({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:Q.string({required:!0,description:`Target MCP client. One of: ${ba.join(`, `)}.`})};static flags={...YesFlag(`Overwrite an existing 'apify' entry, and accept a token that's about to expire, without prompting.`),token:X.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 personal one from Apify Console.`}),url:X.string({description:`Apify MCP server URL.`,default:`https://mcp.apify.com`}),tools:X.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: ${ba.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=>`
189
188
  (async () => {
190
189
  const [nodeModule, process, path, fs] = await Promise.all([
191
190
  import('node:module'),
@@ -223,7 +222,7 @@ try:
223
222
  print(${e}.__version__)
224
223
  except:
225
224
  print('n/a')
226
- `,Ea={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}),Ie;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}),Ie;let i=Ea[r]?.(t);if(!i)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:n,moduleName:t}),Ie;try{let r=await K(n.runtime.executablePath,i,{cwd:e.cwd(),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}),Ie):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:n,moduleName:t,version:r.stdout.trim()}),Re(r.stdout.trim()))}catch(e){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:n,moduleName:t,error:e}),Ie}}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)}),Da=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:Da}),r=Date.parse(lookUpProfile(t).profile?.expiresAt??``)-Date.now();return Number.isFinite(r)&&r<Da&&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.
225
+ `,Ta={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}),Ie;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}),Ie;let i=Ta[r]?.(t);if(!i)return cliDebugPrint(`useModuleVersion`,{status:`no_version_script_found`,project:n,moduleName:t}),Ie;try{let r=await K(n.runtime.executablePath,i,{cwd:e.cwd(),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}),Ie):(cliDebugPrint(`useModuleVersion`,{status:`success`,project:n,moduleName:t,version:r.stdout.trim()}),Re(r.stdout.trim()))}catch(e){return cliDebugPrint(`useModuleVersion`,{status:`failed_to_run_version_script`,project:n,moduleName:t,error:e}),Ie}}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)}),Ea=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:Ea}),r=Date.parse(lookUpProfile(t).profile?.expiresAt??``)-Date.now();return Number.isFinite(r)&&r<Ea&&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.
227
226
  Stores data in local '${Qt}' 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:X.boolean({char:`p`,description:`Whether to purge the default request queue, dataset and key-value store before the run starts.
228
227
  For crawlee projects, this is the default behavior, and the flag is optional.
229
228
  Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,exclusive:[`resurrect`]}),resurrect:X.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:X.string({description:`Optional entrypoint for running with injected environment variables.
@@ -233,9 +232,9 @@ Use \`--no-purge\` to keep the storage folder intact.`,required:!1,default:!0,ex
233
232
  `;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:
234
233
  `}if(t){let e={...s,...t.input},a=Tt(c,r,e);if(a.length>0)throw Error(`${f}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
235
234
  `)}`);let l=`${ur}${n}`,u=B(i,`${l}.json`);return await U(i,{recursive:!0}),await writeInputRecord(i,l,e),{tempInputKey:l,tempInputFilePath:u}}if(!l)return await U(i,{recursive:!0}),await writeInputRecord(i,n,s),{existingInput:l,inputKey:n,inputFilePath:u,writtenAt:Date.now()};if(lt.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=Tt(c,r,t);if(a.length>0)throw Error(`${f}${a.map(e=>` - ${e.message.replace(`Field input.`,`Field `)}`).join(`
236
- `)}`);let u=`${ur}${n}`,p=B(i,`${u}.json`);return await writeInputRecord(i,u,t),{tempInputKey:u,tempInputFilePath:p}}return null}};const Oa=[P.READY,P.RUNNING],ka=[P.ABORTING,P.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:Q.string({required:!0,description:`The run ID to abort.`})};static flags={force:X.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(!Oa.includes(n.status))ka.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 Aa=new $({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),ja={"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:Q.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:X.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(Aa.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${J.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${J.display(r.finishedAt)} (took ${t.gray(Sr.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${Sr.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(`
237
- `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n)for(let e of Object.keys(ja))Aa.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});else for(let[e,r]of Object.entries(ja)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:Aa.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`:Aa.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:Aa.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:Q.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 Ma=new $({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:X.integer({description:`Number of runs that will be skipped.`,default:0}),limit:X.integer({description:`Number of runs that will be listed.`,default:10}),desc:X.boolean({description:`Sort runs in descending order.`,default:!1}),compact:X.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Q.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}.`});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(`${Sr.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${Sr.format(r,void 0,{left:``})}`)}Ma.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":yr.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(Ma.render(+!i)),simpleLog({message:f.join(`
238
- `),stdout:!0})}};const Na=[P.SUCCEEDED,P.FAILED,P.ABORTED,P.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:Q.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(!Na.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 Pa=[P.SUCCEEDED,P.FAILED,P.ABORTED,P.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:Q.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(!Pa.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 Z({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).
235
+ `)}`);let u=`${ur}${n}`,p=B(i,`${u}.json`);return await writeInputRecord(i,u,t),{tempInputKey:u,tempInputFilePath:p}}return null}};const Da=[P.READY,P.RUNNING],Oa=[P.ABORTING,P.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:Q.string({required:!0,description:`The run ID to abort.`})};static flags={force:X.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(!Da.includes(n.status))Oa.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 ka=new $({allColumns:[``,`Unit`,`USD Amount`],mandatoryColumns:[``,`Unit`,`USD Amount`],columnAlignments:{Unit:`right`,"USD Amount":`right`}}),Aa={"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:Q.string({required:!0,description:`The run ID to print information about.`})};static flags={verbose:X.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(ka.render(0)),f.push(``),f.push(`${t.yellow(`Started`)}: ${J.display(r.startedAt)}`),r.finishedAt)f.push(`${t.yellow(`Finished`)}: ${J.display(r.finishedAt)} (took ${t.gray(Sr.format(r.stats.durationMillis))})`);else{let e=Date.now()-r.startedAt.getTime();f.push(`${t.yellow(`Finished`)}: ${t.gray(`Running for ${Sr.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(`
236
+ `),stdout:!0})}addDetailedUsage(e){let{usage:t,usageUsd:n}=e;if(!t||!n)for(let e of Object.keys(Aa))ka.pushRow({"":e,Unit:`N/A`,"USD Amount":`N/A`});else for(let[e,r]of Object.entries(Aa)){let i=t[r]??0,a=n[r]??0;switch(r){case`ACTOR_COMPUTE_UNITS`:ka.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`:ka.pushRow({"":e,Unit:prettyPrintBytes({bytes:i*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break;default:ka.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:Q.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 ja=new $({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:X.integer({description:`Number of runs that will be skipped.`,default:0}),limit:X.integer({description:`Number of runs that will be listed.`,default:10}),desc:X.boolean({description:`Sort runs in descending order.`,default:!1}),compact:X.boolean({description:`Display a compact table.`,default:!1,char:`c`})};static args={actorId:Q.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}.`});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(`${Sr.format(r,void 0,{left:``})}`)}else{let r=Date.now()-e.startedAt.getTime();n=t.gray(`Running for ${Sr.format(r,void 0,{left:``})}`)}ja.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":yr.display(e.startedAt),Took:n,"Build No.":e.buildNumber,Origin:e.meta.origin??`UNKNOWN`})}f.push(ja.render(+!i)),simpleLog({message:f.join(`
237
+ `),stdout:!0})}};const Ma=[P.SUCCEEDED,P.FAILED,P.ABORTED,P.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:Q.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(!Ma.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 Na=[P.SUCCEEDED,P.FAILED,P.ABORTED,P.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:Q.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(!Na.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 Z({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).
239
238
  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:Q.string({required:!0,description:`The run ID to wait for.`})};static flags={timeout:X.integer({char:`t`,description:`Maximum seconds to wait before giving up. Without this flag the command waits indefinitely.`,required:!1}),"poll-interval":X.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:F.RUN,maxWaitMillis:n?n*1e3:void 0,pollIntervalMillis:r?r*1e3:void 0}),l=s,u=consoleRunUrl(l.actId,l.id),f=l.status===P.SUCCEEDED,p=exitCodeForWaitResult({job:s,timedOutWaiting:c},F.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.
240
239
  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()}},RuntimeConnectCommand=class extends ApifyCommand{static name=`connect`;static description=`Sends all Apify CLI commands to the local Actor runtime instead of the Apify platform. Applies in every terminal until you run 'apify runtime disconnect'. Your login stays the same.
241
240
  In a shell where APIFY_CLIENT_BASE_URL or APIFY_CONSOLE_URL is set, those variables override this setting.
@@ -251,9 +250,9 @@ The runtime keeps running. To stop it, run 'apify runtime stop'.
251
250
  Tagged images are always re-checked against the registry, so an outdated local copy gets updated.
252
251
  'apify runtime start' then runs the image installed last.
253
252
  Requires Docker or Podman. For installation steps, see https://docs.docker.com/get-started/get-docker/ or ${Cn}.\n\nNOTE: This command is experimental and might change in future releases.`;static group=`Local Actor Development`;static examples=[{description:`Install the Actor runtime.`,command:`apify runtime install`},{description:`Re-download the Actor runtime image even if it is already present.`,command:`apify runtime install --force`},{description:`Install a specific runtime image, e.g. a pinned build or another implementation.`,command:`apify runtime install apify/actor-runtime:master-5462005`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-install`;static args={image:Q.string({description:`Container image to install as the Actor runtime. Defaults to 'apify/actor-runtime:latest'.`})};static flags={force:X.boolean({char:`f`,description:`Re-download the Actor runtime image even if it's already present.`,default:!1})};async run(){await ensureActorRuntimeImage({image:this.args.image??`apify/actor-runtime:latest`,forcePull:this.flags.force,refreshFromRegistry:!0})&&(success({message:`Actor runtime is installed.`}),simpleLog({message:`Start it with 'apify runtime start'.`}),simpleLog({message:[``,...runtimeSkillHintLines()].join(`
254
- `)}))}};const Fa=`apify-actor-runtime`,Ia=`SKILL.md`;function describeSkillSource(e){return e.kind===`runtime`?`the runtime at ${e.baseUrl}`:`the '${e.image}' image`}async function fetchSkillFromRuntime(e){try{let t=await fetch(`${e.replace(/\/v2\/?$/,``)}/actor-runtime/skill`,{headers:sn});if(!t.ok)return null;let n=await t.text();return n.trim()?n:null}catch{return null}}async function readSkillFromImage(e,t){let n=await xe(B(fe(),`apify-runtime-skill-`)),r;try{let{stdout:i}=await K(e,[`create`,t]);return r=i.trim().split(`
255
- `).at(-1)?.trim(),r?(await K(e,[`cp`,`${r}:/usr/src/app/skills/actor-runtime/.`,n]),await Se(B(n,Ia),`utf8`)):null}catch{return null}finally{r&&await K(e,[`rm`,`-f`,r]).catch(()=>{}),await Te(n,{recursive:!0,force:!0})}}async function resolveRuntimeSkill(){let e=resolveApiBaseUrl()??runtimeApiUrl(configuredRuntimePorts().api),t=await fetchSkillFromRuntime(e);if(t)return{content:t,source:{kind:`runtime`,baseUrl:e}};let n=await findRunningRuntimeEngine(),r=installedActorRuntimeImage();for(let e of n?[n]:[`docker`,`podman`]){if(!await imageExistsLocally(e,r))continue;let t=await readSkillFromImage(e,r);if(t)return{content:t,source:{kind:`image`,image:r}}}return null}function frameSkillForReading(e,t){let n=e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/,``).trimStart();return[`<!-- Agent Skill '${Fa}', read from ${describeSkillSource(t)}. -->`,``,`> The local Actor runtime's own instructions for using it. To keep them loaded in later sessions`,"> instead of only this one, run `apify runtime skill --install`.",``,n].join(`
256
- `)}function skillTargets(t=userHomeDir(),n=e.cwd()){let r=[];t&&r.push({directory:B(t,`.claude`,`skills`,Fa),label:`Claude Code`},{directory:B(t,`.agents`,`skills`,Fa),label:`Codex and other agents`});for(let[e,t]of[[`.claude`,`this project (Claude Code)`],[`.agents`,`this project`]])p(B(n,e,`skills`))&&r.push({directory:B(n,e,`skills`,Fa),label:t});return r}function stampSkill(e,t,n=/* @__PURE__ */ new Date){let r=`<!-- Installed by 'apify runtime skill --install' from ${describeSkillSource(t)} on ${n.toISOString().slice(0,10)}. Re-run it after upgrading the runtime. -->`,i=/^(---\r?\n[\s\S]*?\r?\n---\r?\n)/.exec(e);return i?`${i[1]}\n${r}\n${e.slice(i[1].length)}`:`${r}\n${e}`}async function writeSkillTo(e,t){await U(e.directory,{recursive:!0}),await G(B(e.directory,Ia),t)}var RuntimeSkillCommand=class extends ApifyCommand{static name=`skill`;static description=`Prints the Agent Skill that teaches coding agents how to use the Actor runtime.
253
+ `)}))}};const Pa=`apify-actor-runtime`,Fa=`SKILL.md`;function describeSkillSource(e){return e.kind===`runtime`?`the runtime at ${e.baseUrl}`:`the '${e.image}' image`}async function fetchSkillFromRuntime(e){try{let t=await fetch(`${e.replace(/\/v2\/?$/,``)}/actor-runtime/skill`,{headers:sn});if(!t.ok)return null;let n=await t.text();return n.trim()?n:null}catch{return null}}async function readSkillFromImage(e,t){let n=await xe(B(fe(),`apify-runtime-skill-`)),r;try{let{stdout:i}=await K(e,[`create`,t]);return r=i.trim().split(`
254
+ `).at(-1)?.trim(),r?(await K(e,[`cp`,`${r}:/usr/src/app/skills/actor-runtime/.`,n]),await Se(B(n,Fa),`utf8`)):null}catch{return null}finally{r&&await K(e,[`rm`,`-f`,r]).catch(()=>{}),await Te(n,{recursive:!0,force:!0})}}async function resolveRuntimeSkill(){let e=resolveApiBaseUrl()??runtimeApiUrl(configuredRuntimePorts().api),t=await fetchSkillFromRuntime(e);if(t)return{content:t,source:{kind:`runtime`,baseUrl:e}};let n=await findRunningRuntimeEngine(),r=installedActorRuntimeImage();for(let e of n?[n]:[`docker`,`podman`]){if(!await imageExistsLocally(e,r))continue;let t=await readSkillFromImage(e,r);if(t)return{content:t,source:{kind:`image`,image:r}}}return null}function frameSkillForReading(e,t){let n=e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/,``).trimStart();return[`<!-- Agent Skill '${Pa}', read from ${describeSkillSource(t)}. -->`,``,`> The local Actor runtime's own instructions for using it. To keep them loaded in later sessions`,"> instead of only this one, run `apify runtime skill --install`.",``,n].join(`
255
+ `)}function skillTargets(t=userHomeDir(),n=e.cwd()){let r=[];t&&r.push({directory:B(t,`.claude`,`skills`,Pa),label:`Claude Code`},{directory:B(t,`.agents`,`skills`,Pa),label:`Codex and other agents`});for(let[e,t]of[[`.claude`,`this project (Claude Code)`],[`.agents`,`this project`]])p(B(n,e,`skills`))&&r.push({directory:B(n,e,`skills`,Pa),label:t});return r}function stampSkill(e,t,n=/* @__PURE__ */ new Date){let r=`<!-- Installed by 'apify runtime skill --install' from ${describeSkillSource(t)} on ${n.toISOString().slice(0,10)}. Re-run it after upgrading the runtime. -->`,i=/^(---\r?\n[\s\S]*?\r?\n---\r?\n)/.exec(e);return i?`${i[1]}\n${r}\n${e.slice(i[1].length)}`:`${r}\n${e}`}async function writeSkillTo(e,t){await U(e.directory,{recursive:!0}),await G(B(e.directory,Fa),t)}var RuntimeSkillCommand=class extends ApifyCommand{static name=`skill`;static description=`Prints the Agent Skill that teaches coding agents how to use the Actor runtime.
257
256
  The skill comes with the runtime image, so it always matches the version you have installed. The runtime doesn't need to be running.
258
257
  To keep the skill available to your agents in later sessions, use --install. It writes the skill to every agent skills directory it finds.
259
258
 
@@ -273,7 +272,7 @@ Exits with code 1 when the runtime isn't running, so scripts can test for it.
273
272
  `)}),n||(e.exitCode=1)}},RuntimeStopCommand=class extends ApifyCommand{static name=`stop`;static description=`Stops the Actor runtime container started with 'apify runtime start --detach'.
274
273
 
275
274
  `+wn;static group=`Local Actor Development`;static examples=[{description:`Stop the running Actor runtime.`,command:`apify runtime stop`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-stop`;async run(){let t=await findRunningRuntimeEngine();if(!t)info({message:`The Actor runtime is not running.`});else{try{await execWithLog({cmd:t,args:[`stop`,Sn]})}catch{e.exitCode=1;return}success({message:`The Actor runtime was stopped.`}),isConnectedToActorRuntime()&&warning({message:`The Apify CLI is still connected to the Actor runtime, so commands will fail until you start it again with 'apify runtime start --detach' or run 'apify runtime disconnect'.`})}}},RuntimeIndexCommand=class extends ApifyCommand{static name=`runtime`;static description=[`Manages the Actor runtime, a self-contained local Apify platform running as a container on Docker or Podman.`,`For setup and usage, see https://docs.apify.com/cli/docs/actor-runtime.`,``,wn].join(`
276
- `);static group=`Local Actor Development`;static experimental=!0;static examples=[{description:`Start the runtime in the background.`,command:`apify runtime start --detach`},{description:`Point the CLI at the runtime and list the Actors it knows about.`,command:`apify runtime connect && apify actors ls`},{description:`Point the CLI at the runtime for a single command instead.`,command:`APIFY_CLIENT_BASE_URL=${On} apify actors ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime`;static subcommands=[RuntimeInstallCommand,RuntimeStartCommand,RuntimeStopCommand,RuntimeStatusCommand,RuntimeConnectCommand,RuntimeDisconnectCommand,RuntimeSkillCommand];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:Q.string({required:!0,description:`Name of the secret.`}),value:Q.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const La=new $({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)La.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:La.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:Q.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 '${q}' 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()}},ServerEndpointsCommand=class extends ApifyCommand{static name=`endpoints`;static enableProfileFlag=!0;static description=`Lists the HTTP endpoints of a Server Actor, read from the web server schema of the build that serves its server interface.`;static examples=[{description:`List the endpoints of an Actor.`,command:`apify server endpoints apify/rag-web-browser`},{description:`Print the endpoints as JSON.`,command:`apify server endpoints apify/rag-web-browser --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-server-endpoints`;static args={target:Q.string({description:`The Actor ID or "username/name". Defaults to the Actor in the current directory.`})};static enableJsonFlag=!0;async run(){let e=await getLoggedClientOrThrow(),t=await resolveServerActor(e,this.args.target),n=await resolveServerBuild(e,t),{webServerSchema:r,webServerMcpPath:i}=getServerDefinition(n),a=listServerOperations(r);if(this.flags.json){printJsonToStdout({url:t.standbyUrl,tenancy:t.tenancy??null,build:{ref:t.buildRef,id:n.id,buildNumber:n.buildNumber},operations:a,mcpPath:i??null});return}let s=a.map(e=>({method:e.method,path:e.path,summary:e.summary?shortenSummary(e.summary):``}));i&&s.push({method:`MCP`,path:i,summary:``});let c=Math.max(0,...s.map(e=>e.path.length));for(let e of s){let t=e.summary?`${e.path.padEnd(c)} ${e.summary}`:e.path;simpleLog({message:`${e.method.padEnd(7)} ${t}`,stdout:!0})}a.length===0&&!i&&info({message:`Actor "${t.userFriendlyId}" does not document its endpoints. See its README: apify actors info ${t.userFriendlyId} --readme`})}},ServerRequestCommand=class extends ApifyCommand{static name=`request`;static enableProfileFlag=!0;static description=`Sends an authenticated HTTP request to a Server Actor's server interface and prints the response.
275
+ `);static group=`Local Actor Development`;static experimental=!0;static examples=[{description:`Start the runtime in the background.`,command:`apify runtime start --detach`},{description:`Point the CLI at the runtime and list the Actors it knows about.`,command:`apify runtime connect && apify actors ls`},{description:`Point the CLI at the runtime for a single command instead.`,command:`APIFY_CLIENT_BASE_URL=${On} apify actors ls`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime`;static subcommands=[RuntimeInstallCommand,RuntimeStartCommand,RuntimeStopCommand,RuntimeStatusCommand,RuntimeConnectCommand,RuntimeDisconnectCommand,RuntimeSkillCommand];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:Q.string({required:!0,description:`Name of the secret.`}),value:Q.string({required:!0,description:`Value of the secret.`})};async run(){let{name:e,value:t}=this.args;addSecret(e,t)}};const Ia=new $({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)Ia.pushRow({"Secret Name":t.cyan(e)});simpleLog({message:Ia.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:Q.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 '${q}' 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()}},ServerEndpointsCommand=class extends ApifyCommand{static name=`endpoints`;static enableProfileFlag=!0;static description=`Lists the HTTP endpoints of a Server Actor, read from the web server schema of the build that serves its server interface.`;static examples=[{description:`List the endpoints of an Actor.`,command:`apify server endpoints apify/rag-web-browser`},{description:`Print the endpoints as JSON.`,command:`apify server endpoints apify/rag-web-browser --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-server-endpoints`;static args={target:Q.string({description:`The Actor ID or "username/name". Defaults to the Actor in the current directory.`})};static enableJsonFlag=!0;async run(){let e=await getLoggedClientOrThrow(),t=await resolveServerActor(e,this.args.target),n=await resolveServerBuild(e,t),{webServerSchema:r,webServerMcpPath:i}=getServerDefinition(n),a=listServerOperations(r);if(this.flags.json){printJsonToStdout({url:t.standbyUrl,tenancy:t.tenancy??null,build:{ref:t.buildRef,id:n.id,buildNumber:n.buildNumber},operations:a,mcpPath:i??null});return}let s=a.map(e=>({method:e.method,path:e.path,summary:e.summary?shortenSummary(e.summary):``}));i&&s.push({method:`MCP`,path:i,summary:``});let c=Math.max(0,...s.map(e=>e.path.length));for(let e of s){let t=e.summary?`${e.path.padEnd(c)} ${e.summary}`:e.path;simpleLog({message:`${e.method.padEnd(7)} ${t}`,stdout:!0})}a.length===0&&!i&&info({message:`Actor "${t.userFriendlyId}" does not document its endpoints. See its README: apify actors info ${t.userFriendlyId} --readme`})}},ServerRequestCommand=class extends ApifyCommand{static name=`request`;static enableProfileFlag=!0;static description=`Sends an authenticated HTTP request to a Server Actor's server interface and prints the response.
277
276
  The host always comes from the Actor; pass a path, never a full URL. The API token is sent in the Authorization header and never reaches the Actor.`;static examples=[{description:`Send a GET request (the default method).`,command:`apify server request apify/rag-web-browser /search -p '{"query":"apify"}'`},{description:`Send a POST request with a JSON body.`,command:`apify server request POST apify/web-fetch / -d '{"url":"https://example.com"}'`},{description:`Call the Actor in the current directory.`,command:`apify server request /health`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-server-request`;static args={methodOrTarget:Q.string({description:`The HTTP method (defaults to GET), or the Actor when the method is omitted.`}),targetOrPath:Q.string({description:`The Actor ID or "username/name" (defaults to the Actor in the current directory), or the path.`}),path:Q.string({description:`The path on the Actor's server, starting with "/". Defaults to "/".`})};static flags={method:X.string({char:`X`,description:`The HTTP method to use. Defaults to GET.`,choices:Yr}),body:X.string({char:`d`,description:`The request body. Use "-" to read from stdin.`,required:!1,stdin:2}),header:X.string({char:`H`,description:`Additional HTTP header(s). Pass a single "key:value" string, or a JSON object like '{"X-Foo": "bar", "X-Baz": "qux"}' to send multiple headers.`,required:!1}),params:X.string({char:`p`,description:`Query parameters as a JSON object, e.g. '{"query": "apify"}'.`,required:!1})};async run(){let t=parseServerRequestArgs([this.args.methodOrTarget,this.args.targetOrPath,this.args.path]),n=this.flags.method?.toUpperCase();if(t.method&&n&&t.method!==n)throw Error(`Conflicting HTTP methods: positional "${t.method}" vs --method "${n}". Please specify the method only once.`);let r=t.method??n??`GET`,i=parseParams(this.flags.params),a=parseHeaders(this.flags.header),{body:s}=this.flags;if(s&&Xr.has(r))throw Error(`HTTP ${r} requests cannot have a request body. Use POST, PUT or PATCH, or omit --body.`);let c=await getLoggedClientOrThrow(),l=await resolveServerActor(c,t.target),u=resolveServerRequestUrl(l.standbyUrl,t.path,i);if(!isMultiTenant(l)){let{username:e}=await getCurrentUserInfo();info({message:`${l.userFriendlyId} is single-tenant: it runs in account "${e}", which pays the platform usage.`})}let f={...sn,Authorization:`Bearer ${c.token}`};s&&(f[`Content-Type`]=isJson(s)?`application/json`:`text/plain; charset=utf-8`);let p=mergeHeaders(f,a),m=new AbortController,h=setTimeout(()=>m.abort(),3e5),g=setTimeout(()=>{info({message:`Waiting for the Actor to respond.`})},2e3),_=setTimeout(()=>{info({message:`Still waiting. If the Actor had no run ready, the platform is starting one, which can take up to 2 minutes.`})},2e4),v;try{v=await fetch(u,{method:r,headers:p,body:s||void 0,redirect:`manual`,signal:m.signal})}catch(e){throw m.signal.aborted?Error(`The Actor did not respond within 5 minutes.`):e}finally{clearTimeout(h),clearTimeout(g),clearTimeout(_)}if(v.status>=300&&v.status<400){let e=v.headers.get(`location`);warning({message:`${v.status} ${v.statusText}. Not following the redirect${e?` to ${e}`:``}.`})}if(v.status>=400){e.exitCode=1;let t=await v.text();error({message:`${v.status} ${v.statusText}`});let n=describeServerError(v.status,t);n&&simpleLog({message:n}),t&&(e.stdout.write(t),endLineOnTerminal(t.endsWith(`
278
277
  `)));return}if(!v.body)return;let y;for await(let t of v.body)t.length>0&&(y=t[t.length-1]),e.stdout.write(t)||await Ae(e.stdout,`drain`);endLineOnTerminal(y===void 0||y===10)}};function endLineOnTerminal(t){e.stdout.isTTY&&!t&&e.stdout.write(`
279
278
  `)}function isJson(e){try{return JSON.parse(e),!0}catch{return!1}}var ServerStatusCommand=class extends ApifyCommand{static name=`status`;static enableProfileFlag=!0;static description=`Shows how a Server Actor's server interface is configured and, for single-tenant Actors, the runs serving you. Never sends a request to the Actor, so it cannot start a run.`;static examples=[{description:`Show the server interface of an Actor.`,command:`apify server status apify/rag-web-browser`},{description:`Print the status as JSON.`,command:`apify server status apify/web-fetch --json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-server-status`;static args={target:Q.string({description:`The Actor ID or "username/name". Defaults to the Actor in the current directory.`})};static enableJsonFlag=!0;async run(){let e=await getLoggedClientOrThrow(),t=await resolveServerActor(e,this.args.target),n=await resolveServerBuild(e,t),{webServerSchema:r,webServerMcpPath:i}=getServerDefinition(n),a=listServerOperations(r),s=isMultiTenant(t),{standby:c}=t,{username:l}=await getCurrentUserInfo(),u;if(!s){let{items:n}=await e.actor(t.id).runs().list({status:`RUNNING`,desc:!0});u=n.filter(e=>e.meta?.origin===se.STANDBY).map(({id:e,startedAt:t})=>({id:e,startedAt:t}))}if(this.flags.json){printJsonToStdout({url:t.standbyUrl,tenancy:t.tenancy??null,pricingModel:t.pricingModel??null,build:{ref:t.buildRef,id:n.id,buildNumber:n.buildNumber},memoryMbytes:c.memoryMbytes??null,idleTimeoutSecs:c.idleTimeoutSecs??null,desiredRequestsPerActorRun:c.desiredRequestsPerActorRun??null,maxRequestsPerActorRun:c.maxRequestsPerActorRun??null,operationCount:a.length,mcpPath:i??null,runs:u??null});return}let f=describeTenancy(t,l),p=a.length>0?`${a.length} documented (apify server endpoints ${t.userFriendlyId})`:`not documented (see the Actor README)`,m=[`URL: ${t.standbyUrl}`,`Tenancy: ${f}`,`Build: ${t.buildRef} (${n.buildNumber})`,`Memory: ${c.memoryMbytes??`-`} MB`,`Idle timeout: ${c.idleTimeoutSecs??`-`} s`,`Requests/run: ${c.desiredRequestsPerActorRun??`-`} desired, ${c.maxRequestsPerActorRun??`-`} max`,`Endpoints: ${p}`,...i?[`MCP path: ${i}`]:[]];u&&m.push(u.length>0?`Runs: ${u.length} running (${u.map(e=>e.id).join(`, `)}); the next request is served warm`:`Runs: none running; the next request starts one (cold start)`),simpleLog({message:m.join(`
@@ -281,7 +280,7 @@ The host always comes from the Actor; pass a path, never a full URL. The API tok
281
280
  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:Q.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.
282
281
  Customize with --memory and --timeout flags.
283
282
  `;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:Q.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.
284
- 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:Q.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 Ra=new $({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 Lt().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)Ra.pushRow({Template:e.name,Label:e.label,Language:languageLabel(e.category),"Use cases":(e.useCases??[]).join(`, `)});simpleLog({message:Ra.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.
283
+ 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:Q.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 La=new $({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 Lt().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)La.pushRow({Template:e.name,Label:e.label,Language:languageLabel(e.category),"Use cases":(e.useCases??[]).join(`, `)});simpleLog({message:La.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.
285
284
 
286
285
  When a path argument is provided, validates only the input schema at that path.
287
286
 
@@ -289,5 +288,5 @@ When no path is provided, validates all schemas found in '${q}':
289
288
  - Input schema (from "input" key or default locations)
290
289
  - Dataset schema (from "storages.dataset")
291
290
  - Output schema (from "output")
292
- - 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:Q.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${q}'.`})};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 '${q}'`}`});let t=new mr({strict:!1});wt(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 '${q}'`}`}),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 '${q}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const za=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,RuntimeIndexCommand,SecretsIndexCommand,ServerIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],Ba=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,za as n,processVersionCheck as r,Ba as t};
293
- //# sourceMappingURL=_register-DiTI-XPy.js.map
291
+ - 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:Q.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${q}'.`})};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 '${q}'`}`});let t=new mr({strict:!1});wt(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 '${q}'`}`}),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 '${q}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Ra=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,RuntimeIndexCommand,SecretsIndexCommand,ServerIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],za=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Ra as n,processVersionCheck as r,za as t};
292
+ //# sourceMappingURL=_register-CklrKS5E.js.map