apify-cli 1.10.1-runtime.4 → 1.10.1-runtime.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as A,readFileSync as j,readdirSync as M,realpathSync as ee,renameSync as te,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce,tmpdir as le}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as L,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{Result as Ce,err as we,none as Te,ok as Ee,some as De}from"@sapphire/result";import{execa as R}from"execa";import{access as Oe,appendFile as ke,mkdir as z,mkdtemp as Ae,readFile as B,readdir as je,rename as Me,rm as Ne,stat as V,symlink as Pe,unlink as Fe,writeFile as H}from"node:fs/promises";import Ie from"configparser";import Le from"@inquirer/input";import Re from"which";import{createHmacSignature as ze,cryptoRandomObjectId as Be}from"@apify/utilities";import{execSync as Ve,spawn as He}from"node:child_process";import{DurationFormatter as Ue,Time as We,TimeTypes as Ge}from"@sapphire/duration";import{Timestamp as Ke}from"@sapphire/timestamp";import qe from"adm-zip";import Je from"ajv/dist/2019.js";import{ApifyClient as Ye,DownloadItemsFormat as U}from"apify-client";import{ZipArchive as Xe}from"archiver";import Ze,{AxiosHeaders as Qe}from"axios";import $e from"escape-string-regexp";import et from"ignore";import{getEncoding as tt}from"istextorbinary";import nt,{Mime as rt}from"mime";import it from"mime/types/other.js";import at from"mime/types/standard.js";import{glob as ot}from"tinyglobby";import{calculateRunDynamicMemory as st}from"@apify/actor-memory-expression";import{Separator as ct,createPrompt as lt,isEnterKey as ut,makeTheme as dt,useKeypress as ft,usePrefix as pt,useState as mt}from"@inquirer/core";import{pipeline as ht}from"node:stream/promises";import{MemoryStorage as gt}from"@crawlee/memory-storage";import{compile as _t}from"json-schema-to-typescript";import{validateInputSchema as vt,validateInputUsingValidator as yt}from"@apify/input_schema";import{getDatasetSchemaValidator as bt,getKeyValueStoreSchemaValidator as xt,getOutputSchemaValidator as St}from"@apify/json_schemas";import Ct from"cli-table3";import{downloadTemplate as wt}from"giget";import Tt from"jju";import Et from"open";import{fetchManifest as Dt,manifestUrl as Ot,wrapperManifestUrl as kt}from"@apify/actor-templates";import At from"computer-name";import jt from"@inquirer/password";import Mt from"@inquirer/select";import{createServer as Nt}from"node:http";import Pt from"node:assert";import{ReadStream as Ft}from"node:tty";import{setTimeout as It}from"node:timers/promises";import Lt from"detect-indent";import{fileURLToPath as Rt}from"node:url";import zt from"@root/walk";import Bt from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Vt=null;function useCLIMetadata(){if(Vt)return Vt;let e=detectInstallMethod(),t=getRuntimeInfo();return Vt={version:`1.10.1-runtime.
|
|
1
|
+
import e from"node:process";import t from"chalk";import n from"indent-string";import r from"widest-line";import i from"wrap-ansi";import a,{basename as s,dirname as c,isAbsolute as l,join as u,relative as f,resolve as p,sep as m}from"node:path";import{inspect as h,parseArgs as g,promisify as _}from"node:util";import{gt as v,gte as y,minVersion as b,satisfies as x}from"semver";import{appendFileSync as S,chmodSync as C,constants as w,copyFileSync as T,createWriteStream as E,existsSync as D,fstat as O,mkdirSync as k,openSync as A,readFileSync as j,readdirSync as M,realpathSync as ee,renameSync as te,rmSync as N,statSync as ne,unlinkSync as re,writeFileSync as P}from"node:fs";import ie from"string-width";import ae from"strip-ansi";import{once as oe}from"node:events";import{homedir as se,platform as ce,tmpdir as le}from"node:os";import ue,{isCI as de}from"ci-info";import{ACTOR_ENV_VARS as F,ACTOR_JOB_STATUSES as I,ACTOR_JOB_TERMINAL_STATUSES as fe,ACTOR_NAME as pe,ACTOR_SOURCE_TYPES as me,APIFY_ENV_VARS as L,KEY_VALUE_STORE_KEYS as he,LOCAL_ACTOR_ENV_VARS as ge,LOCAL_STORAGE_SUBDIRS as _e,MAX_MULTIFILE_BYTES as ve,META_ORIGINS as ye,SOURCE_FILE_FORMATS as be}from"@apify/consts";import{jaroWinkler as xe}from"@skyra/jaro-winkler";import Se from"js-levenshtein";import{Result as Ce,err as we,none as Te,ok as Ee,some as De}from"@sapphire/result";import{execa as R}from"execa";import{access as Oe,appendFile as ke,mkdir as z,mkdtemp as Ae,readFile as B,readdir as je,rename as Me,rm as Ne,stat as V,symlink as Pe,unlink as Fe,writeFile as H}from"node:fs/promises";import Ie from"configparser";import Le from"@inquirer/input";import Re from"which";import{createHmacSignature as ze,cryptoRandomObjectId as Be}from"@apify/utilities";import{execSync as Ve,spawn as He}from"node:child_process";import{DurationFormatter as Ue,Time as We,TimeTypes as Ge}from"@sapphire/duration";import{Timestamp as Ke}from"@sapphire/timestamp";import qe from"adm-zip";import Je from"ajv/dist/2019.js";import{ApifyClient as Ye,DownloadItemsFormat as U}from"apify-client";import{ZipArchive as Xe}from"archiver";import Ze,{AxiosHeaders as Qe}from"axios";import $e from"escape-string-regexp";import et from"ignore";import{getEncoding as tt}from"istextorbinary";import nt,{Mime as rt}from"mime";import it from"mime/types/other.js";import at from"mime/types/standard.js";import{glob as ot}from"tinyglobby";import{calculateRunDynamicMemory as st}from"@apify/actor-memory-expression";import{Separator as ct,createPrompt as lt,isEnterKey as ut,makeTheme as dt,useKeypress as ft,usePrefix as pt,useState as mt}from"@inquirer/core";import{pipeline as ht}from"node:stream/promises";import{MemoryStorage as gt}from"@crawlee/memory-storage";import{compile as _t}from"json-schema-to-typescript";import{validateInputSchema as vt,validateInputUsingValidator as yt}from"@apify/input_schema";import{getDatasetSchemaValidator as bt,getKeyValueStoreSchemaValidator as xt,getOutputSchemaValidator as St}from"@apify/json_schemas";import Ct from"cli-table3";import{downloadTemplate as wt}from"giget";import Tt from"jju";import Et from"open";import{fetchManifest as Dt,manifestUrl as Ot,wrapperManifestUrl as kt}from"@apify/actor-templates";import At from"computer-name";import jt from"@inquirer/password";import Mt from"@inquirer/select";import{createServer as Nt}from"node:http";import Pt from"node:assert";import{ReadStream as Ft}from"node:tty";import{setTimeout as It}from"node:timers/promises";import Lt from"detect-indent";import{fileURLToPath as Rt}from"node:url";import zt from"@root/walk";import Bt from"handlebars";function internalLog(e){e.stdoutOutput&&console.log(...e.stdoutOutput),e.stderrOutput&&console.error(...e.stderrOutput)}function simpleLog(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[e.message]})}function error(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.red(`Error:`),e.message]})}function warning(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.yellow.bold(`Warning:`),e.message]})}function success(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.green(`Success:`),e.message]})}function run(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.gray(`Run:`),e.message]})}function info(e){internalLog({[e.stdout?`stdoutOutput`:`stderrOutput`]:[t.white(`Info:`),e.message]})}function detectInstallMethod(){if(process.env.APIFY_CLI_BUNDLE)return`bundle`;let e=process.argv[1];if(!e)return warning({message:`Failed to detect install method of CLI, assuming npm`}),`npm`;let t=ee(e);return process.env.VOLTA_HOME&&t.includes(process.env.VOLTA_HOME)?`volta`:t.includes(`homebrew/Cellar`)||t.includes(`linuxbrew/Cellar`)?`homebrew`:process.env.PNPM_HOME&&t.includes(process.env.PNPM_HOME)?`pnpm`:process.env.BUN_INSTALL&&t.includes(process.env.BUN_INSTALL)?`bun`:`npm`}function getRuntimeInfo(){return process.versions.bun?{runtime:`bun`,version:process.versions.bun,nodeVersion:process.versions.node}:process.versions.deno?{runtime:`deno`,version:process.versions.deno,nodeVersion:process.versions.node}:{runtime:`node`,version:process.versions.node}}let Vt=null;function useCLIMetadata(){if(Vt)return Vt;let e=detectInstallMethod(),t=getRuntimeInfo();return Vt={version:`1.10.1-runtime.5`,hash:`c8742136cfd985dc5555469e3852e3921262fa98`,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`&&(Vt.installPath=c(process.execPath)),Vt}function cliDebugPrint(e,...n){process.env.APIFY_CLI_DEBUG&&console.error(t.gray(`[${e}]`),...n)}const Ht=[`apify`,`actor`];function unixWrapperScript(e){return[`#!/bin/sh`,`DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"`,`APIFY_CLI_ENTRYPOINT=${e} exec "$DIR/apify-cli" "$@"`,``].join(`
|
|
2
2
|
`)}function windowsCmdWrapperScript(e){return[`@echo off`,`setlocal`,`set "APIFY_CLI_ENTRYPOINT=${e}"`,`"%~dp0apify-cli.exe" %*`,``].join(`\r
|
|
3
3
|
`)}function windowsPowershellWrapperScript(e){return[`#!/usr/bin/env pwsh`,`$prev = $env:APIFY_CLI_ENTRYPOINT`,`$env:APIFY_CLI_ENTRYPOINT = "${e}"`,`try {`,` & "$PSScriptRoot\\apify-cli.exe" @args`,`} finally {`,` $env:APIFY_CLI_ENTRYPOINT = $prev`,`}`,`exit $LASTEXITCODE`,``].join(`\r
|
|
4
4
|
`)}function atomicWriteSync(t,n,r){let i=`${t}.${e.pid}.tmp`;try{P(i,n),r!==void 0&&C(i,r),te(i,t)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function atomicCopySync(t,n,r){let i=`${n}.${e.pid}.tmp`;try{T(t,i),r!==void 0&&C(i,r),te(i,n)}catch(e){try{N(i,{force:!0})}catch{}throw e}}function writeEntrypointShims(e,t){for(let n of Ht)atomicWriteSync(u(e,n),unixWrapperScript(n),493),t&&(atomicWriteSync(u(e,`${n}.cmd`),windowsCmdWrapperScript(n)),atomicWriteSync(u(e,`${n}.ps1`),windowsPowershellWrapperScript(n)))}function migrateLegacyBundleInstallIfNeeded(){let t=useCLIMetadata();if(t.installMethod!==`bundle`)return;let n=t.platform===`windows`,r=c(e.execPath),i=s(e.execPath).replace(/\.exe$/i,``).toLowerCase();if(n)for(let e of Ht){let t=u(r,`${e}.exe.old`);if(D(t))try{N(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`||!Ht.includes(i))return;cliDebugPrint(`[migration] legacy multi-bundle install detected, migrating to single bundle`,{binDir:r,selfName:i});let a=u(r,`apify-cli${n?`.exe`:``}`);try{atomicCopySync(e.execPath,a,n?void 0:493),cliDebugPrint(`[migration] copied current bundle to`,a)}catch(e){cliDebugPrint(`[migration] failed to copy current bundle, will retry on next run`,{err:e});return}try{writeEntrypointShims(r,n),cliDebugPrint(`[migration] wrote entrypoint shims`)}catch(e){cliDebugPrint(`[migration] failed to write entrypoint shims, will retry on next run`,{err:e})}if(n){for(let t of Ht){let n=u(r,`${t}.exe`);if(D(n))try{p(n)===p(e.execPath)?(te(n,`${n}.old`),cliDebugPrint(`[migration] renamed running legacy binary`,n)):N(n,{force:!0})}catch(e){try{te(n,`${n}.old`)}catch{}cliDebugPrint(`[migration] failed to remove legacy binary`,{legacyBinaryPath:n,err:e})}}let t=u(r,`upgrade.ps1`);try{N(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 Ut;function getMaxLineWidth(){if(Ut)return Ut;let e=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(e))Ut=e;else if(!process.stdout.isTTY)Ut=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;Ut=e<1?80:e<40?40:e}return Ut}var BaseCommandRenderer=class{command;entrypoint;constructor(e,t){this.entrypoint=e,this.command=t}pushShortDescription(e){let n=this.command.interactive?`${t.yellow(`[INTERACTIVE]`)} `:``;this.command.shortDescription?e.push(`${n}${this.command.shortDescription}`,``):this.command.description&&e.push(`${n}${this.command.description.split(`
|
|
@@ -45,7 +45,7 @@ Common package structures:
|
|
|
45
45
|
src/
|
|
46
46
|
my_package/
|
|
47
47
|
__init__.py
|
|
48
|
-
main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:l(e)&&e.includes(` `)?`"${e}"`:e:null}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([V(u(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),V(u(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),V(u(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),V(u(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}let wn=`inherit`;function keepStdoutClean(){wn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{let a=normalizeExecutablePath(t);cliDebugPrint(`spawnPromised`,{escapedCommand:a,args:n,opts:r,forwardSignals:i});let s=R(a,n,{shell:!0,windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,wn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),c=[];if(i?.length)for(let t of i){let handler=()=>{s.kill(t)};e.on(t,handler),c.push(()=>e.off(t,handler))}try{return await Ce.fromAsync(s.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 c)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 Tn=[[`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 Tn)if(process.env[e])return t}function detectCi(){return ue.isCI?{isCi:!0,ciProvider:ue.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await B(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await H(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(m).reduce((e,t)=>(e=u(e,t),D(e)||k(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Ne(e,{recursive:!0,force:!0})))},deleteFile=async e=>{(await V(e)).isFile()&&await Fe(e)};function ensureApifyDirectory(e){let t=c(e);k(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>V(u(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),En=`token`,Dn=`proxy-password`;let On,kn,An;async function loadKeyringModule(){return On===void 0&&(On=await importKeyringModule()),On}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 kn||(kn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`||readAuthFile().secretsBackend===`file`?`file`:await loadKeyringModule()?`keyring`:`file`)(),kn)}function downgradeBackendToFile(){kn=Promise.resolve(`file`)}function readAuthFile(){if(!D(AUTH_FILE_PATH()))return{};try{let e=j(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e)}catch{return{}}}function writeAuthFile(e){ensureApifyDirectory(AUTH_FILE_PATH()),P(AUTH_FILE_PATH(),JSON.stringify(e,null,` `),{mode:384})}async function getKeyringEntry(e){let t=await loadKeyringModule();return t?new t.Entry(`com.apify.cli`,e):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);if(!t)return;t.deletePassword()}catch(t){cliDebugPrint(`credentials`,`failed to delete ${e} from keyring`,t)}}async function getToken(){return await getBackend()===`keyring`?readKeyring(En):readAuthFile().token}async function getProxyPassword(){return await getBackend()===`keyring`?readKeyring(Dn):readAuthFile().proxy?.password}async function setToken(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(En):readAuthFile().token)===e)return;if(n===`keyring`)try{await writeKeyring(En,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.token=e,r.secretsBackend=`file`,writeAuthFile(r)}async function setProxyPassword(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(Dn):readAuthFile().proxy?.password)===e)return;if(n===`keyring`)try{await writeKeyring(Dn,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.proxy={...r.proxy,password:e},r.secretsBackend=`file`,writeAuthFile(r)}async function clearKeyringSecrets(){await deleteKeyring(En),await deleteKeyring(Dn)}async function ensureMigrated(){return An||(An=(async()=>{try{let e=readAuthFile();if(e.secretsBackend||!e.token&&!e.proxy?.password)return;if(await getBackend()===`file`){e.secretsBackend=`file`,writeAuthFile(e);return}try{e.token&&await writeKeyring(En,e.token),e.proxy?.password&&await writeKeyring(Dn,e.proxy.password)}catch(t){cliDebugPrint(`credentials`,`keyring write failed during migration; falling back to file`,t),downgradeBackendToFile(),e.secretsBackend=`file`,writeAuthFile(e);return}delete e.token,e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy),e.secretsBackend=`keyring`,writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),An)}const jn=`__CLI_`;function resolveInputKey(){return process.env[F.INPUT_KEY]||process.env[L.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${$e(e)}(?:\\.[^.]+)?$)`)}function readActorRuntimeConfig(){try{let e=JSON.parse(j(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),P(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Mn=`apify/actor-runtime:latest`,Nn=`apify-actor-runtime`,Pn=`https://docs.docker.com/get-started/get-docker/`,Fn=`https://podman.io/docs/installation`,In=3333,Ln=3e3,Rn=`http://localhost:${In}`,zn=`http://localhost:${Ln}`,Bn={APIFY_CLIENT_BASE_URL:Rn,APIFY_CONSOLE_URL:zn},Vn=[`docker`,`podman`],Hn=`APIFY_CONTAINER_ENGINE`,Un=`/data`;function runtimeEnvExportLines(){return Object.entries(Bn).map(([e,t])=>`export ${e}=${t}`)}function requestedContainerEngine(t=e.env){let n=t[Hn]?.trim().toLowerCase();return Vn.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:Vn,i=[];for(let e of r)await Re(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: ${Fn}`;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 R(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await R(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}async function imageExistsLocally(e,t){try{return await R(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await R(e,[`ps`,`--filter`,`name=^${Nn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}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===Un)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await R(e,[`inspect`,Nn,`--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){if(t===`docker`)return unixSocketPath(n.DOCKER_HOST)??`/var/run/docker.sock`;try{let{stdout:e}=await R(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:/var/run/docker.sock`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,platform:a=e.platform}){let s=[`run`,`--rm`,`--init`,`--name`,Nn];return r&&s.push(`--detach`),s.push(`-p`,`${In}:${In}`,`-p`,`${Ln}:${Ln}`,`-v`,socketMountArg(i,a),`-v`,`${n}:${Un}`,t),s}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 isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function overridingRuntimeEnvVars(t=e.env){return Object.keys(Bn).filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?Rn:void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?zn:void 0)}const Wn=et,Gn=Je,getLocalStorageDir=()=>{let t=L.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=F.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.keyValueStores,r)},getLocalDatasetPath=t=>{let n=F.DEFAULT_DATASET_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.datasets,r)},getLocalRequestQueuePath=t=>{let n=F.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.requestQueues,r)},getLocalUserInfo=async()=>{await ensureMigrated();let e={};try{let t=await B(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{}if(await getBackend()===`keyring`){let t=await getToken();t&&(e.token=t);let n=await getProxyPassword();n&&(e.proxy={...e.proxy,password:n})}let t=!!(e.username||e.id);if(!(t||e.token))return{};if(!t)throw Error(`Stale credentials found without user metadata. Please run "apify login" again.`);return e};async function getLoggedClientOrThrow(){let t=await getLoggedClient();if(!t)throw e.exitCode=1,Error(`You are not logged in with your Apify account. Call "apify login" to fix that.`);return t}const resolveToken=async e=>e||(await ensureMigrated(),getToken()),getApifyClientOptions=async(e,t)=>({token:await resolveToken(e),baseUrl:t||resolveApiBaseUrl(),requestInterceptors:[e=>{e.headers??=new Qe;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){let n=await resolveToken(e),r=new Ye(await getApifyClientOptions(n,t)),i;try{i=await r.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}r.token&&await setToken(r.token,{skipIfUnchanged:!0});let a=i.proxy?.password;a&&await setProxyPassword(a,{skipIfUnchanged:!0}),ensureApifyDirectory(AUTH_FILE_PATH());let s=(()=>{try{return JSON.parse(j(AUTH_FILE_PATH(),`utf-8`))}catch{return{}}})(),c=await getBackend(),l={...s,...i,secretsBackend:c};if(c===`keyring`&&(delete l.token,l.proxy&&typeof l.proxy==`object`)){let{password:e,...t}=l.proxy;Object.keys(t).length>0?l.proxy=t:delete l.proxy}return P(AUTH_FILE_PATH(),JSON.stringify(l,null,` `),{mode:384}),r}const getLocalConfigPath=e=>u(e,G),getJsonFileContent=e=>{if(D(e))return JSON.parse(j(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=u(n||e.cwd(),G);await z(c(r),{recursive:!0}),P(r,JSON.stringify(t,null,` `))},Kn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=u(e,`.gitignore`),r=``;D(n)&&(r=j(n,{encoding:`utf-8`}));let i=[];for(let e of Kn)RegExp(`^${$e(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),P(n,`\n${i.join(`
|
|
48
|
+
main.py`);return null}async function checkScrapyProject(e){return ScrapyProjectAnalyzer.isApplicable(e)}function normalizeExecutablePath(e){return e?e.startsWith(`"`)?e:l(e)&&e.includes(` `)?`"${e}"`:e:null}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([V(u(e,`yarn.lock`)).then(()=>!0).catch(()=>!1),V(u(e,`pnpm-lock.yaml`)).then(()=>!0).catch(()=>!1),V(u(e,`bun.lockb`)).then(()=>!0).catch(()=>!1),V(u(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}let wn=`inherit`;function keepStdoutClean(){wn=e.stderr}const spawnPromised=async(t,n,r,{forwardSignals:i}={})=>{let a=normalizeExecutablePath(t);cliDebugPrint(`spawnPromised`,{escapedCommand:a,args:n,opts:r,forwardSignals:i});let s=R(a,n,{shell:!0,windowsHide:!0,env:r.env,cwd:r.cwd,stdout:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,wn],stderr:e.env.APIFY_NO_LOGS_IN_TESTS?[`pipe`]:[`pipe`,`inherit`],verbose:e.env.APIFY_CLI_DEBUG?`full`:void 0}),c=[];if(i?.length)for(let t of i){let handler=()=>{s.kill(t)};e.on(t,handler),c.push(()=>e.off(t,handler))}try{return await Ce.fromAsync(s.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 c)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 Tn=[[`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 Tn)if(process.env[e])return t}function detectCi(){return ue.isCI?{isCi:!0,ciProvider:ue.id?.toLowerCase()??`unknown`}:{isCi:!1,ciProvider:void 0}}function detectIsInteractive(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}const updateLocalJson=async(e,t={},n=null)=>{let r=await B(e,`utf-8`),i=JSON.parse(r),a;n?(a=i,a[n]={...i[n],...t}):a={...i,...t},await H(e,JSON.stringify(a,null,` `))},ensureFolderExistsSync=(e,t)=>{t||(t=e,e=`.`),t.split(m).reduce((e,t)=>(e=u(e,t),D(e)||k(e),e),e)},rimrafPromised=async e=>{let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async e=>Ne(e,{recursive:!0,force:!0})))},deleteFile=async e=>{(await V(e)).isFile()&&await Fe(e)};function ensureApifyDirectory(e){let t=c(e);k(t,{recursive:!0})}const sumFilesSizeInBytes=async(e,t)=>(await Promise.all(e.map(async e=>V(u(t,e))))).map(e=>e.size).reduce((e,t)=>e+t,0),En=`token`,Dn=`proxy-password`;let On,kn,An;async function loadKeyringModule(){return On===void 0&&(On=await importKeyringModule()),On}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 kn||(kn=(async()=>e.env.APIFY_DISABLE_KEYRING===`1`||readAuthFile().secretsBackend===`file`?`file`:await loadKeyringModule()?`keyring`:`file`)(),kn)}function downgradeBackendToFile(){kn=Promise.resolve(`file`)}function readAuthFile(){if(!D(AUTH_FILE_PATH()))return{};try{let e=j(AUTH_FILE_PATH(),`utf-8`);return JSON.parse(e)}catch{return{}}}function writeAuthFile(e){ensureApifyDirectory(AUTH_FILE_PATH()),P(AUTH_FILE_PATH(),JSON.stringify(e,null,` `),{mode:384})}async function getKeyringEntry(e){let t=await loadKeyringModule();return t?new t.Entry(`com.apify.cli`,e):null}async function readKeyring(e){try{let t=await getKeyringEntry(e);return t?t.getPassword()??void 0:void 0}catch(t){cliDebugPrint(`credentials`,`failed to read ${e} from keyring`,t);return}}async function writeKeyring(e,t){let n=await getKeyringEntry(e);if(!n)throw Error(`OS keyring is not available.`);n.setPassword(t)}async function deleteKeyring(e){try{let t=await getKeyringEntry(e);if(!t)return;t.deletePassword()}catch(t){cliDebugPrint(`credentials`,`failed to delete ${e} from keyring`,t)}}async function getToken(){return await getBackend()===`keyring`?readKeyring(En):readAuthFile().token}async function getProxyPassword(){return await getBackend()===`keyring`?readKeyring(Dn):readAuthFile().proxy?.password}async function setToken(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(En):readAuthFile().token)===e)return;if(n===`keyring`)try{await writeKeyring(En,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.token=e,r.secretsBackend=`file`,writeAuthFile(r)}async function setProxyPassword(e,t={}){let n=await getBackend();if(t.skipIfUnchanged&&(n===`keyring`?await readKeyring(Dn):readAuthFile().proxy?.password)===e)return;if(n===`keyring`)try{await writeKeyring(Dn,e);return}catch(e){cliDebugPrint(`credentials`,`keyring write failed; falling back to file`,e),downgradeBackendToFile()}let r=readAuthFile();r.proxy={...r.proxy,password:e},r.secretsBackend=`file`,writeAuthFile(r)}async function clearKeyringSecrets(){await deleteKeyring(En),await deleteKeyring(Dn)}async function ensureMigrated(){return An||(An=(async()=>{try{let e=readAuthFile();if(e.secretsBackend||!e.token&&!e.proxy?.password)return;if(await getBackend()===`file`){e.secretsBackend=`file`,writeAuthFile(e);return}try{e.token&&await writeKeyring(En,e.token),e.proxy?.password&&await writeKeyring(Dn,e.proxy.password)}catch(t){cliDebugPrint(`credentials`,`keyring write failed during migration; falling back to file`,t),downgradeBackendToFile(),e.secretsBackend=`file`,writeAuthFile(e);return}delete e.token,e.proxy&&(delete e.proxy.password,Object.keys(e.proxy).length===0&&delete e.proxy),e.secretsBackend=`keyring`,writeAuthFile(e)}catch(e){cliDebugPrint(`credentials`,`migration failed`,e)}})(),An)}const jn=`__CLI_`;function resolveInputKey(){return process.env[F.INPUT_KEY]||process.env[L.INPUT_KEY]||process.env.CRAWLEE_INPUT_KEY||`INPUT`}function inputFileRegExp(e){return RegExp(`(^${$e(e)}(?:\\.[^.]+)?$)`)}function readActorRuntimeConfig(){try{let e=JSON.parse(j(ACTOR_RUNTIME_CONFIG_FILE_PATH(),`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function updateActorRuntimeConfig(e){ensureApifyDirectory(ACTOR_RUNTIME_CONFIG_FILE_PATH()),P(ACTOR_RUNTIME_CONFIG_FILE_PATH(),JSON.stringify({...readActorRuntimeConfig(),...e},null,` `))}const Mn=`apify/actor-runtime:latest`,Nn=`apify-actor-runtime`,Pn=`https://docs.docker.com/get-started/get-docker/`,Fn=`https://podman.io/docs/installation`,In=3333,Ln=3e3,Rn=`http://localhost:${In}`,zn=`http://localhost:${Ln}`,Bn={APIFY_CLIENT_BASE_URL:Rn,APIFY_CONSOLE_URL:zn},Vn=[`docker`,`podman`],Hn=`APIFY_CONTAINER_ENGINE`,Un=`/data`;function runtimeEnvExportLines(){return Object.entries(Bn).map(([e,t])=>`export ${e}=${t}`)}function requestedContainerEngine(t=e.env){let n=t[Hn]?.trim().toLowerCase();return Vn.find(e=>e===n)}async function installedContainerEngines(t=e.env){let n=requestedContainerEngine(t),r=n?[n]:Vn,i=[];for(let e of r)await Re(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: ${Fn}`;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 R(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Exists}}`]);return e.trim()===`true`}return await R(`docker`,[`info`,`--format`,`{{.ServerVersion}}`]),!0}catch{return!1}}function isDigestPinned(e){return e.includes(`@`)}async function imageExistsLocally(e,t){try{return await R(e,[`image`,`inspect`,t]),!0}catch{return!1}}async function isRuntimeContainerRunning(e){try{let{stdout:t}=await R(e,[`ps`,`--filter`,`name=^${Nn}$`,`--format`,`{{.Names}}`]);return t.trim().length>0}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===Un)?.Source,ports:parsePublishedPorts(n)}}async function inspectRuntimeContainer(e){try{let{stdout:t}=await R(e,[`inspect`,Nn,`--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){if(t===`docker`)return unixSocketPath(n.DOCKER_HOST)??`/var/run/docker.sock`;try{let{stdout:e}=await R(`podman`,[`info`,`--format`,`{{.Host.RemoteSocket.Path}}`]),t=e.trim();return unixSocketPath(t)??t}catch{return`/run/podman/podman.sock`}}function socketMountArg(t,n=e.platform){return`${n===`win32`&&t.startsWith(`/`)?`/${t}`:t}:/var/run/docker.sock`}function buildRuntimeRunArgs({image:t,dataDir:n,detach:r,hostSocketPath:i,platform:a=e.platform}){let s=[`run`,`--rm`,`--init`,`--name`,Nn];return r&&s.push(`--detach`),s.push(`-p`,`${In}:${In}`,`-p`,`${Ln}:${Ln}`,`-v`,socketMountArg(i,a),`-v`,`${n}:${Un}`,t),s}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 isConnectedToActorRuntime(){return readActorRuntimeConfig().connected===!0}function setConnectedToActorRuntime(e){updateActorRuntimeConfig({connected:e})}function overridingRuntimeEnvVars(t=e.env){return Object.keys(Bn).filter(e=>t[e]).map(e=>[e,t[e]])}function resolveApiBaseUrl(t=e.env){return t.APIFY_CLIENT_BASE_URL||(isConnectedToActorRuntime()?Rn:void 0)}function resolveConsoleUrl(t=e.env){return t.APIFY_CONSOLE_URL||(isConnectedToActorRuntime()?zn:void 0)}const Wn=et,Gn=Je,getLocalStorageDir=()=>{let t=L.LOCAL_STORAGE_DIR;return e.env[t]||e.env.CRAWLEE_STORAGE_DIR||`storage`},getLocalKeyValueStorePath=t=>{let n=F.DEFAULT_KEY_VALUE_STORE_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.keyValueStores,r)},getLocalDatasetPath=t=>{let n=F.DEFAULT_DATASET_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.datasets,r)},getLocalRequestQueuePath=t=>{let n=F.DEFAULT_REQUEST_QUEUE_ID,r=t||e.env[n]||ge[n];return u(getLocalStorageDir(),_e.requestQueues,r)},getLocalUserInfo=async()=>{await ensureMigrated();let e={};try{let t=await B(AUTH_FILE_PATH(),`utf-8`);e=JSON.parse(t)}catch{}if(await getBackend()===`keyring`){let t=await getToken();t&&(e.token=t);let n=await getProxyPassword();n&&(e.proxy={...e.proxy,password:n})}let t=!!(e.username||e.id);if(!(t||e.token))return{};if(!t)throw Error(`Stale credentials found without user metadata. Please run "apify login" again.`);return e};async function getLoggedClientOrThrow(){let t=await getLoggedClient();if(!t)throw e.exitCode=1,Error(`You are not logged in with your Apify account. Call "apify login" to fix that.`);return t}const resolveToken=async e=>e||(await ensureMigrated(),getToken()),getApifyClientOptions=async(e,t)=>({token:await resolveToken(e),baseUrl:t||resolveApiBaseUrl(),requestInterceptors:[e=>{e.headers??=new Qe;for(let[t,n]of Object.entries(sn))e.headers[t]=n;return e}]});async function getLoggedClient(e,t){let n=await resolveToken(e),r=new Ye(await getApifyClientOptions(n,t)),i;try{i=await r.user(`me`).get()}catch(e){return cliDebugPrint(`[getLoggedClient] error getting user info`,{error:e,apiBaseUrl:t}),null}r.token&&await setToken(r.token,{skipIfUnchanged:!0});let a=i.proxy?.password;a&&await setProxyPassword(a,{skipIfUnchanged:!0}),ensureApifyDirectory(AUTH_FILE_PATH());let s=(()=>{try{return JSON.parse(j(AUTH_FILE_PATH(),`utf-8`))}catch{return{}}})(),c=await getBackend(),l={...s,...i,secretsBackend:c};if(c===`keyring`&&(delete l.token,l.proxy&&typeof l.proxy==`object`)){let{password:e,...t}=l.proxy;Object.keys(t).length>0?l.proxy=t:delete l.proxy}return P(AUTH_FILE_PATH(),JSON.stringify(l,null,` `),{mode:384}),r}const getLocalConfigPath=e=>u(e,G),getJsonFileContent=e=>{if(D(e))return JSON.parse(j(e,{encoding:`utf-8`}))},getLocalConfig=e=>getJsonFileContent(getLocalConfigPath(e)),setLocalConfig=async(t,n)=>{let r=u(n||e.cwd(),G);await z(c(r),{recursive:!0}),P(r,JSON.stringify(t,null,` `))},Kn=[getLocalStorageDir(),`node_modules`,`.venv`],setLocalEnv=async e=>{let t=getLocalKeyValueStorePath();ensureFolderExistsSync(e,getLocalDatasetPath()),ensureFolderExistsSync(e,getLocalRequestQueuePath()),ensureFolderExistsSync(e,t);let n=u(e,`.gitignore`),r=``;D(n)&&(r=j(n,{encoding:`utf-8`}));let i=[];for(let e of Kn)RegExp(`^${$e(e)}$`,`mg`).test(r)||i.push(e);i.length>0&&(r.length>0?(i.unshift(`# Added by Apify CLI`),P(n,`\n${i.join(`
|
|
49
49
|
`)}\n`,{flag:`a`})):P(n,`${i.join(`
|
|
50
50
|
`)}\n`,{flag:`w`}))},qn=new rt(at,it).define({"application/gzip":[`tgz`],"text/typescript":[`ts`,`tsx`,`mts`]},!0),getSourceFileFormat=(e,t)=>{let n=qn.getType(e);return n?n.startsWith(`text/`)||n.includes(`javascript`)||n.includes(`json`)||n.includes(`xml`)||n.includes(`application/node`)||n.includes(`application/toml`)||n.includes(`application/x-sh`)||n.includes(`application/x-httpd-php`)?be.TEXT:be.BASE64:tt(t)===`binary`?be.BASE64:be.TEXT},createSourceFiles=async(e,t)=>e.map(e=>{let n=j(u(t,e)),r=getSourceFileFormat(e,n);return{name:e,format:r,content:r===be.TEXT?n.toString(`utf8`):n.toString(`base64`)}}),getGitignoreFallbackFilter=async e=>{let t=await ot(`**/.gitignore`,{dot:!0,cwd:e,ignore:[`.git/**`],expandDirectories:!1}),n=[];for(let r of t){let t=c(r),i=await B(u(e,r),`utf-8`);n.push({dir:t===`.`?``:t,ig:Wn().add(i)})}let r=c(e);for(;r!==c(r)&&!D(u(r,`.git`));){let t=u(r,`.gitignore`);if(D(t))try{let i=await B(t,`utf-8`),a=f(r,e);n.push({dir:``,ig:Wn().add(i),ancestorPrefix:a})}catch{}r=c(r)}return n.length===0?e=>e:e=>e.filter(e=>{for(let{dir:t,ig:r,ancestorPrefix:i}of n){let n;if(n=t?e.startsWith(`${t}/`)?e.slice(t.length+1):null:i?`${i}/${e}`:e,n!==null&&r.ignores(n))return!1}return!0})},parseActorIgnore=async e=>{let t=u(e,`.actorignore`);if(!D(t))return{excludeFilter:null,forceIncludePatterns:[]};let n=(await B(t,`utf-8`)).split(`
|
|
51
51
|
`),r=[],i=[];for(let e of n){let t=e.trim();!t||t.startsWith(`#`)||(t.startsWith(`!`)?i.push(t.slice(1)):r.push(t))}return{excludeFilter:r.length>0?e=>{let t=Wn().add(r);return e.filter(e=>!t.ignores(e))}:null,forceIncludePatterns:i}},getActorLocalFilePaths=async t=>{let n=t??e.cwd(),r=[`.git/**`,`apify_storage`,`node_modules`,`storage`,`crawlee_storage`],{excludeFilter:i,forceIncludePatterns:a}=await parseActorIgnore(n),gitIgnoreFilter=null;try{let e=Ve(`git ls-files --others --ignored --exclude-standard --directory`,{cwd:n,encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).split(`
|
|
@@ -233,9 +233,10 @@ The API and console URL environment variables keep taking precedence where they
|
|
|
233
233
|
`)});let e=overridingRuntimeEnvVars();e.length&&warning({message:[`These environment variables are set in this shell and take precedence over the connection:`,...e.map(([e,t])=>` ${e}=${t}`),`Unset them to let the connection decide where commands go.`].join(`
|
|
234
234
|
`)}),await findRunningRuntimeEngine()||warning({message:`The Actor runtime is not running - commands will fail until you start it with ${t.white.bold(`apify runtime start --detach`)}.`})}},RuntimeDisconnectCommand=class extends ApifyCommand{static name=`disconnect`;static description=`Reverts 'apify runtime connect': the Apify CLI targets the Apify platform again, unless the API and console URL environment variables point it somewhere else.
|
|
235
235
|
The runtime itself keeps running - stop it with 'apify runtime stop'.`;static group=`Local Actor Development`;static examples=[{description:`Send Apify CLI commands to the Apify platform again.`,command:`apify runtime disconnect`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-runtime-disconnect`;async run(){let e=isConnectedToActorRuntime();setConnectedToActorRuntime(!1),e?success({message:`The Apify CLI no longer targets the local Actor runtime.`}):info({message:`The Apify CLI was not connected to the local Actor runtime.`});let t=overridingRuntimeEnvVars();t.length&&warning({message:[`These environment variables are still set in this shell and keep pointing the CLI away from the Apify platform:`,...t.map(([e,t])=>` ${e}=${t}`),`Unset them to talk to the Apify platform.`].join(`
|
|
236
|
-
`)})}};function installedActorRuntimeImage(){let{image:e}=readActorRuntimeConfig();return e||`apify/actor-runtime:latest`}function rememberInstalledActorRuntimeImage(e){updateActorRuntimeConfig({image:e})}async function ensureActorRuntimeImage({image:n,forcePull:r=!1}){let
|
|
237
|
-
`)}),e.exitCode=1,null}}var RuntimeInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Installs the Actor runtime: verifies this machine has a working container engine (Docker or Podman) and downloads the Actor runtime image ('${Mn}' unless another one is given).\
|
|
238
|
-
|
|
236
|
+
`)})}};function installedActorRuntimeImage(){let{image:e}=readActorRuntimeConfig();return e||`apify/actor-runtime:latest`}function rememberInstalledActorRuntimeImage(e){updateActorRuntimeConfig({image:e})}async function ensureActorRuntimeImage({image:n,forcePull:r=!1,refreshFromRegistry:i=!1}){let a=await findContainerEngine();if(!a){let t=requestedContainerEngine();return error({message:t?`${Hn}=${t} is set, but the '${t}' command was not found.\n ${engineInstallHint(t)}`:`Docker or Podman is required to run the Actor runtime, but neither the 'docker' nor the 'podman' command was found.\n ${engineInstallHint(`docker`)}\n ${engineInstallHint(`podman`)}`}),e.exitCode=1,null}let{engine:s,ready:c}=a;if(!c)return error({message:s===`podman`?`Podman is installed, but its API socket is not being served.\n ${engineDaemonHint(s)}`:`Docker is installed, but the Docker daemon is not running or not reachable.\n ${engineDaemonHint(s)}`}),e.exitCode=1,null;let l=await imageExistsLocally(s,n);if(l&&(isDigestPinned(n)||!i)&&!r)return info({message:`Actor runtime image '${n}' is already available locally.`}),rememberInstalledActorRuntimeImage(n),s;info({message:l?`Checking the registry for a newer Actor runtime image '${n}'...`:`Downloading the Actor runtime image '${n}'...`});try{return await execWithLog({cmd:s,args:[`pull`,n]}),rememberInstalledActorRuntimeImage(n),s}catch{return error({message:[`Could not pull '${n}'.`,` Check that you are online and can access the image - a private repository needs ${t.white.bold(`${s} login`)} first.`,` You can also build the image locally from an actor-runtime checkout instead:`,t.white.bold(` ${s} build -t ${n} .`)].join(`
|
|
237
|
+
`)}),e.exitCode=1,null}}var RuntimeInstallCommand=class extends ApifyCommand{static name=`install`;static description=`Installs the Actor runtime: verifies this machine has a working container engine (Docker or Podman) and downloads the Actor runtime image ('${Mn}' unless another one is given).\nTagged images are always re-checked against the registry, so an outdated local copy gets updated.
|
|
238
|
+
'apify runtime start' then runs the image installed last.
|
|
239
|
+
The engine itself is a prerequisite and is not installed by this command - see ${Pn} or ${Fn}.`;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:X.string({description:`Container image to install as the Actor runtime. Defaults to '${Mn}'.`})};static flags={force:J.boolean({char:`f`,description:`Download the Actor runtime image even when it is already available locally.`,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(`
|
|
239
240
|
`)}))}};const wi=`apify-actor-runtime`,Ti=`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 Ae(u(le(),`apify-runtime-skill-`)),r;try{let{stdout:i}=await R(e,[`create`,t]);return r=i.trim().split(`
|
|
240
241
|
`).at(-1)?.trim(),r?(await R(e,[`cp`,`${r}:/usr/src/app/skills/actor-runtime/.`,n]),await B(u(n,Ti),`utf8`)):null}catch{return null}finally{r&&await R(e,[`rm`,`-f`,r]).catch(()=>{}),await Ne(n,{recursive:!0,force:!0})}}async function resolveRuntimeSkill(){let e=resolveApiBaseUrl()??Rn,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 '${wi}', 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(`
|
|
241
242
|
`)}function skillTargets(t=userHomeDir(),n=e.cwd()){let r=[];t&&r.push({directory:u(t,`.claude`,`skills`,wi),label:`Claude Code`},{directory:u(t,`.agents`,`skills`,wi),label:`Codex and other agents`});for(let[e,t]of[[`.claude`,`this project (Claude Code)`],[`.agents`,`this project`]])D(u(n,e,`skills`))&&r.push({directory:u(n,e,`skills`,wi),label:t});return r}function stampSkill(e,t,n=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 z(e.directory,{recursive:!0}),await H(u(e.directory,Ti),t)}var RuntimeSkillCommand=class extends ApifyCommand{static name=`skill`;static description=`Prints the Actor runtime's Agent Skill - the runtime's own instructions for how to use it.
|
|
@@ -261,4 +262,4 @@ When no path is provided, validates all schemas found in '${G}':
|
|
|
261
262
|
- Dataset schema (from "storages.dataset")
|
|
262
263
|
- Output schema (from "output")
|
|
263
264
|
- Key-Value Store schema (from "storages.keyValueStore")`;static group=`Local Actor Development`;static examples=[{description:`Validate the input schema discovered from the default locations.`,command:`apify validate-schema`},{description:`Validate a specific INPUT_SCHEMA.json file.`,command:`apify validate-schema ./my-schema.json`}];static docsUrl=`https://docs.apify.com/cli/docs/reference#apify-validate-schema`;static args={path:X.string({required:!1,description:`Optional path to your INPUT_SCHEMA.json file. If not provided, validates all schemas in '${G}'.`})};static hiddenAliases=[`vis`];async run(){if(this.args.path){await this.validateInputSchemaAtPath(this.args.path);return}await this.validateAllSchemas()}async validateInputSchemaAtPath(t){await readAndValidateInputSchema({forcePath:t,cwd:e.cwd(),getMessage:e=>`Validating input schema at ${e??t}`}),success({message:`Input schema is valid.`})}async validateAllSchemas(){let t=e.cwd(),n=!1,r=!1;try{let{inputSchema:e,inputSchemaPath:r}=await readInputSchema({cwd:t,throwOnMissing:!0});if(e){n=!0,info({message:`Validating input schema ${r?`at ${r}`:`embedded in '${G}'`}`});let t=new Gn({strict:!1});vt(t,e),success({message:`Input schema is valid.`})}}catch(e){n=!0,r=!0,error({message:e.message})}let i=[{label:`Dataset`,read:()=>readStorageSchema({cwd:t,key:`dataset`,label:`Dataset`,throwOnMissing:!0}),validate:validateDatasetSchema},{label:`Output`,read:()=>readStorageSchema({cwd:t,key:`output`,label:`Output`,getRef:e=>e?.output,throwOnMissing:!0}),validate:validateOutputSchema},{label:`Key-Value Store`,read:()=>readStorageSchema({cwd:t,key:`keyValueStore`,label:`Key-Value Store`,throwOnMissing:!0}),validate:validateKvsSchema}];for(let{label:e,read:t,validate:a}of i)try{let r=t();r&&(n=!0,info({message:`Validating ${e} schema ${r.schemaPath?`at ${r.schemaPath}`:`embedded in '${G}'`}`}),a(r.schema),success({message:`${e} schema is valid.`}))}catch(e){n=!0,r=!0,error({message:e.message})}if(!n)throw Error(`No schemas found. Make sure '${G}' exists and defines at least one schema.`);r&&(e.exitCode=5)}};const Oi=[ActorIndexCommand,ActorsIndexCommand,AuthIndexCommand,BuildsIndexCommand,DatasetsIndexCommand,KeyValueStoresIndexCommand,MCPIndexCommand,RequestQueuesIndexCommand,RunsIndexCommand,RuntimeIndexCommand,SecretsIndexCommand,TasksIndexCommand,TelemetryIndexCommand,TemplatesIndexCommand,ApiCommand,TopLevelCallCommand,UpgradeCommand,InstallCommand,CreateCommand,EditInputSchemaCommand,InfoCommand,WrapScrapyCommand,InitCommand,LoginCommand,LogoutCommand,TopLevelPullCommand,ToplevelPushCommand,RunCommand,ValidateSchemaCommand,HelpCommand],ki=[ActorSetValueCommand,ActorPushDataCommand,ActorGetValueCommand,ActorGetPublicUrlCommand,ActorGetInputCommand,ActorChargeCommand,ActorCalculateMemoryCommand,ActorGenerateSchemaTypesCommand,HelpCommand,UpgradeCommand,InstallCommand,TelemetryIndexCommand];export{runCLI as i,Oi as n,processVersionCheck as r,ki as t};
|
|
264
|
-
//# sourceMappingURL=_register-
|
|
265
|
+
//# sourceMappingURL=_register-BhT_ALLm.js.map
|