apify-cli 0.21.10-beta.0 → 0.21.10-beta.10

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.
Files changed (251) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/actor.js +3 -0
  4. package/dist/actor.js.map +1 -0
  5. package/dist/apify.js +3 -0
  6. package/dist/apify.js.map +1 -0
  7. package/dist/chunk-A3JEYXK4.js +236 -0
  8. package/dist/chunk-A3JEYXK4.js.map +1 -0
  9. package/dist/index.js +2 -3
  10. package/package.json +15 -13
  11. package/dist/commands/_register.js +0 -68
  12. package/dist/commands/_register.js.map +0 -1
  13. package/dist/commands/actor/_index.js +0 -24
  14. package/dist/commands/actor/_index.js.map +0 -1
  15. package/dist/commands/actor/charge.js +0 -84
  16. package/dist/commands/actor/charge.js.map +0 -1
  17. package/dist/commands/actor/get-input.js +0 -10
  18. package/dist/commands/actor/get-input.js.map +0 -1
  19. package/dist/commands/actor/get-public-url.js +0 -52
  20. package/dist/commands/actor/get-public-url.js.map +0 -1
  21. package/dist/commands/actor/get-value.js +0 -18
  22. package/dist/commands/actor/get-value.js.map +0 -1
  23. package/dist/commands/actor/push-data.js +0 -38
  24. package/dist/commands/actor/push-data.js.map +0 -1
  25. package/dist/commands/actor/set-value.js +0 -52
  26. package/dist/commands/actor/set-value.js.map +0 -1
  27. package/dist/commands/actors/_index.js +0 -28
  28. package/dist/commands/actors/_index.js.map +0 -1
  29. package/dist/commands/actors/build.js +0 -6
  30. package/dist/commands/actors/build.js.map +0 -1
  31. package/dist/commands/actors/call.js +0 -224
  32. package/dist/commands/actors/call.js.map +0 -1
  33. package/dist/commands/actors/info.js +0 -203
  34. package/dist/commands/actors/info.js.map +0 -1
  35. package/dist/commands/actors/ls.js +0 -226
  36. package/dist/commands/actors/ls.js.map +0 -1
  37. package/dist/commands/actors/pull.js +0 -150
  38. package/dist/commands/actors/pull.js.map +0 -1
  39. package/dist/commands/actors/push.js +0 -300
  40. package/dist/commands/actors/push.js.map +0 -1
  41. package/dist/commands/actors/rm.js +0 -43
  42. package/dist/commands/actors/rm.js.map +0 -1
  43. package/dist/commands/actors/start.js +0 -125
  44. package/dist/commands/actors/start.js.map +0 -1
  45. package/dist/commands/builds/_index.js +0 -22
  46. package/dist/commands/builds/_index.js.map +0 -1
  47. package/dist/commands/builds/create.js +0 -130
  48. package/dist/commands/builds/create.js.map +0 -1
  49. package/dist/commands/builds/info.js +0 -78
  50. package/dist/commands/builds/info.js.map +0 -1
  51. package/dist/commands/builds/log.js +0 -35
  52. package/dist/commands/builds/log.js.map +0 -1
  53. package/dist/commands/builds/ls.js +0 -141
  54. package/dist/commands/builds/ls.js.map +0 -1
  55. package/dist/commands/builds/rm.js +0 -59
  56. package/dist/commands/builds/rm.js.map +0 -1
  57. package/dist/commands/call.js +0 -5
  58. package/dist/commands/call.js.map +0 -1
  59. package/dist/commands/create.js +0 -264
  60. package/dist/commands/create.js.map +0 -1
  61. package/dist/commands/datasets/_index.js +0 -25
  62. package/dist/commands/datasets/_index.js.map +0 -1
  63. package/dist/commands/datasets/create.js +0 -38
  64. package/dist/commands/datasets/create.js.map +0 -1
  65. package/dist/commands/datasets/get-items.js +0 -84
  66. package/dist/commands/datasets/get-items.js.map +0 -1
  67. package/dist/commands/datasets/info.js +0 -125
  68. package/dist/commands/datasets/info.js.map +0 -1
  69. package/dist/commands/datasets/ls.js +0 -73
  70. package/dist/commands/datasets/ls.js.map +0 -1
  71. package/dist/commands/datasets/push-items.js +0 -70
  72. package/dist/commands/datasets/push-items.js.map +0 -1
  73. package/dist/commands/datasets/rename.js +0 -71
  74. package/dist/commands/datasets/rename.js.map +0 -1
  75. package/dist/commands/datasets/rm.js +0 -48
  76. package/dist/commands/datasets/rm.js.map +0 -1
  77. package/dist/commands/edit-input-schema.js +0 -162
  78. package/dist/commands/edit-input-schema.js.map +0 -1
  79. package/dist/commands/help.js +0 -43
  80. package/dist/commands/help.js.map +0 -1
  81. package/dist/commands/info.js +0 -21
  82. package/dist/commands/info.js.map +0 -1
  83. package/dist/commands/init-wrap-scrapy.js +0 -27
  84. package/dist/commands/init-wrap-scrapy.js.map +0 -1
  85. package/dist/commands/init.js +0 -94
  86. package/dist/commands/init.js.map +0 -1
  87. package/dist/commands/key-value-stores/_index.js +0 -30
  88. package/dist/commands/key-value-stores/_index.js.map +0 -1
  89. package/dist/commands/key-value-stores/create.js +0 -38
  90. package/dist/commands/key-value-stores/create.js.map +0 -1
  91. package/dist/commands/key-value-stores/delete-value.js +0 -61
  92. package/dist/commands/key-value-stores/delete-value.js.map +0 -1
  93. package/dist/commands/key-value-stores/get-value.js +0 -70
  94. package/dist/commands/key-value-stores/get-value.js.map +0 -1
  95. package/dist/commands/key-value-stores/info.js +0 -127
  96. package/dist/commands/key-value-stores/info.js.map +0 -1
  97. package/dist/commands/key-value-stores/keys.js +0 -61
  98. package/dist/commands/key-value-stores/keys.js.map +0 -1
  99. package/dist/commands/key-value-stores/ls.js +0 -70
  100. package/dist/commands/key-value-stores/ls.js.map +0 -1
  101. package/dist/commands/key-value-stores/rename.js +0 -71
  102. package/dist/commands/key-value-stores/rename.js.map +0 -1
  103. package/dist/commands/key-value-stores/rm.js +0 -48
  104. package/dist/commands/key-value-stores/rm.js.map +0 -1
  105. package/dist/commands/key-value-stores/set-value.js +0 -57
  106. package/dist/commands/key-value-stores/set-value.js.map +0 -1
  107. package/dist/commands/login.js +0 -183
  108. package/dist/commands/login.js.map +0 -1
  109. package/dist/commands/logout.js +0 -16
  110. package/dist/commands/logout.js.map +0 -1
  111. package/dist/commands/pull.js +0 -5
  112. package/dist/commands/pull.js.map +0 -1
  113. package/dist/commands/push.js +0 -5
  114. package/dist/commands/push.js.map +0 -1
  115. package/dist/commands/request-queues/_index.js +0 -9
  116. package/dist/commands/request-queues/_index.js.map +0 -1
  117. package/dist/commands/run.js +0 -434
  118. package/dist/commands/run.js.map +0 -1
  119. package/dist/commands/runs/_index.js +0 -23
  120. package/dist/commands/runs/_index.js.map +0 -1
  121. package/dist/commands/runs/abort.js +0 -68
  122. package/dist/commands/runs/abort.js.map +0 -1
  123. package/dist/commands/runs/info.js +0 -238
  124. package/dist/commands/runs/info.js.map +0 -1
  125. package/dist/commands/runs/log.js +0 -32
  126. package/dist/commands/runs/log.js.map +0 -1
  127. package/dist/commands/runs/ls.js +0 -106
  128. package/dist/commands/runs/ls.js.map +0 -1
  129. package/dist/commands/runs/resurrect.js +0 -54
  130. package/dist/commands/runs/resurrect.js.map +0 -1
  131. package/dist/commands/runs/rm.js +0 -58
  132. package/dist/commands/runs/rm.js.map +0 -1
  133. package/dist/commands/secrets/_index.js +0 -25
  134. package/dist/commands/secrets/_index.js.map +0 -1
  135. package/dist/commands/secrets/add.js +0 -22
  136. package/dist/commands/secrets/add.js.map +0 -1
  137. package/dist/commands/secrets/rm.js +0 -18
  138. package/dist/commands/secrets/rm.js.map +0 -1
  139. package/dist/commands/task/_index.js +0 -11
  140. package/dist/commands/task/_index.js.map +0 -1
  141. package/dist/commands/task/run.js +0 -91
  142. package/dist/commands/task/run.js.map +0 -1
  143. package/dist/commands/upgrade.js +0 -74
  144. package/dist/commands/upgrade.js.map +0 -1
  145. package/dist/commands/validate-schema.js +0 -44
  146. package/dist/commands/validate-schema.js.map +0 -1
  147. package/dist/entrypoints/_shared.js +0 -256
  148. package/dist/entrypoints/_shared.js.map +0 -1
  149. package/dist/entrypoints/actor.js +0 -19
  150. package/dist/entrypoints/actor.js.map +0 -1
  151. package/dist/entrypoints/apify.js +0 -18
  152. package/dist/entrypoints/apify.js.map +0 -1
  153. package/dist/index.js.map +0 -1
  154. package/dist/lib/actor.js +0 -74
  155. package/dist/lib/actor.js.map +0 -1
  156. package/dist/lib/command-framework/apify-command.js +0 -426
  157. package/dist/lib/command-framework/apify-command.js.map +0 -1
  158. package/dist/lib/command-framework/args.js +0 -24
  159. package/dist/lib/command-framework/args.js.map +0 -1
  160. package/dist/lib/command-framework/flags.js +0 -99
  161. package/dist/lib/command-framework/flags.js.map +0 -1
  162. package/dist/lib/command-framework/help/CommandHelp.js +0 -228
  163. package/dist/lib/command-framework/help/CommandHelp.js.map +0 -1
  164. package/dist/lib/command-framework/help/CommandWithSubcommands.js +0 -75
  165. package/dist/lib/command-framework/help/CommandWithSubcommands.js.map +0 -1
  166. package/dist/lib/command-framework/help/_BaseCommandRenderer.js +0 -63
  167. package/dist/lib/command-framework/help/_BaseCommandRenderer.js.map +0 -1
  168. package/dist/lib/command-framework/help/consts.js +0 -27
  169. package/dist/lib/command-framework/help/consts.js.map +0 -1
  170. package/dist/lib/command-framework/help.js +0 -105
  171. package/dist/lib/command-framework/help.js.map +0 -1
  172. package/dist/lib/commands/pretty-print-bytes.js +0 -13
  173. package/dist/lib/commands/pretty-print-bytes.js.map +0 -1
  174. package/dist/lib/commands/pretty-print-status.js +0 -29
  175. package/dist/lib/commands/pretty-print-status.js.map +0 -1
  176. package/dist/lib/commands/read-stdin.js +0 -42
  177. package/dist/lib/commands/read-stdin.js.map +0 -1
  178. package/dist/lib/commands/resolve-actor-context.js +0 -70
  179. package/dist/lib/commands/resolve-actor-context.js.map +0 -1
  180. package/dist/lib/commands/resolve-input.js +0 -162
  181. package/dist/lib/commands/resolve-input.js.map +0 -1
  182. package/dist/lib/commands/responsive-table.js +0 -129
  183. package/dist/lib/commands/responsive-table.js.map +0 -1
  184. package/dist/lib/commands/run-on-cloud.js +0 -126
  185. package/dist/lib/commands/run-on-cloud.js.map +0 -1
  186. package/dist/lib/commands/storage-size.js +0 -8
  187. package/dist/lib/commands/storage-size.js.map +0 -1
  188. package/dist/lib/commands/storages.js +0 -30
  189. package/dist/lib/commands/storages.js.map +0 -1
  190. package/dist/lib/consts.js +0 -69
  191. package/dist/lib/consts.js.map +0 -1
  192. package/dist/lib/create-utils.js +0 -156
  193. package/dist/lib/create-utils.js.map +0 -1
  194. package/dist/lib/exec.js +0 -34
  195. package/dist/lib/exec.js.map +0 -1
  196. package/dist/lib/files.js +0 -54
  197. package/dist/lib/files.js.map +0 -1
  198. package/dist/lib/hooks/runtimes/javascript.js +0 -86
  199. package/dist/lib/hooks/runtimes/javascript.js.map +0 -1
  200. package/dist/lib/hooks/runtimes/python.js +0 -80
  201. package/dist/lib/hooks/runtimes/python.js.map +0 -1
  202. package/dist/lib/hooks/runtimes/utils.js +0 -16
  203. package/dist/lib/hooks/runtimes/utils.js.map +0 -1
  204. package/dist/lib/hooks/useActorConfig.js +0 -177
  205. package/dist/lib/hooks/useActorConfig.js.map +0 -1
  206. package/dist/lib/hooks/useCLIMetadata.js +0 -73
  207. package/dist/lib/hooks/useCLIMetadata.js.map +0 -1
  208. package/dist/lib/hooks/useCLIVersionCheck.js +0 -91
  209. package/dist/lib/hooks/useCLIVersionCheck.js.map +0 -1
  210. package/dist/lib/hooks/useCommandSuggestions.js +0 -37
  211. package/dist/lib/hooks/useCommandSuggestions.js.map +0 -1
  212. package/dist/lib/hooks/useCwdProject.js +0 -174
  213. package/dist/lib/hooks/useCwdProject.js.map +0 -1
  214. package/dist/lib/hooks/useLocalState.js +0 -56
  215. package/dist/lib/hooks/useLocalState.js.map +0 -1
  216. package/dist/lib/hooks/useModuleVersion.js +0 -103
  217. package/dist/lib/hooks/useModuleVersion.js.map +0 -1
  218. package/dist/lib/hooks/useStdin.js +0 -65
  219. package/dist/lib/hooks/useStdin.js.map +0 -1
  220. package/dist/lib/input_schema.js +0 -130
  221. package/dist/lib/input_schema.js.map +0 -1
  222. package/dist/lib/outputs.js +0 -45
  223. package/dist/lib/outputs.js.map +0 -1
  224. package/dist/lib/project_analyzer.js +0 -30
  225. package/dist/lib/project_analyzer.js.map +0 -1
  226. package/dist/lib/projects/CrawleeAnalyzer.js +0 -20
  227. package/dist/lib/projects/CrawleeAnalyzer.js.map +0 -1
  228. package/dist/lib/projects/OldApifySDKAnalyzer.js +0 -38
  229. package/dist/lib/projects/OldApifySDKAnalyzer.js.map +0 -1
  230. package/dist/lib/projects/scrapy/ScrapyProjectAnalyzer.js +0 -73
  231. package/dist/lib/projects/scrapy/ScrapyProjectAnalyzer.js.map +0 -1
  232. package/dist/lib/projects/scrapy/Spider.js +0 -13
  233. package/dist/lib/projects/scrapy/Spider.js.map +0 -1
  234. package/dist/lib/projects/scrapy/SpiderFileAnalyzer.js +0 -20
  235. package/dist/lib/projects/scrapy/SpiderFileAnalyzer.js.map +0 -1
  236. package/dist/lib/projects/scrapy/wrapScrapyProject.js +0 -113
  237. package/dist/lib/projects/scrapy/wrapScrapyProject.js.map +0 -1
  238. package/dist/lib/projects/shared.js +0 -13
  239. package/dist/lib/projects/shared.js.map +0 -1
  240. package/dist/lib/secrets.js +0 -106
  241. package/dist/lib/secrets.js.map +0 -1
  242. package/dist/lib/telemetry.js +0 -86
  243. package/dist/lib/telemetry.js.map +0 -1
  244. package/dist/lib/types.js +0 -4
  245. package/dist/lib/types.js.map +0 -1
  246. package/dist/lib/utils/cliDebugPrint.js +0 -7
  247. package/dist/lib/utils/cliDebugPrint.js.map +0 -1
  248. package/dist/lib/utils/confirm.js +0 -28
  249. package/dist/lib/utils/confirm.js.map +0 -1
  250. package/dist/lib/utils.js +0 -457
  251. package/dist/lib/utils.js.map +0 -1
@@ -0,0 +1,236 @@
1
+ var Ra=Object.defineProperty;var l=(t,e)=>Ra(t,"name",{value:e,configurable:!0});import de from"process";import ue from"chalk";import{satisfies as Hc}from"semver";import Jc from"yargs/yargs";import Oi from"chalk";import Cc from"indent-string";import Ic from"widest-line";import $c from"wrap-ansi";import at from"chalk";function qe(t){t.stdoutOutput&&console.log(...t.stdoutOutput),t.stderrOutput&&console.error(...t.stderrOutput)}l(qe,"internalLog");function _(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[t.message]})}l(_,"simpleLog");function m(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.red("Error:"),t.message]})}l(m,"error");function x(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.yellow.bold("Warning:"),t.message]})}l(x,"warning");function R(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.green("Success:"),t.message]})}l(R,"success");function ye(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.gray("Run:"),t.message]})}l(ye,"run");function v(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.white("Info:"),t.message]})}l(v,"info");function Ks(t){qe({[t.stdout?"stdoutOutput":"stderrOutput"]:[at.blue(t.message),t.url]})}l(Ks,"link");import Ut from"chalk";import Ei from"indent-string";import Ri from"widest-line";import _i from"wrap-ansi";import{realpathSync as _a}from"fs";import{dirname as xa}from"path";var qs="0.0.0";var Oa="0.21.10-beta.10",Na="0e634801dd5b0e4c9dd165a14e18b213b133820f";function La(){if(process.env.APIFY_CLI_MARKED_INSTALL_METHOD)return process.env.APIFY_CLI_MARKED_INSTALL_METHOD;if(process.env.APIFY_CLI_BUNDLE)return"bundle";let t=process.argv[1];if(!t)return x({message:"Failed to detect install method of CLI, assuming npm"}),"npm";let e=_a(t);return process.env.VOLTA_HOME&&e.includes(process.env.VOLTA_HOME)?"volta":e.includes("homebrew/Cellar")||e.includes("linuxbrew/Cellar")?"homebrew":process.env.PNPM_HOME&&e.includes(process.env.PNPM_HOME)?"pnpm":process.env.BUN_INSTALL&&e.includes(process.env.BUN_INSTALL)?"bun":"npm"}l(La,"detectInstallMethod");function Da(){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}}l(Da,"getRuntimeInfo");var $t=null;function ee(){if($t)return $t;let t=La(),e=Da();return $t={version:Oa,hash:Na,arch:process.env.APIFY_BUNDLE_ARCH??process.arch,platform:process.platform==="win32"?"windows":process.platform,runtime:e.runtime,extraRuntimeData:e.nodeVersion?`(emulating node ${e.nodeVersion})`:"",installMethod:t,get fullVersionString(){return`apify-cli/${this.version} (${this.hash.slice(0,7)}) running on ${this.platform}-${this.arch} with ${this.runtime}-${e.version}${this.extraRuntimeData?` ${this.extraRuntimeData}`:""}, installed via ${this.installMethod}`}},t==="bundle"&&($t.installPath=xa(process.execPath)),$t}l(ee,"useCLIMetadata");import{createWriteStream as Ka,existsSync as ne,mkdirSync as qa,readdirSync as ni,readFileSync as Ot,writeFileSync as ir}from"fs";import{mkdir as Wa,readFile as za}from"fs/promises";import{get as Xa}from"https";import{dirname as ai,join as Ae}from"path";import ie from"process";import{finished as Za}from"stream/promises";import{DurationFormatter as ci,TimeTypes as Ze}from"@sapphire/duration";import{Timestamp as os}from"@sapphire/timestamp";import Qa from"adm-zip";import ec from"ajv/dist/2019.js";import{ApifyClient as li}from"apify-client";import tc from"archiver";import{AxiosHeaders as rc}from"axios";import oc from"escape-string-regexp";import{globby as ui}from"globby";import{getEncoding as sc}from"istextorbinary";import{Mime as ic}from"mime";import nc from"mime/types/other.js";import ac from"mime/types/standard.js";import{gte as cc,minVersion as lc,satisfies as uc}from"semver";import{ACTOR_ENV_VARS as ss,ACTOR_JOB_TERMINAL_STATUSES as dc,ACTOR_NAME as xt,APIFY_ENV_VARS as mc,KEY_VALUE_STORE_KEYS as ii,LOCAL_ACTOR_ENV_VARS as is,LOCAL_STORAGE_SUBDIRS as ns,SOURCE_FILE_FORMATS as _t}from"@apify/consts";import{homedir as ka}from"os";import{join as We}from"path";import{KEY_VALUE_STORE_KEYS as Fa,META_ORIGINS as Ua}from"@apify/consts";var Ws={name:"apify-cli",version:"0.21.10-beta.10",description:"Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",exports:"./dist/index.js",type:"module",scripts:{"dev:apify":"tsx ./src/entrypoints/apify.ts","dev:actor":"tsx ./src/entrypoints/actor.ts","test:all":"yarn test:local && yarn test:api","test:local":"vitest run --testNamePattern '^((?!\\[api]).)*$' --exclude ./test/api","test:api":"vitest run --testNamePattern '\\[api\\]'","test:python":"vitest run --testNamePattern '\\[python\\]'","test:cucumber":'cross-env NODE_OPTIONS="--import tsx" cucumber-js',lint:"eslint src test scripts features --ext .ts,.cjs,.mjs","lint:fix":"eslint src test scripts features --fix --ext .ts,.cjs,.mjs",format:'biome format . && prettier --check "**/*.{md,yml,yaml}"',"format:fix":'biome format --write . && prettier --write "**/*.{md,yml,yaml}"',clean:"rimraf dist",build:"yarn clean && tsc && tsup","build-bundles":"bun run scripts/build-cli-bundles.ts",prepack:"yarn insert-cli-metadata && yarn build && yarn update-docs","insert-cli-metadata":"tsx scripts/insert-cli-metadata.ts","update-docs":"tsx scripts/generate-cli-docs.ts",postinstall:`node -e "console.log('We have an active developer community on Discord. You can find it on https://discord.gg/crawlee-apify-801163717915574323.');"`},files:["dist"],bin:{actor:"./dist/actor.js",apify:"./dist/apify.js","apify-cli":"./dist/apify.js"},contributors:["Jakub Drobn\xEDk <jakub.drobnik@apify.com>","Jan Curn <jan@apify.com>","Vlad Frangu <vlad.frangu@apify.com>"],repository:{type:"git",url:"git+https://github.com/apify/apify-cli.git"},keywords:["apify","client","node","command","line","bash"],author:{name:"Apify",email:"support@apify.com",url:"https://www.apify.com"},license:"Apache-2.0",bugs:{url:"https://github.com/apify/apify-cli/issues"},homepage:"https://github.com/apify/apify-cli#readme",engines:{node:">=18"},dependencies:{"@apify/actor-templates":"^0.1.5","@apify/consts":"^2.36.0","@apify/input_schema":"^3.17.0","@apify/utilities":"^2.15.1","@crawlee/memory-storage":"^3.12.0","@inquirer/core":"^10.1.15","@inquirer/input":"^4.2.1","@inquirer/password":"^4.0.17","@inquirer/select":"^4.3.1","@root/walk":"~1.1.0","@sapphire/duration":"^1.1.2","@sapphire/result":"^2.7.2","@sapphire/timestamp":"^1.0.3","@skyra/jaro-winkler":"^1.1.1","adm-zip":"~0.5.15",ajv:"~8.17.1","apify-client":"^2.12.6",archiver:"~7.0.1",axios:"^1.11.0",chalk:"~5.5.0","cli-table3":"^0.6.5","computer-name":"~0.1.0",configparser:"~0.3.10",cors:"~2.8.5","detect-indent":"~7.0.1","escape-string-regexp":"~5.0.0",execa:"^9.5.2",express:"~5.1.0",globby:"~14.1.0",handlebars:"~4.7.8","indent-string":"^5.0.0","is-ci":"~4.1.0",istextorbinary:"~9.5.0",jju:"~1.4.0","js-levenshtein":"^1.1.6","lodash.clonedeep":"^4.5.0",mime:"~4.0.4",mixpanel:"~0.18.0",open:"~10.2.0",ow:"~2.0.0",rimraf:"~6.0.1",semver:"~7.7.0","string-width":"^7.2.0","strip-ansi":"^7.1.0",tiged:"~2.12.7",which:"^5.0.0","widest-line":"^5.0.0","wrap-ansi":"^9.0.0",yargs:"^17.7.2"},devDependencies:{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@biomejs/biome":"^2.0.0","@crawlee/types":"^3.11.1","@cucumber/cucumber":"^12.0.0","@types/adm-zip":"^0.5.5","@types/archiver":"^6.0.2","@types/bun":"^1.2.5","@types/chai":"^4.3.17","@types/cors":"^2.8.17","@types/execa":"^2.0.2","@types/express":"^5.0.0","@types/fs-extra":"^11","@types/is-ci":"^3.0.4","@types/jju":"^1.4.5","@types/js-levenshtein":"^1","@types/lodash.clonedeep":"^4","@types/mime":"^4.0.0","@types/node":"^22.0.0","@types/semver":"^7.5.8","@types/which":"^3.0.4","@types/yargs":"^17.0.33","@yarnpkg/core":"^4.1.2",apify:"^3.2.4",chai:"^4.4.1","cross-env":"^10.0.0",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","lint-staged":"^16.0.0","mdast-util-from-markdown":"^2.0.2","mock-stdin":"^1.0.0",prettier:"^3.5.3",tsup:"^8.5.0",tsx:"^4.16.5",typescript:"^5.8.3","typescript-eslint":"^8.31.0",vitest:"^3.0.0"},volta:{node:"22.18.0",yarn:"4.9.2"},packageManager:"yarn@4.9.2",devEngines:{runtime:[{name:"node",version:">= 20",onFail:"error"},{name:"bun",version:">= 1.2.5",onFail:"ignore"}],packageManager:{name:"yarn",version:">= 4",onFail:"warn"}},"lint-staged":{"*":"biome format --write --no-errors-on-unmatched","*.{mjs,js,ts}":"eslint --fix --ext mjs,js,ts","*.md":"prettier --write"}};var ze="storage",Qo="apify_storage",es=1,er={actorSpecification:es,name:null,version:"0.0",buildTag:"latest",environmentVariables:{}},zs={SCRAPY:"scrapy",CRAWLEE:"crawlee",PRE_CRAWLEE_APIFY_SDK:"apify",UNKNOWN:"unknown"},Xs=1440*60*1e3,ct=l(()=>{let t=We(ka(),".apify");return process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__?We(t,process.env.__APIFY_INTERNAL_TEST_AUTH_PATH__):t},"GLOBAL_CONFIGS_FOLDER"),se=l(()=>We(ct(),"auth.json"),"AUTH_FILE_PATH"),tr=l(()=>We(ct(),"secrets.json"),"SECRETS_FILE_PATH"),rr=l(()=>We(ct(),"state.json"),"STATE_FILE_PATH"),De=l(()=>We(ct(),"telemetry.json"),"TELEMETRY_FILE_PATH"),or="apify.json",ts=".actor",ja="actor.json",M=We(ts,ja),rs=new RegExp(`^${Fa.INPUT}\\..*`),we=Ws.engines.node,Zs={"X-Apify-Request-Origin":Ua.CLI},Xe="3.9.0",Qs=".venv",ei="ea75e434d4b4d2405d79ed9d14bfc93b";import{existsSync as Ma,mkdirSync as Ba}from"fs";import{readFile as Va,stat as ti,unlink as Ya,writeFile as Ga}from"fs/promises";import{join as ri,sep as Ha}from"path";import{rimraf as Ja}from"rimraf";var oi=l(async(t,e={},r=null)=>{let o=await Va(t,"utf-8"),s=JSON.parse(o),i;r?(i=s,i[r]={...s[r],...e}):i={...s,...e},await Ga(t,JSON.stringify(i,null," "))},"updateLocalJson"),sr=l((t,e)=>{e||(e=t,t="."),e.split(Ha).reduce((o,s)=>(o=ri(o,s),Ma(o)||Ba(o),o),t)},"ensureFolderExistsSync"),Et=l(async t=>{await Ja(t)},"rimrafPromised"),Rt=l(async t=>{(await ti(t)).isFile()&&await Ya(t)},"deleteFile"),si=l(async(t,e)=>(await Promise.all(t.map(async s=>ti(ri(e,s))))).map(s=>s.size).reduce((s,i)=>s+i,0),"sumFilesSizeInBytes");var lt=ec,nr=l(async t=>new Promise((e,r)=>{Xa(t,o=>{o.statusCode===301||o.statusCode===302?(e(nr(o.headers.location)),o.destroy()):e(o)}).on("error",r)}),"httpsGet"),ae=l(()=>{let t=mc.LOCAL_STORAGE_DIR;return ie.env[t]||ie.env.CRAWLEE_STORAGE_DIR||ze},"getLocalStorageDir"),Te=l(t=>{let e=ss.DEFAULT_KEY_VALUE_STORE_ID,r=t||ie.env[e]||is[e];return Ae(ae(),ns.keyValueStores,r)},"getLocalKeyValueStorePath"),di=l(t=>{let e=ss.DEFAULT_DATASET_ID,r=t||ie.env[e]||is[e];return Ae(ae(),ns.datasets,r)},"getLocalDatasetPath"),mi=l(t=>{let e=ss.DEFAULT_REQUEST_QUEUE_ID,r=t||ie.env[e]||is[e];return Ae(ae(),ns.requestQueues,r)},"getLocalRequestQueuePath"),k=l(async()=>{let t={};try{let e=await za(se(),"utf-8");t=JSON.parse(e)}catch{return{}}if(!t.username&&!t.id)throw new Error('Corrupted local user info was found. Please run "apify login" to fix it.');return t},"getLocalUserInfo");async function S(){let t=await Nt();if(!t)throw new Error('You are not logged in with your Apify account. Call "apify login" to fix that.');return t}l(S,"getLoggedClientOrThrow");var pi=l(t=>{if(!t&&ne(ct())&&ne(se())){let e=Ot(se(),"utf-8");return JSON.parse(e).token}return t},"getTokenWithAuthFileFallback"),as=l((t,e)=>(t=pi(t),{token:t,baseUrl:e||ie.env.APIFY_CLIENT_BASE_URL,requestInterceptors:[r=>{r.headers??=new rc;for(let[o,s]of Object.entries(Zs))r.headers[o]=s;return r}]}),"getApifyClientOptions");async function Nt(t,e){t=pi(t);let r=new li(as(t,e)),o;try{o=await r.user("me").get()}catch{return null}return Qe(se()),ir(se(),JSON.stringify({token:r.token,...o},null," ")),r}l(Nt,"getLoggedClient");var cs=l(t=>Ae(t,M),"getLocalConfigPath"),ve=l(t=>{if(ne(t))return JSON.parse(Ot(t,{encoding:"utf-8"}))},"getJsonFileContent"),Pe=l(t=>ve(cs(t)),"getLocalConfig"),ar=l(async(t,e)=>{let r=Ae(e||ie.cwd(),M);await Wa(ai(r),{recursive:!0}),ir(r,JSON.stringify(t,null," "))},"setLocalConfig"),pc=[ae(),"node_modules",".venv"],cr=l(async t=>{let e=Te();sr(t,di()),sr(t,mi()),sr(t,e);let r=Ae(t,".gitignore"),o="";ne(r)&&(o=Ot(r,{encoding:"utf-8"}));let s=[];for(let i of pc)RegExp(`^${oc(i)}$`,"mg").test(o)||s.push(i);s.length>0&&(o.length>0?(s.unshift("# Added by Apify CLI"),ir(r,`
2
+ ${s.join(`
3
+ `)}
4
+ `,{flag:"a"})):ir(r,`${s.join(`
5
+ `)}
6
+ `,{flag:"w"}))},"setLocalEnv"),fi=new ic(ac,nc).define({"application/gzip":["tgz"],"text/typescript":["ts","tsx","mts"]},!0),fc=l((t,e)=>{let r=fi.getType(t);return r?r.startsWith("text/")||r.includes("javascript")||r.includes("json")||r.includes("xml")||r.includes("application/node")||r.includes("application/toml")||r.includes("application/x-sh")||r.includes("application/x-httpd-php")?_t.TEXT:_t.BASE64:sc(e)==="binary"?_t.BASE64:_t.TEXT},"getSourceFileFormat"),gi=l(async(t,e)=>t.map(r=>{let o=Ot(Ae(e,r)),s=fc(r,o);return{name:r,format:s,content:s===_t.TEXT?o.toString("utf8"):o.toString("base64")}}),"createSourceFiles"),hi=l(async t=>ui(["*","**/**"],{ignore:[".git/**","apify_storage","node_modules","storage","crawlee_storage"],gitignore:!0,dot:!0,cwd:t}),"getActorLocalFilePaths"),yi=l(async(t,e,r)=>{ne(t)&&await Rt(t);let o=Ka(t),s=tc("zip");s.pipe(o),e.forEach(i=>s.glob(i,{cwd:r})),await s.finalize()},"createActZip"),Lt=l(t=>{let e=Te();if(!ne(Ae(t,e)))return;let s=ni(Ae(t,e)).find(a=>!!a.match(rs));if(!s)return;let i=Ot(Ae(t,e,s)),n=fi.getType(s);return{body:i,contentType:n,fileName:s}},"getLocalInput"),wi=l(async()=>{let t=mi();ne(ae())&&ne(t)&&await Et(t)},"purgeDefaultQueue"),Ai=l(async()=>{let t=di();ne(ae())&&ne(t)&&await Et(t)},"purgeDefaultDataset"),bi=l(async()=>{let t=Te();if(!ne(ae())||!ne(t))return;let e=ni(t),r=[];e.forEach(o=>{o.match(rs)||r.push(Rt(Ae(t,o)))}),await Promise.all(r)},"purgeDefaultKeyValueStore"),Se=l(async({job:t,timeoutMillis:e,apifyClient:r})=>{let{id:o,status:s}=t,i=r||new li({baseUrl:ie.env.APIFY_CLIENT_BASE_URL});if(dc.includes(s)){if(ie.env.APIFY_NO_LOGS_IN_TESTS)return;let n=await i.log(o).get();ie.stderr.write(n);return}return new Promise(async n=>{let a=await i.log(o).stream();if(!a){n("no-logs");return}let c=null;a.on("data",d=>{ie.env.APIFY_NO_LOGS_IN_TESTS||ie.stderr.write(d.toString())}),a.once("end",()=>{n("finished"),c&&clearTimeout(c)}),e&&(c=setTimeout(()=>{a.destroy(),n("timeouts")},e))})},"outputJobLog");var Ti=l(async()=>(await ui([`${ae()}/**`,`!${Te()}/${ii.INPUT}.*`,`!${Te()}/${ii.INPUT}_CLI-*`])).length===0,"checkIfStorageIsEmpty"),Dt=l(t=>{if(!xt.REGEX.test(t))throw new Error("The Actor name must be a DNS hostname-friendly string (e.g. my-newest-actor).");if(t.length<xt.MIN_LENGTH)throw new Error("The Actor name must be at least 3 characters long.");if(t.length>xt.MAX_LENGTH)throw new Error("The Actor name must be a maximum of 30 characters long.")},"validateActorName"),vi=l(t=>{let e=t.replaceAll(/[^a-zA-Z0-9-]/g,"-");return e.length<xt.MIN_LENGTH&&(e=`${e}-apify-actor`),e=e.replaceAll(/^-+/g,"").replaceAll(/-+$/g,""),e.slice(0,xt.MAX_LENGTH)},"sanitizeActorName"),lr=l(t=>uc(t,`^${Xe}`),"isPythonVersionSupported"),ur=l(t=>{let e=lc(we);return cc(t,e)},"isNodeVersionSupported"),dr=l(async({url:t,pathTo:e})=>{let r=await nr(t),o=[];r.on("data",i=>o.push(i)),await Za(r),new Qa(Buffer.concat(o)).extractAllTo(e,!0)},"downloadAndUnzip");function Qe(t){let e=ai(t);qa(e,{recursive:!0})}l(Qe,"ensureApifyDirectory");var B=new os("YYYY-MM-DD [at] HH:mm:ss"),Pt=new os(`YYYY-MM-DD[
7
+ ]HH:mm:ss`),Si=new os("YYYY-MM-DD"),kt=new ci,oe=new ci({[Ze.Day]:{DEFAULT:"d"},[Ze.Hour]:{DEFAULT:"h"},[Ze.Minute]:{DEFAULT:"m"},[Ze.Month]:{DEFAULT:"M"},[Ze.Second]:{DEFAULT:"s"},[Ze.Week]:{DEFAULT:"w"},[Ze.Year]:{DEFAULT:"y"}});function mr(t,e){if("groupBy"in Object)return Object.groupBy(t,e);let r={},o=0;for(let s of t){let i=e(s,o++);r[i]||(r[i]=[]),r[i].push(s)}return r}l(mr,"objectGroupBy");function Ci(t,e){let r=new Map,o=0;for(let s of t){let i=e(s,o++),n=r.get(i);n?n.push(s):r.set(i,[s])}return r}l(Ci,"mapGroupBy");function N(t){console.log(JSON.stringify(t,null,2))}l(N,"printJsonToStdout");import pr from"chalk";import ls from"indent-string";import wc from"string-width";import Ac from"strip-ansi";import $i from"widest-line";import us from"wrap-ansi";import gc from"chalk";import hc from"indent-string";import Ii from"string-width";import yc from"wrap-ansi";var ke;function re(){if(ke)return ke;let t=Number(process.env.APIFY_CLI_MAX_LINE_WIDTH);if(!Number.isNaN(t))ke=t;else if(!process.stdout.isTTY)ke=80;else{let e=process.stdout.getWindowSize?.()[0]??-1;e<1?ke=80:e<40?ke=40:ke=e}return ke}l(re,"getMaxLineWidth");var ut=class{static{l(this,"BaseCommandRenderer")}command;entrypoint;constructor(e,r){this.entrypoint=e,this.command=r}pushShortDescription(e){this.command.shortDescription?e.push(this.command.shortDescription,""):this.command.description&&e.push(this.command.description.split(`
8
+ `)[0],"")}pushDescription(e){if(!this.command.description)return;e.push(gc.bold("DESCRIPTION"));let r=yc(this.command.description,re()-2,{trim:!1}),o=hc(r,2);e.push(o),e.push("")}pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:e,itemToAdd:r,indentSize:o}){let s=Ii(e.join(" ").split(`
9
+ `).at(-1)||"")+o,i=Ii(r);s+i>re()&&e.push(`
10
+ `),e.push(r)}kebabFlagName(e){return ce(le(e)).toLowerCase()}makeFlagString(e,r){let o=this.kebabFlagName(e),s=r.char?`-${r.char}`:`--${o}`;switch(r.flagTag){case"boolean":return s;case"string":case"integer":{let i=r.choicesType?.length?`${r.choicesType.join("|")}`:"<value>";return`${s} ${i}`}default:throw new RangeError(`Unhandled flag type: ${r.flagTag}`)}}};var fr=class extends ut{static{l(this,"CommandHelp")}render(){let e=[];return this.pushShortDescription(e),this.pushUsageString(e),this.command.description&&this.pushDescription(e),e.join(`
11
+ `).trim()}selectiveRender(e){let r=[];return e.showShortDescription&&this.pushShortDescription(r),e.showUsageString&&this.pushUsageString(r),e.showDescription&&this.command.description&&this.pushDescription(r),r.join(`
12
+ `).trim()}pushUsageString(e){e.push(pr.bold("USAGE"));let r=`$ ${this.entrypoint} ${this.command.name}`,o=2+wc(r),s=[r],i=Object.entries(this.command.args??{});if(i.length)for(let[f,p]of i){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:p.required?`<${f}>`:`[${f}]`,indentSize:o})}let n=Object.entries(this.command.flags??{}).filter(([,f])=>{if(typeof f=="string")throw new RangeError("This is a type-check only value, do not actually use it");return!f.hidden});this.command.enableJsonFlag&&n.push(["json",{choicesType:null,flagTag:"boolean",hasDefault:!1,required:!1,stdin:null,builder:null,aliases:void 0,char:void 0,description:"Format the command output as JSON",hidden:void 0,exclusive:void 0}]);let a=new Map(n.sort((f,p)=>{if(typeof f[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(typeof p[1]=="string")throw new RangeError("This is a type-check only value, do not actually use it");return f[1].required&&!p[1].required?-1:!f[1].required&&p[1].required?1:f[0].localeCompare(p[0])})),c=new Set;if(n.length)for(let[f,p]of a){if(typeof p=="string")throw new RangeError("This is a type-check only value, do not actually use it");if(c.has(f))continue;let g=p.required,b=[this.makeFlagString(f,p)];if(p.exclusive?.length)for(let C of p.exclusive){c.add(C);let T=a.get(C),I=this.makeFlagString(C,T);b.push(I),T.required&&(g=!0)}this.pushNewLineBeforeNewEntryIfLengthIsPastTheLimit({state:s,itemToAdd:g?b.join(" | "):`[${b.join(" | ")}]`,indentSize:o})}let d=us(s.join(" "),re()-o),u=ls(d,o+1).trim();e.push(` ${u}`,""),i.length&&this.pushArguments(e,i),n.length&&this.pushFlags(e,a)}pushArguments(e,r){if(!r.length)return;e.push(pr.bold("ARGUMENTS"));let o=$i(r.map(([s])=>s).join(`
13
+ `));for(let[s,i]of r){let n=`${s.padEnd(o)} ${i.description}`,a=us(n,re()-o-2),c=ls(a,o+2+2).trim();e.push(` ${c}`)}e.push("")}pushFlags(e,r){if(!r.size)return;e.push(pr.bold("FLAGS"));let o=new Map;for(let[i,n]of r){let a=[];switch(n.char?a.push(`-${n.char},`):a.push(" ".repeat(3)),n.flagTag){case"boolean":a.push(`--${this.kebabFlagName(i)}`);break;case"string":case"integer":{let c=n.choicesType?"<option>":"<value>";a.push(`--${this.kebabFlagName(i)}=${pr.underline(c)}`);break}default:throw new Error(`Unhandled flag tag: ${n.flagTag}`)}o.set(a.join(" "),n)}let s=$i([...o.keys()].join(`
14
+ `));for(let[i,n]of o){let a=s-Ac(i).length,c=`${i}${" ".repeat(a)} ${n.description??""}`;n.choicesType?.length&&(c+=`
15
+ <options: ${n.choicesType.join("|")}>`);let d=us(c,re()-s),u=ls(d,s).trim().split(`
16
+ `).map(f=>/^-[a-z]/.test(f.trim())?f:` ${f}`).join(`
17
+ `);e.push(` ${u}`)}e.push("")}};import bc from"chalk";import Tc from"indent-string";import vc from"widest-line";import Sc from"wrap-ansi";var Ft=class extends ut{static{l(this,"CommandWithSubcommandsHelp")}render(){let e=[];return this.pushShortDescription(e),this.command.description&&this.pushDescription(e),this.pushSubcommands(e),e.join(`
18
+ `).trim()}selectiveRender(e){let r=[];return e.showShortDescription&&this.pushShortDescription(r),e.showDescription&&this.command.description&&this.pushDescription(r),e.showSubcommands&&this.pushSubcommands(r),r.join(`
19
+ `).trim()}pushSubcommands(e){if(!this.command.subcommands?.length)return;e.push(bc.bold("SUBCOMMANDS"));let r=vc(this.command.subcommands.map(o=>`${this.command.name} ${o.name}`).join(`
20
+ `));for(let o of this.command.subcommands){let s=o.shortDescription||o.description?.split(`
21
+ `)[0]||"",i=`${this.command.name} ${o.name.padEnd(r-this.command.name.length-1)} ${s}`,n=Sc(i,re()-r-2),a=Tc(n,r+2+2).trim();e.push(` ${a}`)}e.push("")}};var jt=new Map;function ds(t,e){if(e.name.toLowerCase()!==e.name){m({message:`Command name "${e.name}" is not correctly set up internally. Make sure you fill out the "name" field in the command class extension.`});return}if(e.subcommands?.length){jt.set(e,new Ft(t,e));for(let r of e.subcommands)ds(`${t} ${e.name}`,r)}else jt.set(e,new fr(t,e))}l(ds,"registerCommandForHelpGeneration");function gr(t){let e=jt.get(t);if(!e)throw new Error(`No help renderer found for command ${t.name}`);return e.render()}l(gr,"renderHelpForCommand");function hr(t,e){let r=jt.get(t);if(!r)throw new Error(`No help renderer found for command ${t.name}`);return r.selectiveRender(e)}l(hr,"selectiveRenderHelpForCommand");function xi(t,e){return t[0].name.localeCompare(e[0].name)}l(xi,"sortByName");function yr(t){let e=ee(),r=[];r.push("Apify command-line interface (CLI) helps you manage the Apify cloud platform and develop, build, and deploy Apify Actors.",""),r.push(Ut.bold("VERSION")),r.push(` ${e.fullVersionString}`),r.push(""),r.push(Ut.bold("USAGE")),r.push(` $ ${t} <command> [options]`),r.push("");let o=Ci(jt,([n,a])=>a.entrypoint.includes(" ")||n.hidden?"ignored":a instanceof Ft?"subcommand":"command"),s=o.get("subcommand")?.sort(xi),i=o.get("command")?.sort(xi);if(s?.length){r.push(Ut.bold("TOPICS"));let n=[],a=Ri(s.map(([c])=>c.name).join(`
22
+ `));for(let[c]of s){if(c.hidden)continue;let d=c.shortDescription||c.description?.split(`
23
+ `)[0]||"",u=`${c.name.padEnd(a)} ${d}`,f=_i(u,re()-a-2);n.push(` ${Ei(f,a+2+2).trim()}`)}r.push(...n,"")}if(i?.length){r.push(Ut.bold("COMMANDS"));let n=[],a=Ri(i.map(([c])=>c.name).join(`
24
+ `));for(let[c]of i){if(c.hidden)continue;let d=c.shortDescription||c.description?.split(`
25
+ `)[0]||"",u=`${c.name.padEnd(a)} ${d}`,f=_i(u,re()-a-2);n.push(` ${Ei(f,a+2+2).trim()}`)}r.push(...n,"")}return r.push(Ut.bold("TROUBLESHOOTING")," For general support, reach out to us at https://apify.com/contact",""," If you believe you are encountering a bug, file it at https://github.com/apify/apify-cli/issues/new"),r.join(`
26
+ `).trim()}l(yr,"renderMainHelpMenu");function Ni(t){return t.replace(/[-_\s](.)/g,(e,r)=>r.toUpperCase())}l(Ni,"camelCaseString");function ce(t){return t.replace(/[\s_]+/g,"-")}l(ce,"kebabCaseString");function le(t){return t.replace(/([A-Z])/g,"-$1").toLowerCase()}l(le,"camelCaseToKebabCase");var K=new Map,h=class{static args;static flags;static subcommands;static enableJsonFlag=!1;static name;static shortDescription;static description;static aliases;static hidden;static hiddenAliases;telemetryData={};flags;args;entrypoint;constructor(e){this.entrypoint=e}get ctor(){return this.constructor}pluralString(e,r,o){return e===1?r:o}printHelp(){console.log(gr(this.ctor)),process.exit(0)}async _run(e){e.help&&this.printHelp(),this.args={},this.flags={},this.ctor.enableJsonFlag&&(typeof e.json=="boolean"?this.flags.json=e.json:this.flags.json=!1);let r=new Map;if(this.ctor.args)for(let[o,s]of Object.entries(this.ctor.args)){if(typeof s=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let i=o.replaceAll(" ",""),n=Ni(o);if(e[i])switch(s.argTag){case"string":default:this.args[n]=String(e[i]),e[i]==="-"&&s.stdin&&(this.args[n]=this._handleStdin(s.stdin)),s.catchAll&&(this.args[n]=this.args[n].split(",").join(" "));break}else s.required&&r.set(o,s)}if(r.size){this._printMissingRequiredArgs(r);return}if(this.ctor.flags)for(let[o,s]of Object.entries(this.ctor.flags)){if(typeof s=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");let i=ce(le(o)).toLowerCase(),n=Ni(i),a=i;if(i.startsWith("no-")&&(a=i.slice(3)),typeof e[a]<"u"){if(Array.isArray(e[a])){m({message:`Flag --${a} can only be specified once`});return}switch(s.flagTag){case"boolean":{this.flags[n]=i.startsWith("no-")?!e[a]:e[a];break}case"integer":{let c=Number(e[a]);if(Number.isNaN(c)||!Number.isInteger(c)){m({message:`The provided value for the '--${a}' flag could not be processed as an integer.`});return}this.flags[n]=c;break}case"string":default:{if(this.flags[n]=e[a],e[a]==="-"&&s.stdin&&(this.flags[n]=this._handleStdin(s.stdin)),!this.flags[n]){m({message:`Flag --${a} expects a value`});return}break}}}else if(s.required){m({message:`Flag --${a} is required`});return}else typeof s.hasDefault<"u"&&(this.flags[n]=s.hasDefault)}try{await this.run()}catch(o){m({message:o.message})}finally{}}_printMissingRequiredArgs(e){let r=hr(this.ctor,{showUsageString:!0}),o=Ic([...e.keys()].join(`
27
+ `)),s=[];for(let[i,n]of e){let a=`${i.padEnd(o)} ${n.description}`,c=$c(a,re()-o-2),d=Cc(c,o+2+2).trim();s.push(` ${Oi.red(">")} ${d}`)}m({message:[`Missing ${e.size} required ${this.pluralString(e.size,"argument","arguments")}:`,...s,Oi.gray(" See more help with --help"),"",r].join(`
28
+ `)})}_handleStdin(e){switch(e){case 2:return Ce?.toString("utf8")??"";default:return Ce}}_buildCommandStrings(e){let r=`${e||this.ctor.name}`;if(this.ctor.args){let o=!1;for(let[s,i]of Object.entries(this.ctor.args)){if(typeof i=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");if(i.catchAll){if(o)throw new RangeError("Only one catch-all argument is allowed in a command");o=!0,r+=` [${s}...]`}else r+=` [${s}]`}}return[r,...this.ctor.aliases??[]]}_buildCommandBuilder(){return e=>{let r=e;if(this.ctor.args)for(let[o,s]of Object.entries(this.ctor.args)){if(typeof s=="string")throw new RangeError("Do not provide the string for the json arg! It is a type level assertion!");o.toLowerCase()!=="json"&&(r=s.builder(r,o))}if(this.ctor.flags)for(let[o,s]of Object.entries(this.ctor.flags)){if(typeof s=="string")throw new RangeError("Do not provide the string for the json flag! It is a type level assertion!");if(o.toLowerCase()==="json")continue;let i=ce(le(o)).toLowerCase();i.startsWith("no-")?r=s.builder(r,i.slice(3)):r=s.builder(r,i)}if(this.ctor.subcommands?.length)for(let o of this.ctor.subcommands){let s=new o(`${this.entrypoint} ${this.ctor.name}`)._toYargs();r=r.command(s)}return this.ctor.enableJsonFlag&&(r=r.option("json",{boolean:!0,describe:"Format output as json."})),r}}_toYargs(){let e={handler:this._run.bind(this),command:this._buildCommandStrings(),describe:this.ctor.hidden?!1:this.ctor.description,builder:this._buildCommandBuilder()},r=[{...e,aliases:this.ctor.aliases}];if(this.ctor.hiddenAliases?.length)for(let o of this.ctor.hiddenAliases)r.push({...e,command:this._buildCommandStrings(o),describe:!1});return r}static registerCommand(e,r){let s=new this(e)._toYargs();if(r.command(s),ds(e,this),K.set(this.name,this),this.aliases?.length)for(let i of this.aliases)K.set(i,this);if(this.hiddenAliases?.length)for(let i of this.hiddenAliases)K.set(i,this);if(this.subcommands?.length)for(let i of this.subcommands){if(K.set(`${this.name} ${i.name}`,i),this.aliases?.length)for(let n of this.aliases)K.set(`${n} ${i.name}`,i);if(this.hiddenAliases?.length)for(let n of this.hiddenAliases)K.set(`${n} ${i.name}`,i);if(i.aliases?.length)for(let n of i.aliases){if(K.set(`${this.name} ${n}`,i),this.aliases?.length)for(let a of this.aliases)K.set(`${a} ${n}`,i);if(this.hiddenAliases?.length)for(let a of this.hiddenAliases)K.set(`${a} ${n}`,i)}if(i.hiddenAliases?.length)for(let n of i.hiddenAliases){if(K.set(`${this.name} ${n}`,i),this.aliases?.length)for(let a of this.aliases)K.set(`${a} ${n}`,i);if(this.hiddenAliases?.length)for(let a of this.hiddenAliases)K.set(`${a} ${n}`,i)}}}};async function Li(t,e,r){let o={_:[],$0:"apify"};for(let[i,n]of Object.entries(r)){let[a,c]=i.split("_");if(a==="args")o[c]=n;else{let d=ce(le(c)).toLowerCase();d.startsWith("no-")?o[d.slice(3)]=!n:o[d]=n}}await new e(t)._run(o)}l(Li,"internalRunCommand");import{once as Oc}from"events";import{constants as Di,fstat as Rc}from"fs";import Pi from"process";import{promisify as _c}from"util";import Ec from"chalk";function $(t,...e){process.env.APIFY_CLI_DEBUG&&console.error(Ec.gray(`[${t}]`),...e)}l($,"cliDebugPrint");var xc=_c(Rc),ms;async function wr(){if(ms)return ms;let t=Pi.stdin,e={isTTY:t.isTTY,hasData:!1,waitDelay:0,stream:t},r=await xc(0).then(o=>{if($("useStdin",{stat:o,isRegularFile:o.isFile(),isDirectory:o.isDirectory(),isBlockDevice:o.isBlockDevice(),isCharDevice:o.isCharacterDevice(),isSymbolicLink:o.isSymbolicLink(),isFIFO:o.isFIFO(),isSocket:o.isSocket()}),Pi.platform==="win32"){if((o.mode&Di.S_IFIFO)===Di.S_IFIFO)return 100;if(o.isFile())return 50}return o.isFIFO()||o.isFile()||(o.isSocket()?50:!1)}).catch(()=>!1);return $("useStdin",{hasData:e.hasData,waitDelay:e.waitDelay,isTTY:e.isTTY,pipedIn:r,readableEnded:t.readableEnded}),(!t.isTTY||r!==!1&&(t.isTTY!==void 0||!t.readableEnded))&&(e.hasData=!0),typeof r=="number"&&(e.waitDelay=r),ms=e,e}l(wr,"useStdin");async function ki(){let t=await wr(),{hasData:e,waitDelay:r,stream:o}=t;if(!e)return;let s=[],i=new AbortController,n=null;r&&(n=setTimeout(()=>{i.abort()},r).unref()),o.on("data",c=>{s.push(c),n&&(clearTimeout(n),n=null)});try{await Oc(o,"end",{signal:i.signal})}catch(c){if(c.name==="AbortError")return}n&&clearTimeout(n),t.hasData=!1;let a=Buffer.concat(s);if(a.length)return a}l(ki,"readStdin");import{gt as jc}from"semver";import{existsSync as Nc,mkdirSync as Lc,readFileSync as Dc,writeFileSync as Pc}from"fs";import{dirname as kc}from"path";function Fc(t){if(t.version&&t.version>=1)return!1;let e=t;if(e.latestNpmVersionCheckedAt){let r=new Date(e.latestNpmVersionCheckedAt).getTime(),o=e.latestNpmVersion;$("LocalStateV0ToV1","Migrating state from v0 to v1",{oldState:t,newState:{versionCheck:{lastChecked:r,lastVersion:o}}}),fs({version:1},s=>{s.versionCheck={lastChecked:r,lastVersion:o}})}return!0}l(Fc,"migrateStateV0ToV1");var Uc={version:1};function ps(){let t=rr();if(!Nc(t))return Uc;let r=JSON.parse(Dc(t,"utf-8"));return Fc(r)?ps():r}l(ps,"useLocalState");function fs(t,e){let r={...t};e(r);let o=rr(),s=kc(o);Lc(s,{recursive:!0}),Pc(rr(),JSON.stringify(r,null," "))}l(fs,"updateLocalState");var Ar=ee(),Fi=`Apify CLI/${Ar.version} (https://github.com/apify/apify-cli)`,Mc=["https://1.1.1.1","https://8.8.8.8"];async function Bc(t=500){let e=new AbortController,r=setTimeout(()=>{e.abort()},t),o=await Promise.any(Mc.map(async s=>fetch(s,{signal:e.signal,headers:{"User-Agent":Fi},keepalive:!1}))).catch(()=>null);return clearTimeout(r),o?o.ok?($("isOnline",{state:"online",site:o.url}),!0):($("isOnline",{state:"offline"}),!1):($("isOnline",{state:"timeout"}),!1)}l(Bc,"isOnline");async function Vc(t){let e=await fetch("https://api.github.com/repos/apify/apify-cli/releases/latest",{headers:{"User-Agent":Fi}});if(!e.ok)return $("useCLIVersionCheck","Failed to fetch latest version",{statusCode:e.status,body:await e.text()}),x({message:"Failed to fetch latest version of Apify CLI, using the cached version instead."}),null;let o=(await e.json()).tag_name.replace(/^v/,"");return $("useCLIVersionCheck","Fetched latest version",{version:o}),fs(t,s=>{s.versionCheck={lastChecked:Date.now(),lastVersion:o}}),o}l(Vc,"getLatestVersion");function Ui(){return!!(process.env.APIFY_CLI_SKIP_UPDATE_CHECK&&!["0","false"].includes(process.env.APIFY_CLI_SKIP_UPDATE_CHECK))}l(Ui,"shouldSkipVersionCheck");async function ji(t=!1){let e=ps(),r=!e.versionCheck||Date.now()-e.versionCheck.lastChecked>Xs,o=t||r&&await Bc(),s=o?await Vc(e):e.versionCheck?.lastVersion;if(!s)return{currentVersion:Ar.version,latestVersion:"unknown",shouldUpdate:!1,cacheHit:!1};let i=jc(s,Ar.version);return{currentVersion:Ar.version,latestVersion:s,shouldUpdate:i,cacheHit:!o}}l(ji,"useCLIVersionCheck");import{jaroWinkler as Yc}from"@skyra/jaro-winkler";import Gc from"js-levenshtein";function Mt(t){let e=[...K.entries()].sort(([s],[i])=>s.localeCompare(i)),r=t.toLowerCase();return e.map(([s,i])=>{let n=s.toLowerCase(),a=s.split(" "),c=a[a.length-1].toLowerCase(),d=i.aliases?.includes(c)||i.hiddenAliases?.includes(c)||!1,u=Gc(r,n),f=Yc(r,n),p=u<=2||f>=.975;return p?($("useCommandSuggestions",{inputString:r,lowercased:n,matches:p,levenshtein:u,jaroWinkler:f}),d?{string:`${n} (alias for ${i.name})`,distance:f}:{string:`${n}`,distance:f}):null}).filter(s=>s!==null).sort((s,i)=>i.distance-s.distance).map(s=>s.string)}l(Mt,"useCommandSuggestions");var Ce=await ki(),br=Jc().version(!1).help(!1).parserConfiguration({"camel-case-expansion":!1,"dot-notation":!1,"parse-numbers":!1,"parse-positional-numbers":!1,"short-option-groups":!1}).strict().locale("en").updateStrings({"Not enough arguments following: %s":"MISSING_ARGUMENT_INPUT %s","Unknown argument: %s":{one:"UNKNOWN_ARGUMENT_INPUT %s",other:"UNKNOWN_ARGUMENTS_INPUT %s"},"Not enough non-option arguments: got %s, need at least %s":{one:'NOT_ENOUGH_NON_OPTION_ARGUMENTS_INPUT {"got":%s,"need":%s}',other:'NOT_ENOUGH_NON_OPTION_ARGUMENTS_INPUT {"got":%s,"need":%s}'},"Arguments %s and %s are mutually exclusive":'ARGUMENTS_ARE_MUTUALLY_EXCLUSIVE_INPUT ["%s","%s"]',"Invalid values:":"INVALID_VALUES_INPUT","Argument: %s, Given: %s, Choices: %s":'INVALID_ARGUMENT_OPTION {"argument":"%s","given":%s,"choices":[%s]}'}).option("help",{boolean:!0,describe:"Shows this help message.",alias:"h"});br.usageConfiguration({"hide-types":!0});br.middleware(async t=>{let e=K.get("upgrade");[e.name,...e.aliases??[]].some(o=>t._[0]===o)||Ui()||await Li(t.$0,e,{flags_internalAutomaticCall:!0})});var dt=ee(),Bt=`Apify CLI/${dt.version} (https://github.com/apify/apify-cli)`;function Kf(t){dt.installMethod!=="bundle"&&(Hc(de.version,we)||(m({message:`${t} CLI requires Node.js version ${we}. Your current version is ${de.version}.`}),de.exit(1)))}l(Kf,"processVersionCheck");function Kc(t){(t.v===!0||t.version===!0)&&(console.log(dt.fullVersionString),de.exit(0))}l(Kc,"printCLIVersionAndExitIfFlagUsed");function qc(t,e){(t.help===!0||t.h===!0||t._.length===0)&&(console.log(yr(e)),de.exit(0))}l(qc,"printHelpAndExitIfFlagUsedOrNoCommandPassed");async function qf(t){$("CLIMetadata",{...dt,fullVersionString:dt.fullVersionString,argv:de.argv,cwd:de.cwd(),execPath:de.execPath}),br.scriptName(t),await br.parse(de.argv.slice(2),{},(e,r)=>{if(e&&r._.length>0){$("RunCLIError",{type:"parsed",error:e?.message,parsed:r});let o=e.message.split(" ").map(a=>a.trim()),s=[`${r._[0]} ${r._[1]}`,`${r._[0]}`],i=K.get(s.find(a=>K.has(a))??"");if(!i){let a=Mt(String(r._[0])),c=ue.gray(`Command ${ue.whiteBright(r._[0])} not found`);a.length&&(c+=`
29
+ `,c+=ue.gray(`Did you mean: ${a.map(d=>ue.whiteBright(d)).join(", ")}?`)),m({message:c});return}let n=Object.entries(i.flags??{}).filter(([,a])=>typeof a!="string").map(([a,c])=>{let d=c;return{flagKey:ce(le(a)).toLowerCase(),char:d.char,aliases:d.aliases?.map(f=>ce(le(f)).toLowerCase()),matches(f){return this.flagKey===f||this.char===f||this.aliases?.some(p=>p===f)}}});switch(o[0]){case"MISSING_ARGUMENT_INPUT":{for(let a of n)if(a.matches(o[1])){m({message:`Flag --${a.flagKey} expects a value`});return}break}case"ARGUMENTS_ARE_MUTUALLY_EXCLUSIVE_INPUT":{let a=JSON.parse(o[1]);m({message:["The following errors occurred:",...a.sort((c,d)=>c.localeCompare(d)).map(c=>{let d=r[c],f=typeof d=="boolean"?`--${c}`:`--${c}=${d}`;return` ${ue.red(">")} ${ue.gray(`${f} cannot also be provided when using ${a.filter(p=>p!==c).map(p=>`--${p}`).join(", ")}`)}`}),` ${ue.red(">")} See more help with --help`].join(`
30
+ `)});break}case"UNKNOWN_ARGUMENT_INPUT":case"UNKNOWN_ARGUMENTS_INPUT":{let a=n.length?"flag":i.subcommands?.length?"subcommand":"argument",c=a==="flag"?o[1].length===1?`-${o[1]}`:`--${o[1]}`:o[1],d=a==="subcommand"?Mt(`${r._[0]} ${o[1]}`):[],u=[ue.gray(`Nonexistent ${a}: ${ue.whiteBright(c)}`)];d.length&&u.push(ue.gray(` Did you mean: ${d.map(f=>ue.whiteBright(f)).join(", ")}?`)),m({message:[...u,"",hr(i,{showUsageString:!0,showSubcommands:!0})].join(`
31
+ `)});break}case"INVALID_VALUES_INPUT":if(o[2]==="INVALID_ARGUMENT_OPTION"){let a=o.slice(3).join(" ");try{let c=JSON.parse(a),u=(n.some(f=>f.matches(c.argument))?"flag":"argument")==="flag"?`--${c.argument}`:c.argument;m({message:[`Expected ${u} to have one of the following values: ${c.choices.join(", ")}`,` ${ue.red(">")} See more help with --help`].join(`
32
+ `)});break}catch{$("RunCLIError",{type:"parse_error_invalid_choices",error:e.message,parsed:r,jsonPart:a})}}default:$("RunCLIError",{type:"unhandled",error:e.message,parsed:r}),console.error(["The CLI encountered an unhandled argument parsing error!","Please report this issue at https://github.com/apify/apify-cli/issues, and provide the following information:","",`- Stack:
33
+ ${e.stack}`,"","- Arguments (!!!only provide these as is if there is no sensitive information!!!):",` ${JSON.stringify(de.argv.slice(2))}`,"",`- CLI version: \`${dt.fullVersionString}\``,`- CLI debug logs (process.env.APIFY_CLI_DEBUG): ${de.env.APIFY_CLI_DEBUG?"Enabled":"Disabled"}`,`- Stdin data? ${Ce?"Yes":"No"}`].join(`
34
+ `)),de.exit(1)}}else Wc(r,t)})}l(qf,"runCLI");function Wc(t,e){t._.length===0&&(Kc(t),qc(t,e))}l(Wc,"handleParseResults");import{APIFY_ENV_VARS as il}from"@apify/consts";import Vt from"process";import{pipeline as zc}from"stream/promises";import{MemoryStorage as Xc}from"@crawlee/memory-storage";import{ApifyClient as Zc}from"apify-client";import Mi from"ow";import{ACTOR_ENV_VARS as Bi,APIFY_ENV_VARS as Vi,KEY_VALUE_STORE_KEYS as Qc,LOCAL_ACTOR_ENV_VARS as el}from"@apify/consts";var Yt={KEY_VALUE_STORE:"KEY_VALUE_STORE",DATASET:"DATASET",REQUEST_QUEUE:"REQUEST_QUEUE"},gs=l(async()=>{let t=Vt.env[Vi.TOKEN];if(t)return t;let e=await k();if(!e||!e.token)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN or apify login command.");return e.token},"getApifyTokenFromEnvOrAuthFile"),et=l(async(t={},e=Reflect.has(Vt.env,Vi.IS_AT_HOME))=>{let r=ae();if(r&&!e)return new Xc({localDataDirectory:r,...t});let o=await gs();return new Zc({...as(o),...t})},"getApifyStorageClient"),Gt=l(t=>{let e=Bi[`DEFAULT_${t}_ID`];return Vt.env[e]||el[e]},"getDefaultStorageId"),hs=l(async t=>{Mi(t,Mi.string);let e=await et(),r=Gt(Yt.KEY_VALUE_STORE),o=await e.keyValueStore(r).getRecord(t,{stream:!0});o&&await zc(o.value,Vt.stdout,{end:!1})},"outputRecordFromDefaultStore"),Yi=l(async()=>hs(Vt.env[Bi.INPUT_KEY]||Qc.INPUT),"outputInputFromDefaultStore");function tl(t){return{argTag:"string",builder:l((e,r)=>(e.positional(r,{type:"string",alias:t.aliases,description:t.description,demandOption:!1}),e),"builder"),required:t.required??!1,stdin:t.stdin??1,description:t.description,aliases:t.aliases,catchAll:t.catchAll??!1}}l(tl,"stringArg");var w={string:tl};var A={string:rl,boolean:ol,integer:sl};function rl(t){return{flagTag:"string",builder:l((e,r,o)=>{let s=new Set([...t.aliases??[],...o??[]]);return t.char&&s.add(t.char),s.delete(r),e.option(r,{demandOption:!1,describe:t.description,alias:[...s].map(i=>ce(le(i))),hidden:t.hidden??!1,conflicts:t.exclusive,choices:t.choices,string:!0,nargs:1})},"builder"),choicesType:t.choices,required:t.required??!1,hasDefault:t.default,stdin:t.stdin??1,description:t.description,aliases:t.aliases,char:t.char,hidden:t.hidden,exclusive:t.exclusive}}l(rl,"stringFlag");function ol(t){return{flagTag:"boolean",builder:l((e,r,o)=>{let s=new Set([...t.aliases??[],...o??[]]);return t.char&&s.add(t.char),s.delete(r),e.option(r,{demandOption:!1,describe:t.description,alias:[...s].map(i=>ce(le(i))),hidden:t.hidden??!1,conflicts:t.exclusive,boolean:!0})},"builder"),choicesType:null,required:t.required??!1,hasDefault:t.default,stdin:t.stdin??1,description:t.description,aliases:t.aliases,char:t.char,hidden:t.hidden,exclusive:t.exclusive}}l(ol,"booleanFlag");function sl(t){return{flagTag:"integer",builder:l((e,r,o)=>{let s=new Set([...t.aliases??[],...o??[]]);return t.char&&s.add(t.char),s.delete(r),e.option(r,{demandOption:!1,describe:t.description,alias:[...s].map(i=>ce(le(i))),hidden:t.hidden??!1,conflicts:t.exclusive,choices:t.choices,string:!0,nargs:1})},"builder"),choicesType:null,required:t.required??!1,hasDefault:t.default,stdin:t.stdin??1,description:t.description,aliases:t.aliases,char:t.char,hidden:t.hidden,exclusive:t.exclusive}}l(sl,"integerFlag");var mt=class extends h{static name="charge";static description="Charge for a specific event in the pay-per-event Actor run.";static args={eventName:w.string({description:"Name of the event to charge for",required:!0})};static flags={count:A.integer({description:"Number of events to charge",required:!1,default:1}),"idempotency-key":A.string({description:"Idempotency key for the charge request",required:!1}),"test-pay-per-event":A.boolean({description:"Test pay-per-event charging without actually charging",required:!1,default:!1})};async run(){let{eventName:e}=this.args,{count:r,testPayPerEvent:o,idempotencyKey:s}=this.flags;if(!!!process.env.APIFY_IS_AT_HOME){v({message:`No platform detected: would charge ${r} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}if(o){v({message:`PPE test mode: would charge ${r} events of type "${e}" with idempotency key "${s??"not-provided"}".`,stdout:!0});return}let n=await gs(),a=await Nt(n);if(!a)throw new Error("Apify token is not set. Please set it using the environment variable APIFY_TOKEN.");let c=process.env[il.ACTOR_RUN_ID];if(!c)throw new Error("Charge command must be executed in a running Actor. Run ID not found.");if((await a.run(c).get())?.pricingInfo?.pricingModel!=="PAY_PER_EVENT")throw new Error("Charge command can only be used with pay-per-event pricing model.");v({message:`Charging ${r} events of type "${e}" with idempotency key "${s??"not-provided"}" (runId: ${c}).`,stdout:!0}),await a.run(c).charge({eventName:e,count:r,idempotencyKey:s})}};var pt=class extends h{static name="get-input";static description="Gets the Actor input value from the default key-value store associated with the Actor run.";async run(){await Yi()}};import{ACTOR_ENV_VARS as ys,APIFY_ENV_VARS as Gi}from"@apify/consts";import{createHmacSignature as nl}from"@apify/utilities";var ft=class extends h{static name="get-public-url";static description="Get an HTTP URL that allows public access to a key-value store item.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;if([void 0,"false",""].includes(process.env[Gi.IS_AT_HOME])){m({message:"get-public-url is not yet implemented for local development"}),process.exitCode=255;return}let r=process.env[Gi.API_PUBLIC_BASE_URL],o=process.env[ys.DEFAULT_KEY_VALUE_STORE_ID];if(!o){m({message:`Missing environment variable: ${ys.DEFAULT_KEY_VALUE_STORE_ID}. Please set it before running the command.`}),process.exitCode=5;return}let i=await(await et()).keyValueStore(o).get(),n=new URL(`${r}/v2/key-value-stores/${o}/records/${e}`);if(!i){m({message:`Key-Value store with ID '${o}' was not found. Ensure the store exists and that the correct ID is set in ${ys.DEFAULT_KEY_VALUE_STORE_ID}.`}),process.exitCode=250;return}let{urlSigningSecretKey:a}=i;a&&n.searchParams.append("signature",nl(a,e)),console.log(n.toString())}};var gt=class extends h{static name="get-value";static description="Gets a value from the default key-value store associated with the Actor run.";static args={key:w.string({required:!0,description:"Key of the record in key-value store"})};async run(){let{key:e}=this.args;await hs(e)}};var ht=class extends h{static name="push-data";static description=`Saves data to Actor's run default dataset.
35
+
36
+ Accept input as:
37
+ - JSON argument:
38
+ $ apify actor push-data {"key": "value"}
39
+ - Piped stdin:
40
+ $ cat ./test.json | apify actor push-data`;static args={item:w.string({description:"JSON string with one object or array of objects containing data to be stored in the default dataset."})};async run(){let{item:e}=this.args,r=e||Ce;if(!r){m({message:"No item was provided."});return}let o=await et(),s=Gt(Yt.DATASET),i;try{i=JSON.parse(r.toString("utf8"))}catch(n){throw new Error(`Failed to parse data as JSON string: ${n.message}`)}await o.dataset(s).pushItems(i)}};var yt=class extends h{static name="set-value";static description=`Sets or removes record into the default key-value store associated with the Actor run.
41
+
42
+ It is possible to pass data using argument or stdin.
43
+
44
+ Passing data using argument:
45
+ $ apify actor set-value KEY my-value
46
+
47
+ Passing data using stdin with pipe:
48
+ $ cat ./my-text-file.txt | apify actor set-value KEY --contentType text/plain`;static args={key:w.string({required:!0,description:"Key of the record in key-value store."}),value:w.string({required:!1,description:`Record data, which can be one of the following values:
49
+ - If empty, the record in the key-value store is deleted.
50
+ - If no \`contentType\` flag is specified, value is expected to be any JSON string value.
51
+ - If options.contentType is set, value is taken as is.`})};static flags={contentType:A.string({char:"c",description:'Specifies a custom MIME content type of the record. By default "application/json" is used.',required:!1})};async run(){let{key:e,value:r}=this.args,{contentType:o="application/json; charset=utf-8"}=this.flags,s=r||process.stdin,n=(await et()).keyValueStore(Gt(Yt.KEY_VALUE_STORE));s==null||s===""||s==="null"||s==="undefined"?await n.deleteRecord(e):await n.setRecord({key:e,value:s,contentType:o})}};var vr=class extends h{static name="actor";static description="Manages runtime data operations inside of a running Actor.";static subcommands=[yt,ht,gt,ft,pt,mt];async run(){this.printHelp()}};import Ie from"chalk";import al from"process";async function Fe({providedActorNameOrId:t,client:e}){let r=await k(),o=r.username||r.id,s=Pe(al.cwd())||{};if(t?.includes("/")){let i=await e.actor(t).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with ID "${t}" was not found`}}if(t){let i=await e.actor(t).get();if(i)return{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id};let n=await e.actor(`${o}/${t.toLowerCase()}`).get();return n?{valid:!0,userFriendlyId:`${n.username}/${n.name}`,id:n.id}:{valid:!1,reason:`Actor with name or ID "${t}" was not found`}}if(s.name){let i=await e.actor(`${o}/${s.name}`).get();return i?{valid:!0,userFriendlyId:`${i.username}/${i.name}`,id:i.id}:{valid:!1,reason:`Actor with name "${s.name}" was not found`}}return{valid:!1,reason:"Unable to detect what Actor to create a build for"}}l(Fe,"resolveActorContext");var wt=class extends h{static name="create";static description="Creates a new build of the Actor.";static flags={tag:A.string({description:'Build tag to be applied to the successful Actor build. By default, this is "latest".'}),version:A.string({description:"Optional Actor Version to build. By default, this will be inferred from the tag, but this flag is required when multiple versions have the same tag.",required:!1}),log:A.boolean({description:"Whether to print out the build log after the build is triggered."})};static args={actorId:w.string({description:"Optional Actor ID or Name to trigger a build for. By default, it will use the Actor from the current directory."})};static enableJsonFlag=!0;async run(){let{tag:e,version:r,json:o,log:s}=this.flags,{actorId:i}=this.args,n=await S(),a=await Fe({providedActorNameOrId:i,client:n});if(!a.valid){m({message:`${a.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let c=await n.actor(a.id).get(),u=mr(c.versions,I=>I.buildTag??"latest")[e??"latest"],f=c.versions.find(I=>I.versionNumber===r),p,g=e;if(f){if(e&&(!u||!u.some(I=>I.versionNumber===r))){m({message:`The Actor Version "${r}" does not have the tag "${e}".`,stdout:!0});return}p=r,g=f.buildTag??"latest"}else if(u&&(p=u[0].versionNumber,g=e??"latest",u.length>1&&!r)){m({message:`Multiple Actor versions with the tag "${e}" found. Please specify the version number using the "--version" flag.
52
+ Available versions for this tag: ${u.map(I=>Ie.yellow(I.versionNumber)).join(", ")}`,stdout:!0});return}if(!p){m({message:`No Actor versions with the tag "${e}" found. You can push a new version with this tag by using "apify push --build-tag=${e}".`,stdout:!0});return}let y=await n.actor(a.id).build(p,{tag:e});if(o){N(y);return}let b=[`${Ie.yellow("Actor")}: ${c?.username?`${c.username}/`:""}${c?.name??"unknown-actor"} (${Ie.gray(y.actId)})`,` ${Ie.yellow("Version")}: ${p} (tagged with ${Ie.yellow(g)})`,"",`${Ie.greenBright("Build Started")} (ID: ${Ie.gray(y.id)})`,` ${Ie.yellow("Build Number")}: ${y.buildNumber} (will get tagged once finished)`,` ${Ie.yellow("Started")}: ${B.display(y.startedAt)}`,""],C=`https://console.apify.com/actors/${y.actId}/builds/${y.buildNumber}`,T=`${Ie.blue("View in Apify Console")}: ${C}`;if(_({message:b.join(`
53
+ `),stdout:!0}),s){try{await Se({job:y,apifyClient:n})}catch(I){m({message:`Failed to print log for build with ID "${y.id}": ${I.message}`,stdout:!0})}_({message:"",stdout:!0})}_({message:T,stdout:!0})}};var Sr=class extends wt{static name="build"};import qi from"process";import{DownloadItemsFormat as ml}from"apify-client";import te from"chalk";import{access as cl,readFile as ll}from"fs/promises";import ul,{resolve as Hi}from"path";import $e from"process";import dl from"mime";function Ji(t,e){let r,o;if(e)r=e,o="application/json";else{let s=Lt(t);s&&(dl.getExtension(s.contentType)==="json"?(r=JSON.parse(s.body.toString("utf8")),o="application/json"):(r=s.body,o=s.contentType))}return!r||!o?null:{inputToUse:r,contentType:o}}l(Ji,"resolveInput");async function At(t,e,r){let o,s;if(!e&&!r){let i=Ce;if(i)try{let n=JSON.parse(i.toString("utf8"));if(Array.isArray(n))return m({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=n,s="stdin"}catch(n){return m({message:`Cannot parse JSON input from standard input.
54
+ ${n.message}`}),$e.exitCode=5,!1}}if(e)switch(e[0]){case"-":return m({message:"You need to pipe something into standard input when you specify the `-` value to `--input`."}),$e.exitCode=5,!1;default:{let i=await cl(Hi(t,e)).then(()=>!0).catch(()=>!1),n=e.endsWith(".json")||e.endsWith(".json5")||ul.isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.includes("~")||e.startsWith(".\\")||e.startsWith("..\\");if(i||n)return m({message:'Providing a JSON file path in the --input flag is not supported. Use the "--input-file=" flag instead'}),$e.exitCode=5,!1;try{let a=JSON.parse(e);if(Array.isArray(a))return m({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=a,s="input"}catch(a){return m({message:`Cannot parse JSON input.
55
+ ${a.message}`}),$e.exitCode=5,!1}}}else if(r)switch(r[0]){case"-":return m({message:"You need to pipe something into standard input when you specify the `-` value to `--input-file`."}),$e.exitCode=5,!1;default:{let i=Hi(t,r),n;try{let a=await ll(i,"utf8"),c=JSON.parse(a);if(Array.isArray(c))return m({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=c,s=r}catch(a){n=a}if(n)try{let a=JSON.parse(r);if(Array.isArray(a))return m({message:"The provided input is invalid. It should be an object, not an array."}),$e.exitCode=5,!1;o=a,s=r}catch{return m({message:`Cannot read input file at path "${i}".
56
+ ${n.message}`}),$e.exitCode=5,!1}}}return o?{input:o,source:s}:void 0}l(At,"getInputOverride");import ws from"process";import Cr from"chalk";import{ACTOR_JOB_STATUSES as Ue}from"@apify/consts";var Ki=[Ue.SUCCEEDED,Ue.ABORTED,Ue.FAILED,Ue.TIMED_OUT];async function*bt(t,e){let r=ws.cwd(),{actorOrTaskData:o,runOptions:s,type:i,waitForFinishMillis:n,inputOverride:a,silent:c,waitForRunToFinish:d,printRunLogs:u}=e,f=i==="Actor"?"actor":"task",p=Ji(r,a);c||(i==="Actor"?ye({message:`Calling ${i} ${o.userFriendlyId} (${Cr.gray(o.id)})
57
+ `}):o.title?ye({message:`Calling ${i} ${o.title} (${o.userFriendlyId}, ${Cr.gray(o.id)})
58
+ `}):ye({message:`Calling ${i} ${o.userFriendlyId} (${Cr.gray(o.id)})
59
+ `}));let g;try{p&&i==="Actor"?g=await t[f](o.id).start(p.inputToUse,{...s,contentType:p.contentType}):g=await t[f](o.id).start(void 0,s)}catch(y){throw y.type==="record-not-found"?new Error(`${i} ${o.userFriendlyId} (${o.id}) not found!`):y}if(yield g,!c&&u)try{await Se({job:g,timeoutMillis:n,apifyClient:t})==="timeouts"?console.error(`
60
+ ${Cr.gray("Timeout for printing logs was hit, there may be future logs.")}
61
+ `):console.error()}catch(y){x({message:"Can not get log:"}),console.error(y)}if(g=await t.run(g.id).get(),d)for(;!Ki.includes(g.status)&&(g=await t.run(g.id).get(),!Ki.includes(g.status));)await new Promise(y=>{setTimeout(y,1e3)});c||(g.status===Ue.SUCCEEDED?R({message:`${i} finished.`}):g.status===Ue.RUNNING?x({message:`${i} is still running!`}):g.status===Ue.ABORTED||g.status===Ue.ABORTING?(x({message:`${i} was aborted!`}),ws.exitCode=3):(m({message:`${i} failed!`}),ws.exitCode=1)),yield g}l(bt,"runActorOrTaskOnCloud");var Tt=l(t=>({build:A.string({char:"b",description:'Tag or number of the build to run (e.g. "latest" or "1.2.34").',required:!1}),timeout:A.integer({char:"t",description:`Timeout for the ${t} run in seconds. Zero value means there is no timeout.`,required:!1}),memory:A.integer({char:"m",description:`Amount of memory allocated for the ${t} run, in megabytes.`,required:!1})}),"SharedRunOnCloudFlags");var je=class t extends h{static name="call";static description=`Executes Actor remotely using your authenticated account.
62
+ Reads input from local key-value store by default.`;static flags={...Tt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]}),silent:A.boolean({char:"s",description:"Prevents printing the logs of the Actor run to the console.",default:!1}),"output-dataset":A.boolean({char:"o",description:"Prints out the entire default dataset on successful run of the Actor."})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${M}' file.`})};async run(){let e=qi.cwd(),r=Pe(e)||{},o=await S(),s=await k(),i=s.username||s.id;if(this.flags.json&&this.flags.outputDataset){m({message:"You cannot use both the --json and --output-dataset flags when running this command."}),qi.exitCode=5;return}let{id:n,userFriendlyId:a,actorData:c}=await t.resolveActorId({client:o,localActorName:r.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={waitForFinish:2};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let u=await At(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=!1,p,g,y,b=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:u?.input,silent:this.flags.silent,waitForRunToFinish:!0,printRunLogs:!0});for await(let C of b)if(p=C,!f&&(f=!0,!this.flags.silent)){g=`https://console.apify.com/actors/${n}/runs/${C.id}`,y=`https://console.apify.com/storage/datasets/${C.defaultDatasetId}`;let T=[`${te.yellow("Started")}: ${B.display(C.startedAt)}`];C.containerUrl&&T.push(`${te.yellow("Container URL")}: ${te.blue(C.containerUrl)}`);let I=p.buildNumber.split(".").slice(0,2).join("."),L=c.versions.find(Y=>Y.versionNumber===I),D=Object.entries(c.taggedBuilds??{}).find(([,Y])=>Y.buildNumber===C.buildNumber)?.[0],j=[`${te.yellow("Build")}:`,te.cyan(p.buildNumber)];D?j.push(`(${te.yellow(D)})`):j.push(`(${te.gray("N/A")})`),L&&j.push(`| ${te.gray("Actor version:")} ${te.cyan(L.versionNumber)} (${te.yellow(L.buildTag)})`),T.push(j.join(" ")),T.push(`${te.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),T.push(`${te.yellow("Memory")}: ${p.options.memoryMbytes} MB`),T.push(`${te.blue("View on Apify Console")}: ${g}`,""),_({message:T.join(`
63
+ `),stdout:!this.flags.json})}if(this.flags.json){N(p);return}if(this.flags.silent||_({message:["",`${te.blue("Export results")}: ${y}`,`${te.blue("View on Apify Console")}: ${g}`].join(`
64
+ `),stdout:!0}),this.flags.outputDataset){let C=p.defaultDatasetId,T,I=4;do{if(T=await o.dataset(C).get(),T?.itemCount)break;await new Promise(D=>{setTimeout(D,250)})}while(I--);let L=await o.dataset(C).downloadItems(ml.JSON,{clean:!0});console.log(L.toString())}}static async resolveActorId({client:e,localActorName:r,usernameOrId:o,providedActorNameOrId:s}){if(s?.includes("/")){let i=await e.actor(s).get();if(!i)throw new Error(`Cannot find Actor with ID '${s}' in your account.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}if(s){let i=await e.actor(s).get();if(i)return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i};let n=await e.actor(`${o}/${s.toLowerCase()}`).get();if(n)return{userFriendlyId:`${n.username}/${n.name}`,id:n.id,actorData:n};throw new Error(`Cannot find Actor with name or ID '${s}' in your account.`)}if(r){let i=await e.actor(`${o}/${r}`).get();if(!i)throw new Error(`Cannot find Actor with ID '${o}/${r}' in your account. Call "apify push" to push this Actor to Apify platform.`);return{userFriendlyId:`${i.username}/${i.name}`,id:i.id,actorData:i}}throw new Error("Please provide an Actor ID or name, or run this command from a directory with a valid Apify Actor.")}};import O from"chalk";import pl from"cli-table3";var fl={mid:"","left-mid":"","mid-mid":"","right-mid":"",middle:" ","top-mid":"\u2500","bottom-mid":"\u2500"},gl={middle:" ","top-mid":"\u2500","bottom-mid":"\u2500",top:"\u2500",bottom:"\u2500","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u2500","right-mid":"\u2524"},hl={left:"",right:"",mid:"","bottom-left":"","bottom-mid":"","bottom-right":"",top:"","top-left":"","top-mid":"","top-right":"","left-mid":"","mid-mid":"","right-mid":"",bottom:"",middle:" "};var yl={[-1]:void 0,0:fl,1:gl,2:hl};function wl(t){return Array.from({length:t},()=>"cyan")}l(wl,"generateHeaderColors");var Al=process.stdout.columns??100,Ir=Symbol.for("@apify/cli:responsive-table:skip-column"),V=class t{static{l(this,"ResponsiveTable")}options;rows=[];constructor(e){this.options=e}pushRow(e){this.rows.push(e)}render(e){let r=t.isSmallTerminal()?this.options.mandatoryColumns:this.options.allColumns,o=wl(r.length),s=e===0||e===2,i=yl[e],n=[],a=[],c=[];for(let u of r)this.options.hiddenColumns?.includes(u)||this.rows.some(f=>f[u]===Ir)||(n.push(this.options.columnAlignments?.[u]||"left"),t.isSmallTerminal()?(a.push(this.options.breakpointOverrides?.small?.[u]?.label??u),c.push(this.options.breakpointOverrides?.small?.[u]?.valueFrom??u)):(a.push(u),c.push(u)));let d=new pl({head:a,style:{head:o,compact:s},colAligns:n,chars:i});for(let u of this.rows){let f=c.map(p=>u[p]);d.push(f)}return d.toString()}static isSmallTerminal(){return Al<100}};var $r="\u200B",Er="\u200B\u200B",Wi=new V({allColumns:[$r,Er],mandatoryColumns:[$r,Er],columnAlignments:{[$r]:"left",[Er]:"right"}}),Rr=class extends h{static name="info";static description="Get information about an Actor.";static flags={readme:A.boolean({description:"Return the Actor README.",exclusive:["input"]}),input:A.boolean({description:"Return the Actor input schema.",exclusive:["readme"]})};static args={actorId:w.string({description:"The ID of the Actor to return information about.",required:!0})};static enableJsonFlag=!0;async run(){let{actorId:e}=this.args,{readme:r,input:o,json:s}=this.flags,i=await S(),n=await Fe({providedActorNameOrId:e,client:i});if(!n.valid){m({message:`${n.reason}. Please specify the Actor ID.`,stdout:!0});return}let a=await i.actor(n.id).get(),c=await i.user(a.userId).get();a.actorMaker=c;for(let p of Object.values(a.taggedBuilds??{})){if(!p.buildId)continue;let g=await i.build(p.buildId).get();p.build=g}if(s){N(a);return}let d=a.taggedBuilds?.latest;if(r){if(!d){m({message:"No README found for this Actor.",stdout:!0});return}if(!d.build?.readme){m({message:"No README found for this Actor.",stdout:!0});return}_({message:d.build.readme,stdout:!0})}if(o){if(!d){m({message:"No input schema found for this Actor.",stdout:!0});return}if(!d.build?.inputSchema){m({message:"No input schema found for this Actor.",stdout:!0});return}_({message:d.build.inputSchema,stdout:!0})}let u=[`Information about Actor ${O.yellow(`${a.username}/${a.name}`)} (${O.gray(a.id)})`,""];a.title&&u.push(`${O.yellow("Title:")} ${O.bold(a.title)}`),a.description&&u.push(`${O.yellow("Description:")} ${a.description}`),u.push(`${O.yellow("Created at:")} ${O.cyan(B.display(a.createdAt))} ${O.gray("|")} ${O.yellow("Updated at:")} ${O.cyan(B.display(a.modifiedAt))}`),a.actorMaker&&(u.push("",`${O.yellow("Made by:")} ${O.cyan(a.actorMaker.profile.name??a.actorMaker.username)}`),Reflect.get(a,"isCritical")&&(u[u.length-1]+=` ${O.bgGray("Maintained by Apify")}`)),a.isPublic?u.push("",`${O.yellow("Actor is")} ${O.green("PUBLIC")}`):u.push("",`${O.yellow("Actor is")} ${O.cyan("PRIVATE")}`),a.isDeprecated&&u.push("",`${O.yellow("Actor is")} ${O.red("DEPRECATED")}`);let f=Reflect.get(a,"pricingInfos");if(f?.length){let p=f.at(-1);switch(p.pricingModel){case"FLAT_PRICE_PER_MONTH":{if(u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${p.pricePerUnitUsd}/month + usage`)}`),p.trialMinutes){let g=p.trialMinutes*60*1e3,y=kt.format(g);u.push(` ${O.yellow("Trial duration:")} ${O.bold(y)}`)}break}case"PRICE_PER_DATASET_ITEM":{let g=p.pricePerUnitUsd*1e3;u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`$${g.toFixed(2)} / 1,000 results`)}`);break}case"PAY_PER_EVENT":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay per event")}`);let g=Object.values(p.pricingPerEvent?.actorChargeEvents??{});for(let C of g)Wi.pushRow({[$r]:C.eventTitle,[Er]:O.bold(`$${C.eventPriceUsd.toFixed(2)}`)});let b=Wi.render(0).split(`
65
+ `);b.splice(1,1),u.push(b.join(`
66
+ `));break}case"FREE":{u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);break}default:u.push(`${O.yellow("Pricing information:")} ${O.bgGray(`Unknown pricing model (${O.yellow(p.pricingModel)})`)}`)}}else u.push(`${O.yellow("Pricing information:")} ${O.bgGray("Pay for usage")}`);if((a.seoTitle||a.seoDescription)&&(u.push("",O.yellow("SEO information:")),a.seoTitle&&u.push(` ${O.yellow("Title:")} ${a.seoTitle}`),a.seoDescription&&u.push(` ${O.yellow("Description:")} ${a.seoDescription}`)),a.taggedBuilds){u.push("",O.yellow("Builds:"));let p=a.taggedBuilds.latest;p&&u.push(` ${O.yellow("-")} ${O.cyan(p.buildNumber)} ${O.gray("/")} ${O.yellow("latest")}`);for(let[g,y]of Object.entries(a.taggedBuilds))g!=="latest"&&u.push(` ${O.yellow("-")} ${O.cyan(y.buildNumber)} ${O.gray("/")} ${O.yellow(g)}`)}_({message:u.join(`
67
+ `),stdout:!0})}};import{Time as bl}from"@sapphire/duration";import q from"chalk";import xe from"chalk";function be(t){switch(t){case"READY":return xe.green("Ready");case"RUNNING":return xe.blue("Running");case"SUCCEEDED":return xe.green("Succeeded");case"FAILED":return xe.red("Failed");case"ABORTING":return xe.yellow("Aborting");case"ABORTED":return xe.red("Aborted");case"TIMING-OUT":return xe.yellow("Timing Out");case"TIMED-OUT":return xe.red("Timed Out");default:return xe.gray(t.split("-").map(e=>e[0].toUpperCase()+e.slice(1).toLowerCase()).join(" "))}}l(be,"prettyPrintStatus");var Tl={"TIMED-OUT":q.gray("after"),"TIMING-OUT":q.gray("after"),ABORTED:q.gray("after"),ABORTING:q.gray("after"),FAILED:q.gray("after"),READY:q.gray("for"),RUNNING:q.gray("for"),SUCCEEDED:q.gray("after")},vl=new V({allColumns:["Name","Runs","Last run started at","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run status","Last run duration"],columnAlignments:{Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},hiddenColumns:["_Small_LastRunText"],breakpointOverrides:{small:{"Last run status":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),Sl=new V({allColumns:["Name","Modified at","Builds","Default build","Runs","Last run","Last run status","Last run duration","_Small_LastRunText"],mandatoryColumns:["Name","Runs","Last run","Last run duration"],hiddenColumns:["_Small_LastRunText"],columnAlignments:{Builds:"right",Runs:"right","Last run duration":"right",Name:"left","Last run status":"center"},breakpointOverrides:{small:{"Last run":{label:"Last run",valueFrom:"_Small_LastRunText"}}}}),_r=class extends h{static name="ls";static description="Prints a list of recently executed Actors or Actors you own.";static flags={my:A.boolean({description:"Whether to list Actors made by the logged in user.",default:!1}),offset:A.integer({description:"Number of Actors that will be skipped.",default:0}),limit:A.integer({description:"Number of Actors that will be listed.",default:20}),desc:A.boolean({description:"Sort Actors in descending order.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,limit:r,offset:o,my:s,json:i}=this.flags,n=await S(),a=await n.actors().list({limit:r,offset:o,desc:e,my:s});if(a.count===0){if(i){N(a);return}v({message:s?"You don't have any Actors yet!":"There are no recent Actors used by you.",stdout:!0});return}let c={...a,items:await Promise.all(a.items.map(async f=>{let p=await n.actor(f.id).get(),g=await n.actor(f.id).runs().list({desc:!0,limit:1}).catch(()=>({count:0,desc:!0,items:[],limit:1,offset:0,total:0}));return{...f,actor:p??null,lastRun:g.items[0]??null}}))};if(c.items=s?this.sortByModifiedAt(c.items):this.sortByLastRun(c.items),i){N(c);return}let d=s?Sl:vl,u=c.items.reduce((f,p)=>{let g=`${p.username}/${p.name}`;return g.length>f?g.length:f},0)+2+6;for(let f of c.items){let p=f.stats.lastRunStartedAt?Pt.display(f.stats.lastRunStartedAt):"",g=f.lastRun?(()=>{if(f.lastRun.finishedAt)return oe.format(f.lastRun.finishedAt.getTime()-f.lastRun.startedAt.getTime());let C=Date.now()-f.lastRun.startedAt.getTime();return`${oe.format(C)}\u2026`})():"",y=f.actor?(()=>{let C=Object.entries(f.actor.taggedBuilds??{}).find(([T,I])=>I.buildNumber===f.actor.defaultRunOptions.build||T===f.actor.defaultRunOptions.build);return C?`${q.yellow(C[0])} / ${q.cyan(C[1].buildNumber??f.actor.defaultRunOptions.build)}`:q.gray("Unknown")})():q.gray("Unknown"),b=(()=>{if(f.lastRun){let T=[be(f.lastRun.status)];if(g&&T.push(Tl[f.lastRun.status],q.cyan(g)),f.lastRun.finishedAt){let I=Date.now()-f.lastRun.finishedAt.getTime();I<bl.Week?T.push(`
68
+ `,q.gray(`${oe.format(I)} ago`)):T.push(`
69
+ `,q.gray("On",Si.display(f.lastRun.finishedAt)))}return T.join(" ")}return""})();d.pushRow({Name:`${f.title}
70
+ ${q.gray(`${f.username}/${f.name}`)}`,Runs:V.isSmallTerminal()&&u>=56?Ir:q.cyan(`${f.stats?.totalRuns??0}`),"Last run started at":p,"Last run":p,"Last run status":f.lastRun?be(f.lastRun.status):"","Modified at":Pt.display(f.modifiedAt),Builds:f.actor?q.cyan(f.actor.stats.totalBuilds):q.gray("Unknown"),"Last run duration":V.isSmallTerminal()?Ir:q.cyan(g),"Default build":y,_Small_LastRunText:b})}_({message:d.render(1),stdout:!0})}sortByModifiedAt(e){return e.sort((r,o)=>{let s=new Date(r.modifiedAt);return new Date(o.modifiedAt).getTime()-s.getTime()})}sortByLastRun(e){return e.sort((r,o)=>{let s=new Date(r.stats?.lastRunStartedAt??"1970-01-01T00:00Z");return new Date(o.stats?.lastRunStartedAt??"1970-01-01T00:00Z").getTime()-s.getTime()})}};import{mkdirSync as rn,readdirSync as Ml,writeFileSync as on}from"fs";import{dirname as Bl,join as Vl}from"path";import sn from"process";import Yl from"adm-zip";import Gl from"axios";import nn from"jju";import{gt as Hl}from"semver";import Jl from"tiged";import{mkdir as xl,rename as tn,writeFile as Ol}from"fs/promises";import{dirname as Nl,join as Ll}from"path";import en from"process";import{inspect as Dl}from"util";import{err as Ht,ok as Or}from"@sapphire/result";import{createPrompt as Cl,isEnterKey as Il,makeTheme as $l,useKeypress as El,usePrefix as Rl,useState as zi}from"@inquirer/core";function As(t,e){let r=e!==!1;return/^(y|yes)/i.test(t)?r=!0:/^(n|no)/i.test(t)&&(r=!1),r}l(As,"getBooleanValue");function Xi(t){return t?"Yes":"No"}l(Xi,"boolToString");var Zi=Cl((t,e)=>{let r=Xi,[o,s]=zi("idle"),[i,n]=zi(""),a=$l(),c=Rl({status:o,theme:a});El((p,g)=>{if(Il(p)){let y=As(i,t.default);n(r(y)),s("done"),e(y);return}if(p.name==="tab"){let y=Xi(!As(i,t.default));g.clearLine(0),g.write(y),n(y);return}if(p.name==="y"||p.name==="n"){let y=As(p.name,t.default);n(r(y)),s("done"),e(y);return}g.clearLine(0),g.write(i),n(g.line)});let d=i,u="";o==="done"?d=a.style.answer(i):u=` ${a.style.defaultAnswer(t.default===!1?"y/N":"Y/n")}`;let f=a.style.message(t.message,o);return`${c} ${f}${u} ${d}`});import _l from"is-ci";var bs="confirm",Qi=`no-${bs}`;function Ee(t,{errorMessageForStdin:e=`Please use the --${bs}/--${Qi} flags to confirm the action.`}={}){return async(r,...o)=>{let{isTTY:s,hasData:i}=await wr(),n=r;if(_l||!s&&!i){if(typeof n.providedConfirmFromStdin>"u")throw new Error(n.errorMessageForStdin??e??`Please use the --${bs}/--${Qi} flags to confirm the action.`);return n.providedConfirmFromStdin}return await t(r,...o)}}l(Ee,"stdinCheckWrapper");var H=Ee(async({message:t,default:e})=>await Zi({message:t,default:e}));var Pl=l(t=>Ll(t,or),"getDeprecatedLocalConfigPath"),xr=new Map;async function Me({cwd:t=en.cwd(),migrateConfig:e=!0,warnAboutOldConfig:r=!0}={cwd:en.cwd(),migrateConfig:!0,warnAboutOldConfig:!0}){let o=xr.get(t);if(o)return $("useActorConfig",{cacheHit:!0,config:o}),Or(o);let s=cs(t),i=Pl(t),n,a;try{n=ve(s)}catch(d){return Ht({message:`Failed to read local config at path: '${s}':`,cause:d,exists:!1,config:{}})}try{a=ve(i)}catch(d){return Ht({message:`Failed to read local config at path: '${i}':`,cause:d,exists:!1,config:{}})}if(n&&a&&r&&await kl(i),!n&&!a)return xr.set(t,{exists:!1,migrated:!1,config:{}}),Or({exists:!1,migrated:!1,config:{}});let c=!1;if(!n&&a&&e){let d=await Ul(a,i,s);if(d.isErr())return Ht(d.unwrapErr());n=d.unwrap(),c=!0}return xr.set(t,{exists:!0,migrated:c,config:n||a||{}}),$("useActorConfig",{cacheHit:!1,config:xr.get(t)}),Or({exists:!0,migrated:c,config:n||a||{}})}l(Me,"useActorConfig");async function kl(t){if(!await H({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Since we have found both files in your Actor directory, "apify.json" will be renamed to "apify.json.deprecated". Going forward, all commands will use ".actor/actor.json". You can read about the differences between the old and the new config at https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md. Do you want to continue?'})){x({message:'The "apify.json" file present in your Actor directory will be ignored, and the new ".actor/actor.json" file will be used instead. Please, either rename or remove the old file.'});return}try{await tn(t,`${t}.deprecated`),v({message:'The "apify.json" file has been renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted.'})}catch(r){r instanceof Error?m({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
71
+ ${r.message||r}`}):m({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
72
+ ${Dl(r,{showHidden:!1})}`})}}l(kl,"handleBothConfigVersionsFound");var Fl=["name","version","buildTag"];async function Ul(t,e,r){let o={...t};if(typeof o.version=="object"&&(o=jl(o)),o={actorSpecification:es,environmentVariables:t?.env||void 0,...Fl.reduce((i,n)=>(i[n]=t[n],i),{})},!await H({message:'The new version of Apify CLI uses the ".actor/actor.json" instead of the "apify.json" file. Your "apify.json" file will be automatically updated to the new format under ".actor/actor.json". The original file will be renamed by adding the ".deprecated" suffix. Do you want to continue?'}))return Ht({message:'Command can not run with old "apify.json" structure. Either let the CLI auto-update it or follow the guide on https://github.com/apify/apify-cli/blob/master/MIGRATIONS.md and update it manually.',exists:!0,config:o});try{await xl(Nl(r),{recursive:!0}),await Ol(r,JSON.stringify(o,null," "))}catch(i){let n=i;return Ht({message:`Failed to write the new "actor.json" file to path: '${r}'.
73
+ ${n.message||n}`,exists:!0,config:o})}try{await tn(e,`${e}.deprecated`)}catch(i){let n=i;x({message:`Failed to rename the deprecated "apify.json" file to "apify.json.deprecated".
74
+ ${n.message||n}`})}return v({message:'The "apify.json" file has been migrated to ".actor/actor.json" and the original file renamed to "apify.json.deprecated". The deprecated file is no longer used by the CLI or Apify Console. If you do not need it for some specific purpose, it can be safely deleted. Do not forget to commit the new file to your Git repository.'}),Or(o)}l(Ul,"handleMigrationFlow");function jl(t){let e={name:t.name,template:t.template,version:t.version.versionNumber,buildTag:t.version.buildTag,env:null};if(t.version.envVars?.length){let r={};t.version.envVars.forEach(o=>{o.name&&o.value&&(r[o.name]=o.value)}),e.env=r}return e}l(jl,"updateLocalConfigStructure");var an=l(async(t,e)=>{let{data:r}=await Gl.get(t,{responseType:"arraybuffer"}),o=new Yl(Buffer.from(r,"binary"));o.extractEntryTo(o.getEntries()[0].entryName,e,!1)},"extractGitHubZip"),vt=class extends h{static name="pull";static description="Download Actor code to current directory. Clones Git repositories or fetches Actor files based on the source type.";static flags={version:A.string({char:"v",description:"Actor version number which will be pulled, e.g. 1.2. Default: the highest version",required:!1}),dir:A.string({description:"Directory where the Actor should be pulled to",required:!1})};static args={actorId:w.string({required:!1,description:'Name or ID of the Actor to run (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will update the Actor in the current directory based on its name in ".actor/actor.json" file.'})};async run(){let e=sn.cwd(),r=await Me({cwd:e});if(r.isErr()){m({message:r.unwrapErr().message}),sn.exitCode=5;return}let{config:o}=r.unwrap(),s=await k(),i=await S(),n=!this.args.actorId,a=s.username||s.id,c=this.args?.actorId||o?.id||(o?.name?`${a}/${o.name}`:void 0);if(!c)throw new Error("Cannot find Actor in this directory.");let d;try{d=await i.actor(c).get()}catch{throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`)}if(!d)throw new Error(`Cannot find Actor with ID/name '${c}' in your account.`);let{name:u,versions:f}=d,p=null;if(this.flags.version&&(p=f.find(y=>y.versionNumber===this.flags.version),!p))throw new Error(`Cannot find version ${this.flags.version} of Actor ${c}.`);p||(p=f.reduce((y,b)=>Hl(`${b.versionNumber}.0`,`${y.versionNumber}.0`)?b:y));let g=n?e:Vl(e,this.flags.dir??u);if(rn(g,{recursive:!0}),!n&&Ml(g).length!==0){m({message:`Directory ${g} is not empty. Please empty it or choose another directory.`});return}switch(p.sourceType){case"TARBALL":{await an(p.tarballUrl,g);break}case"SOURCE_FILES":{let{sourceFiles:y}=p;for(let b of y){let C=Bl(b.name);if(rn(`${g}/${C}`,{recursive:!0}),!b.folder){let T=b.format==="BASE64"?Buffer.from(b.content,"base64").toString():b.content;if(b.name===M){let I=nn.parse(T);I.name=d.name,on(`${g}/${b.name}`,nn.update(T,I))}else on(`${g}/${b.name}`,T)}}break}case"GIT_REPO":{let{gitRepoUrl:y}=p,[b,C]=y.split("#"),T,I;C&&([T,I]=C.split(":"));let L=b;I&&(L+=`/${I}`),T&&(L+=`#${T}`);let D=Jl(L);try{await D.clone(g)}catch(j){throw new Error(`Failed to pull Actor from ${y}. ${j.message}`)}break}case"GITHUB_GIST":{await an(`${p.gitHubGistUrl}/archive/master.zip`,g);break}default:throw new Error(`Unknown source type: ${p.sourceType}`)}R({message:n?`Actor ${u} updated at ${g}/`:`Pulled to ${g}/`})}};import{readFileSync as Wl,statSync as zl,unlinkSync as Xl}from"fs";import{join as Zl,resolve as Ql}from"path";import rt from"process";import eu from"is-ci";import tu from"open";import{fetchManifest as ru}from"@apify/actor-templates";import{ACTOR_JOB_STATUSES as ot,ACTOR_SOURCE_TYPES as vs,MAX_MULTIFILE_BYTES as hn}from"@apify/consts";import{readFileSync as Kl,writeFileSync as ql}from"fs";var Ts="@",cn=100,ln=5e4,Nr=l(()=>{try{return JSON.parse(Kl(tr(),"utf-8"))||{}}catch{return{}}},"getSecretsFile"),un=l(t=>(Qe(tr()),ql(tr(),JSON.stringify(t,null," ")),t),"writeSecretsFile"),dn=l((t,e)=>{let r=Nr();if(r[t])throw new Error(`Secret with name ${t} already exists. Call "apify secrets rm ${t}" to remove it.`);if(typeof t!="string"||t.length>cn)throw new Error(`Secret name has to be string with maximum length ${cn}.`);if(typeof e!="string"||e.length>ln)throw new Error(`Secret value has to be string with maximum length ${ln}.`);return r[t]=e,un(r)},"addSecret"),mn=l(t=>{let e=Nr();if(!e[t])throw new Error(`Secret with name ${t} doesn't exist.`);delete e[t],un(e)},"removeSecret"),pn=l(t=>new RegExp(`^${Ts}.{1}`).test(t),"isSecretKey"),fn=l((t,e)=>{e=e||Nr();let r={};return Object.keys(t).forEach(o=>{if(pn(t[o])){let s=t[o].replace(new RegExp(`^${Ts}`),"");e[s]?r[o]=e[s]:x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else r[o]=t[o]}),r},"replaceSecretsValue"),gn=l((t,e)=>{e=e||Nr();let r=[];return Object.keys(t).forEach(o=>{if(pn(t[o])){let s=t[o].replace(new RegExp(`^${Ts}`),"");e[s]?r.push({name:o,value:e[s],isSecret:!0}):x({message:`Value for ${s} not found in local secrets. Set it by calling "apify secrets add ${s} [SECRET_VALUE]"`})}else r.push({name:o,value:t[o]})}),r},"transformEnvToEnvVars");var Ss="temp_file.zip",ou={build:"latest",memoryMbytes:4096,timeoutSecs:3600},yn="0.0",su="latest",St=class extends h{static name="push";static description=`Deploys Actor to Apify platform using settings from '${M}'.
75
+ Files under '${hn/1024**2}' MB upload as "Multiple source files"; larger projects upload as ZIP file.
76
+ Use --force to override newer remote versions.`;static flags={version:A.string({char:"v",description:`Actor version number to which the files should be pushed. By default, it is taken from the '${M}' file.`,required:!1}),"build-tag":A.string({char:"b",description:`Build tag to be applied to the successful Actor build. By default, it is taken from the '${M}' file`,required:!1}),"wait-for-finish":A.string({char:"w",description:"Seconds for waiting to build to finish, if no value passed, it waits forever.",required:!1}),"no-prompt":A.boolean({description:"Do not prompt for opening the Actor details in a browser. This will also not open the browser automatically.",default:!1,required:!1}),force:A.boolean({description:"Push an Actor even when the local files are older than the Actor on the platform.",default:!1,required:!1}),dir:A.string({description:"Directory where the Actor is located",required:!1})};static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to push (e.g. "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command will create or modify the Actor with the name specified in '${M}' file.`})};async run(){let e=Ql(rt.cwd(),this.flags.dir??"."),r=await hi(e);if(!r.length){m({message:"You need to call this command from a folder that has an Actor in it!"}),rt.exitCode=4;return}if(![or,"actor.json",".actor/actor.json",".actor"].some(P=>r.some(Q=>Q===P||Q.startsWith(P)))){m({message:["A valid Actor could not be found in the current directory. Please make sure you are in the correct directory.","You can also turn this directory into an Actor by running `apify init`."].join(`
77
+ `)}),rt.exitCode=4;return}let o=await S(),s=await Me({cwd:e});if(s.isErr()){m({message:s.unwrapErr().message}),rt.exitCode=5;return}let{config:i}=s.unwrap(),n=await k(),c=!!n.organizationOwnerUserId?`/organization/${n.id}`:"",d,u,f=!1,p=this.flags.version||i?.version||yn,g=this.flags.buildTag||i?.buildTag;!g&&p===yn&&(g=su);let y=Number.isNaN(this.flags.waitForFinish)?void 0:Number.parseInt(this.flags.waitForFinish,10)*1e3,b=this.args.actorId;if(b){if(u=await o.actor(b).get(),!u)throw new Error(`Cannot find Actor with ID '${b}' in your account.`);d=u.id}else{let P=n.username||n.id;if(u=await o.actor(`${P}/${i.name}`).get(),u)d=u.id;else{let{templates:Q}=await ru(),Le=Q.find(Qt=>Qt.name===i.template)?.defaultRunOptions||ou,Zo={name:i.name,defaultRunOptions:Le,versions:[{versionNumber:p,buildTag:g,sourceType:vs.SOURCE_FILES,sourceFiles:[]}]};u=await o.actors().create(Zo),d=u.id,f=!0,v({message:`Created Actor with name ${i.name} on Apify.`})}}v({message:`Deploying Actor '${i.name}' to Apify.`});let C=await si(r,e),T=o.actor(d),I,L,D;if(C<hn){let P=await T.get();if(!f){let Q=r.reduce((Le,Zo)=>{let{mtimeMs:Qt,ctimeMs:Hs}=zl(Zl(e,Zo)),Js=Qt>Hs?Qt:Hs;return Le>Js?Le:Js},0),he=P?.modifiedAt.valueOf();if(!this.flags.force&&he&&Q<he&&(i?.name||b))throw new Error(`Actor with identifier "${i?.name||b}" is already on the platform and was modified there since modified locally.
78
+ Skipping push. Use --force to override.`)}L=await gi(r,e),I=vs.SOURCE_FILES}else{ye({message:"Zipping Actor files"}),await yi(Ss,r,e);let P=await o.keyValueStores().getOrCreate(`actor-${d}-source`),Q=`version-${p}.zip`,he=Wl(Ss);await o.keyValueStore(P.id).setRecord({key:Q,value:he,contentType:"application/zip"}),Xl(Ss),D=`${o.baseUrl}/key-value-stores/${P.id}/records/${Q}?disableRedirect=true`,I=vs.TARBALL}let j=await T.version(p).get(),Y=i.environmentVariables?gn(i.environmentVariables):void 0;if(j){let P={tarballUrl:D,sourceFiles:L,buildTag:g,sourceType:I,envVars:Y};await T.version(p).update(P),ye({message:`Updated version ${p} for Actor ${u.name}.`})}else{let P={versionNumber:p,tarballUrl:D,sourceFiles:L,buildTag:g,sourceType:I,envVars:Y};await T.versions().create({...P}),ye({message:`Created version ${p} for Actor ${u.name}.`})}ye({message:`Building Actor ${u.name}`});let J=await T.build(p,{useCache:!0,waitForFinish:2});try{await Se({job:J,timeoutMillis:y,apifyClient:o})}catch(P){x({message:"Can not get log:"}),console.error(P)}J=await o.build(J.id).get(),Ks({message:"Actor build detail",url:`https://console.apify.com${c}/actors/${J.actId}#/builds/${J.buildNumber}`}),!eu&&!this.flags.noPrompt&&await H({message:"Do you want to open the Actor detail in your browser?"})&&await tu(`https://console.apify.com${c}/actors/${J.actId}`),J.status===ot.SUCCEEDED?R({message:"Actor was deployed to Apify cloud and built there."}):J.status===ot.READY?x({message:"Build is waiting for allocation."}):J.status===ot.RUNNING?x({message:"Build is still running."}):J.status===ot.ABORTED||J.status===ot.ABORTING?(x({message:"Build was aborted!"}),rt.exitCode=3):J.status===ot.TIMED_OUT||J.status===ot.TIMING_OUT?(x({message:"Build timed out!"}),rt.exitCode=2):(m({message:"Build failed!"}),rt.exitCode=1)}};var Lr=class extends h{static name="rm";static description="Permanently removes an Actor from your account.";static args={actorId:w.string({description:"The Actor ID to delete.",required:!0})};async run(){let{actorId:e}=this.args,r=await S();if(!await r.actor(e).get()){m({message:`Actor with ID "${e}" was not found on your account.`});return}if(!await H({message:"Are you sure you want to delete this Actor?"})){v({message:`Deletion of Actor "${e}" was canceled.`});return}try{await r.actor(e).delete(),R({message:`Actor with ID "${e}" was deleted.`})}catch(i){let n=i;m({message:`Failed to delete Actor "${e}".
79
+ ${n.message||n}`})}}};import X from"chalk";var Dr=class extends h{static name="start";static description=`Starts Actor remotely and returns run details immediately.
80
+ Uses authenticated account and local key-value store for input.`;static flags={...Tt("Actor"),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};static enableJsonFlag=!0;static args={actorId:w.string({required:!1,description:`Name or ID of the Actor to run (e.g. "my-actor", "apify/hello-world" or "E2jjCZBezvAZnX8Rb"). If not provided, the command runs the remote Actor specified in the '${M}' file.`})};async run(){let e=process.cwd(),r=Pe(e)||{},o=await S(),s=await k(),i=s.username||s.id,{id:n,userFriendlyId:a,actorData:c}=await je.resolveActorId({client:o,localActorName:r.name,usernameOrId:i,providedActorNameOrId:this.args.actorId}),d={};this.flags.build&&(d.build=this.flags.build),this.flags.timeout&&(d.timeout=this.flags.timeout),this.flags.memory&&(d.memory=this.flags.memory);let u=await At(e,this.flags.input,this.flags.inputFile);if(u===!1)return;let f=bt(o,{actorOrTaskData:{id:n,userFriendlyId:a},runOptions:d,type:"Actor",inputOverride:u?.input,silent:!0,waitForRunToFinish:!1,printRunLogs:!1}),p;for await(let D of f)p=D;if(this.flags.json){N(p);return}let g=`https://console.apify.com/actors/${n}/runs/${p.id}`,y=`https://console.apify.com/storage/datasets/${p.defaultDatasetId}`,b=[`${X.gray("Run:")} Calling Actor ${a} (${X.gray(n)})`,"",`${X.yellow("Started")}: ${B.display(p.startedAt)}`];p.containerUrl&&b.push(`${X.yellow("Container URL")}: ${X.blue(p.containerUrl)}`);let C=p.buildNumber.split(".").slice(0,2).join("."),T=c.versions.find(D=>D.versionNumber===C),I=Object.entries(c.taggedBuilds??{}).find(([,D])=>D.buildNumber===p.buildNumber)?.[0],L=[`${X.yellow("Build")}:`,X.cyan(p.buildNumber)];I?L.push(`(${X.yellow(I)})`):L.push(`(${X.gray("N/A")})`),T&&L.push(`| ${X.gray("Actor version:")} ${X.cyan(T.versionNumber)} (${X.yellow(T.buildTag)})`),b.push(L.join(" ")),b.push(`${X.yellow("Timeout")}: ${p.options.timeoutSecs.toLocaleString("en-US")} seconds`),b.push(`${X.yellow("Memory")}: ${p.options.memoryMbytes} MB`),b.push("",`${X.blue("Export results")}: ${y}`,`${X.blue("View on Apify Console")}: ${g}`),_({message:b.join(`
81
+ `),stdout:!0})}};var Pr=class extends h{static name="actors";static description="Manages Actor creation, deployment, and execution on the Apify platform.";static subcommands=[Dr,Lr,St,vt,_r,Rr,je,Sr];async run(){this.printHelp()}};import z from"chalk";var iu=l(t=>t,"noColor");function W({bytes:t,shortBytes:e=!1,colorFunc:r=iu,precision:o=2}){let s=[e?"B":"Bytes","KB","MB","GB","TB"];if(t===0)return e?`${0 .toPrecision(o)} B`:`${0 .toPrecision(o)} Byte`;let i=Math.floor(Math.log(t)/Math.log(1e3));return`${(t/1e3**i).toFixed(o)} ${r(s[i])}`}l(W,"prettyPrintBytes");var kr=class extends h{static name="info";static description="Prints information about a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get information about."})};static enableJsonFlag=!0;async run(){let{buildId:e}=this.args,r=await S(),o=await r.build(e).get();if(!o){m({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}if(this.flags.json){N(o);return}let s=await r.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[g,y]of Object.entries(s.taggedBuilds))if(y.buildId===o.id){i=g;break}}let n=Reflect.get(o,"exitCode"),a=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",c=i?` (tagged as ${z.yellow(i)})`:"",d=typeof n<"u"?` (exit code: ${z.gray(n)})`:"",u=[`${z.yellow("Actor")}: ${a} (${z.gray(o.actId)})`,"",`${z.yellow("Build Information")} (ID: ${z.gray(o.id)})`,` ${z.yellow("Build Number")}: ${o.buildNumber}${c}`,` ${z.yellow("Status")}: ${be(o.status)}${d}`,` ${z.yellow("Started")}: ${B.display(o.startedAt)}`];if(o.finishedAt)u.push(` ${z.yellow("Finished")}: ${B.display(o.finishedAt)} (took ${z.gray(kt.format(o.stats?.durationMillis??0))})`);else{let g=Date.now()-o.startedAt.getTime();u.push(` ${z.yellow("Finished")}: ${z.gray(`Running for ${kt.format(g)}`)}`)}o.stats?.computeUnits&&u.push(` ${z.yellow("Compute Units")}: ${o.stats.computeUnits.toFixed(3)}`);let f=Reflect.get(o.stats??{},"imageSizeBytes");f&&u.push(` ${z.yellow("Docker Image Size")}: ${W({bytes:f})}`),u.push(` ${z.yellow("Origin")}: ${o.meta.origin??"UNKNOWN"}`),u.push("");let p=`https://console.apify.com/actors/${o.actId}/builds/${o.buildNumber}`;u.push(`${z.blue("View in Apify Console")}: ${p}`),_({message:u.join(`
82
+ `),stdout:!0})}};var Fr=class extends h{static name="log";static description="Prints the log of a specific build.";static args={buildId:w.string({required:!0,description:"The build ID to get the log from."})};async run(){let{buildId:e}=this.args,r=await S(),o=await r.build(e).get();if(!o){m({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for build with ID "${e}":
83
+ `});try{await Se({job:o,apifyClient:r})}catch(s){m({message:`Failed to get log for build with ID "${e}": ${s.message}`,stdout:!0})}}};import me from"chalk";var nu=l(()=>new V({allColumns:["Number","ID","Status","Took"],mandatoryColumns:["Number","ID","Status","Took"],columnAlignments:{Took:"right"}}),"tableFactory"),Ur=class extends h{static name="ls";static description="Lists all builds of the Actor.";static flags={offset:A.integer({description:"Number of builds that will be skipped.",default:0}),limit:A.integer({description:"Number of builds that will be listed.",default:10}),desc:A.boolean({description:"Sort builds in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:r,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await S(),c=await Fe({providedActorNameOrId:n,client:a});if(!c.valid){m({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`,stdout:!0});return}let d=await a.actor(c.id).builds().list({desc:e,limit:r,offset:o}),u=await a.actor(c.id).get(),f=mr(d.items,y=>{let b=Reflect.get(y,"buildNumber"),[C,T]=b.split(".");return`${C}.${T}`}),p=Object.entries(u.taggedBuilds??{}).reduce((y,[b,C])=>(y[C.buildNumber]=b,y),{});if(i){for(let y of d.items){let b=Reflect.get(y,"buildNumber"),C=p[b];C&&Reflect.set(y,"buildTag",C)}N(d);return}_({message:`${me.reset("Showing")} ${me.yellow(d.items.length)} out of ${me.yellow(d.total)} builds for Actor ${me.yellow(c.userFriendlyId)} (${me.gray(c.id)})
84
+ `,stdout:!0});let g=Object.entries(f).sort((y,b)=>y[0].localeCompare(b[0]));for(let[y,b]of g){if(!b?.length){_({message:`No builds for version ${y}`,stdout:!0});continue}let C=u.versions.find(D=>D.versionNumber===y)?.buildTag,T=this.generateTableForActorVersion({buildsForVersion:b,buildTagToActorVersion:p}),I=C?` (latest build gets tagged with ${me.yellow(C)})`:"",L=[me.reset(`Builds for Actor Version ${me.yellow(y)}${I}`),T.render(s?0:-1),""];_({message:L.join(`
85
+ `),stdout:!0})}}generateTableForActorVersion({buildsForVersion:e,buildTagToActorVersion:r}){let o=nu();for(let s of e){let i=Reflect.get(s,"buildNumber"),n=r[i]?` (${me.yellow(r[i])})`:"",a;if(s.finishedAt){let c=s.finishedAt.getTime()-s.startedAt.getTime();a=me.gray(`${oe.format(c,void 0,{left:""})}`)}else{let c=Date.now()-s.startedAt.getTime();a=me.gray(`Running for ${oe.format(c,void 0,{left:""})}`)}o.pushRow({Number:`${i}${n}`,ID:me.gray(s.id),Status:be(s.status),Took:a})}return o}};import au from"@inquirer/input";var wn=Ee(async({message:t,expectedValue:e,failureMessage:r})=>await au({message:t,validate(s){return s===e?!0:r??"That is not the correct input!"}}));var jr=class extends h{static name="rm";static description="Permanently removes an Actor build from the Apify platform.";static args={buildId:w.string({description:"The build ID to delete.",required:!0})};async run(){let{buildId:e}=this.args,r=await S(),o=await r.build(e).get();if(!o){m({message:`Build with ID "${e}" was not found on your account.`,stdout:!0});return}let s=await r.actor(o.actId).get(),i;if(s?.taggedBuilds){for(let[a,c]of Object.entries(s.taggedBuilds))if(e===c.buildId){i=a;break}}if(!await(i?wn:H)({message:`Are you sure you want to delete this Actor Build?${i?` If so, please type in "${i}":`:""}`,expectedValue:i??"",failureMessage:"Your provided value does not match the build tag."})){v({message:`Deletion of build "${e}" was canceled.`,stdout:!0});return}try{await r.build(e).delete(),R({message:`Build with ID "${e}" was deleted.`,stdout:!0})}catch(a){let c=a;m({message:`Failed to delete build "${e}".
86
+ ${c.message||c}`,stdout:!0})}}};var Mr=class extends h{static name="builds";static description="Manages Actor build processes and versioning.";static subcommands=[jr,Ur,Fr,kr,wt];async run(){this.printHelp()}};var Br=class extends je{static name="call"};import cu from"assert";import{existsSync as Vr}from"fs";import{mkdir as lu,readFile as uu,symlink as du,unlink as mu,writeFile as An}from"fs/promises";import{basename as pu,join as pe}from"path";import Be from"chalk";var fu=l(t=>pe(t,".install-marker"),"pathToInstallMarker"),Cs=l(t=>t.startsWith(process.env.HOME)?t.replace(process.env.HOME,"~"):t,"tildify"),Jt=class extends h{static name="install";static description="Finalizes the first-time setup of Apify and Actor CLI.";static hidden=!0;async run(){let{installMethod:e,installPath:r,version:o}=ee();if(e!=="bundle"){v({message:`Apify and Actor CLI are already fully configured! \u{1F44D}
87
+ `});return}cu(r,"When CLI is installed via bundles, the install path must be set");let s=fu(r);if(Vr(s)){v({message:`Apify and Actor CLI are already fully configured! \u{1F44D}
88
+ `});return}await this.symlinkToLocalBin(r),await this.promptAddToShell(),await An(s,o),$("[install] install marker written to",s),_({message:""}),R({message:"To get started, run:"}),_({message:Be.white.bold(` apify --help
89
+ actor --help`)})}async symlinkToLocalBin(e){let r=process.env.HOME;if($("[install] user home directory",r),!r){$("[install] user home directory not found"),x({message:Be.gray("User home directory not found, cannot symlink to ~/.local/bin")});return}let o=pe(r,".local","bin");Vr(o)||await lu(o,{recursive:!0});let s=["apify","actor","apify-cli"];for(let i of s){let n=pe(e,i);if(!Vr(n)){$("[install] file not found for symlinking",i,n),x({message:Be.gray(`Bundle not found for symlinking: ${i}`)});continue}let a=pe(o,i);await mu(a),await du(n,a),$("[install] symlink created for item",i,a)}v({message:Be.gray(`Symlinked apify, actor, and apify-cli to ${o}`)})}async promptAddToShell(){let e=process.env.PROVIDED_INSTALL_DIR;if(!e){x({message:Be.gray("Install directory not found, cannot add to shell")});return}let r=process.env.FINAL_BIN_DIR;_({message:""});let o=await H({message:"Should the CLI handle adding itself to your shell automatically? (If you say no, you will receive the lines to add to your shell config file)",providedConfirmFromStdin:!1}),s=pu(process.env.SHELL??"sh"),i=`"${e.replaceAll('"','\\"')}"`,n=[],a="";switch(s){case"bash":{n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"');let c=[pe(process.env.HOME,".bashrc"),pe(process.env.HOME,".bash_profile")];process.env.XDG_CONFIG_HOME&&c.push(pe(process.env.XDG_CONFIG_HOME,".bashrc"),pe(process.env.XDG_CONFIG_HOME,".bash_profile"),pe(process.env.XDG_CONFIG_HOME,"bashrc"),pe(process.env.XDG_CONFIG_HOME,"bash_profile"));for(let d of c)if(Vr(d)){a=d;break}break}case"zsh":n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a=pe(process.env.HOME,".zshrc");break;case"fish":{n.push(`set --export APIFY_CLI_INSTALL ${i}`),n.push(`set --export PATH ${r} $PATH`),a=pe(process.env.HOME,".config","fish","config.fish");break}default:n.push(`export APIFY_CLI_INSTALL=${i}`),n.push('export PATH="$APIFY_CLI_INSTALL/bin:$PATH"'),a="~/.bashrc";break}if(_({message:""}),o&&a){let d=`${await uu(a,"utf-8")}
90
+
91
+ # apify cli
92
+ ${n.join(`
93
+ `)}`;await An(a,d),v({message:Be.gray(`Added "${Cs(r)}" to $PATH in ${Cs(a)}`)})}else v({message:[Be.gray(`Manually add the following lines to your shell config file (${Cs(a)} or similar):`),...n.map(c=>Be.white.bold(` ${c}`))].join(`
94
+ `)})}};import{spawn as Su}from"child_process";import{existsSync as Cu}from"fs";import{lstat as Iu,readdir as $u,writeFile as vn}from"fs/promises";import{dirname as Eu,join as Is}from"path";import $s from"chalk";import{gte as Sn}from"semver";import{Result as hu}from"@sapphire/result";import{execa as yu}from"execa";import{isAbsolute as gu}from"path";function Ve(t){return t?t.startsWith('"')?t:gu(t)&&t.includes(" ")?`"${t}"`:t:null}l(Ve,"normalizeExecutablePath");var wu=l(async(t,e,r)=>{let o=Ve(t);$("spawnPromised",{escapedCommand:o,args:e,opts:r});let s=yu(o,e,{shell:!0,windowsHide:!0,env:r.env,cwd:r.cwd,stdout:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],stderr:process.env.APIFY_NO_LOGS_IN_TESTS?["pipe"]:["pipe","inherit"],verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return hu.fromAsync(s.catch(i=>{throw new Error(`${t} exited with code ${i.exitCode}`,{cause:i})}))},"spawnPromised");async function fe({cmd:t,args:e=[],opts:r={},overrideCommand:o}){ye({message:`${o||t} ${e.join(" ")}`});let s=await wu(t,e,r);if(s.isErr()){let i=s.unwrapErr();if(m({message:i.message}),i.cause)throw i.cause}}l(fe,"execWithLog");import{execSync as bn}from"child_process";import{existsSync as Au,readFileSync as bu}from"fs";var Oe=ee();function Tu(){return Oe.platform==="linux"?Au("/etc/alpine-release"):!1}l(Tu,"isInstalledOnMusl");function vu(){return Oe.platform==="darwin"&&Oe.arch==="x64"?!bn("sysctl -a",{encoding:"utf-8"}).includes("AVX2"):Oe.platform==="linux"&&Oe.arch==="x64"?!bu("/proc/cpuinfo","utf-8").includes("avx2"):Oe.platform==="windows"?Oe.arch==="arm64"?!0:bn(`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":!1}l(vu,"isInstalledOnBaseline");async function Tn(t){let e=t.replace(/^v(\d+)/,"$1"),r=e==="latest"?"latest":`tags/v${e}`,o=await fetch(`https://api.github.com/repos/apify/apify-cli/releases/${r}`,{headers:{"User-Agent":Bt}});if(!o.ok)return $("useCLIVersionAssets","Failed to fetch release",{statusCode:o.status,body:await o.text(),version:t,tag:r}),null;let s=await o.json(),i=Tu(),n=vu(),a=s.assets.filter(c=>{let[d,u,f,p,g,y]=c.name.replace(e,"version").replace(".exe","").split("-");return f!==Oe.platform||p!==Oe.arch?!1:i?g==="musl":n?y==="baseline"||g==="baseline":!g&&!y});return $("useCLIVersionAssets","Fetched release",{version:s.tag_name,filteredAssets:a}),{assets:a,version:s.tag_name.replace(/^v(\d+)/,"$1")}}l(Tn,"useCLIVersionAssets");var Cn={bundle:l((t,e)=>[`${e}`,"upgrade"],"bundle"),npm:l(t=>["npm","install","-g",`apify-cli@${t}`],"npm"),pnpm:l(t=>["pnpm","install","-g",`apify-cli@${t}`],"pnpm"),bun:l(t=>["bun","install","-g",`apify-cli@${t}`],"bun"),homebrew:l(()=>["brew","upgrade","apify-cli"],"homebrew"),volta:l(t=>["volta","install",`apify-cli@${t}`],"volta")},Yr="0.21.8",In="https://raw.githubusercontent.com/apify/apify-cli/main/scripts/install/upgrade.ps1",Kt=class extends h{static name="upgrade";static description="Checks that installed Apify CLI version is up to date.";static hidden=!0;static aliases=["cv","check-version"];static flags={force:A.boolean({description:"Whether to skip checking the locally cached latest version of the CLI and fetch it from the internet instead.",required:!1,char:"f"}),version:A.string({description:"The version of the CLI to upgrade to. If not provided, the latest version will be used.",required:!1}),"internal-automatic-call":A.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 ji(this.flags.force),{installMethod:r}=ee();if(!e.shouldUpdate||e.currentVersion===qs){this.flags.internalAutomaticCall||v({message:`${this.cliName} is up to date \u{1F44D}
95
+ `});return}if(!this.flags.internalAutomaticCall){await this.handleInstallSpecificVersion("latest");return}let o=Cn[r]("latest",this.entrypoint).join(" ");_({message:""});let s=[`You are using an old version of ${this.cliName}. We strongly recommend you always use the latest available version.`,` \u21AA Run ${$s.bgWhite($s.black(o))} to update! \u{1F44D}
96
+ `].join(`
97
+ `);x({message:s})}async handleInstallSpecificVersion(e){if(e!=="latest"&&!Sn(e,Yr)){m({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Yr}.`});return}let r=await Tn(e);if(!r){m({message:"The provided version does not exist. Please check the version number and try again."});return}let{assets:o,version:s}=r;if(!Sn(s,Yr)){m({message:`The minimum version of the CLI you can manually downgrade/upgrade to is ${Yr}.`});return}let i=ee();if(i.installMethod==="bundle"){if(!o.length){m({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`].join(`
98
+ `)});return}let a=Eu(process.execPath);$("[upgrade] bundleDirectory",a);let c=await $u(a);if(!c.some(d=>d.startsWith("apify")||d.startsWith("actor"))){$("[upgrade] directoryEntries",c),m({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: ${s}`,`- The system you are running on: ${i.platform} ${i.arch}`,`- The directory where the ${this.cliName} bundle is installed: ${a}`].join(`
99
+ `)});return}if(i.platform==="windows")return this.startUpgradeProcess(a,s,o);await this.handleUnixUpgrade(a,s,o),this.successMessage(s);return}let n=Cn[i.installMethod](e,this.entrypoint);if(process.env.APIFY_CLI_DEBUG){v({message:`Would run command: ${n.join(" ")}`});return}try{await fe({cmd:n[0],args:n.slice(1)}),this.successMessage(s)}catch{m({message:`Failed to upgrade the CLI. Please run the following command manually: ${n.join(" ")}`})}}successMessage(e){R({message:`Successfully upgraded to ${e} \u{1F44D}`})}async startUpgradeProcess(e,r,o){await this.upsertUpgradeScript(e);let s=["-ExecutionPolicy","Bypass","-File",`"${Is(e,"upgrade.ps1")}"`,"-ProcessId",process.pid.toString(),"-InstallLocation",`"${e}"`,"-Version",`"${r}"`],i=o.map(a=>a.browser_download_url).join(",");s.push("-AllUrls",`"${i}"`),$("[upgrade] starting upgrade process with args",s),v({message:"Starting upgrade process..."});let n=Su("powershell.exe",s,{detached:!0,shell:!0,stdio:"inherit",windowsHide:!1,windowsVerbatimArguments:!0});n.on("spawn",()=>{$("[upgrade] upgrade process spawned"),n.unref(),process.exit(0)}),n.on("error",a=>{m({message:`Failed to start the upgrade process: ${a.message}`})})}async upsertUpgradeScript(e){let r=Is(e,"upgrade.ps1");if(Cu(r))return;let o=ee(),s=await fetch(In,{headers:{"User-Agent":Bt}});s.ok||(m({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: ${o.platform} ${o.arch}`,`- The URL of the asset that failed to fetch: ${In}`,`- The status code of the response: ${s.status}`].join(`
100
+ `)}),process.exit(1));let i=await s.arrayBuffer();await vn(r,Buffer.from(i)),$("[upgrade] downloaded upgrade script to",r)}async handleUnixUpgrade(e,r,o){let s=ee();for(let i of o){let n=i.name.split("-")[0],a=Is(e,n);v({message:`Downloading ${n}...`});let c=await fetch(i.browser_download_url,{headers:{"User-Agent":Bt}});if(!c.ok){let u=await c.text();$("[upgrade] failed to fetch asset",{asset:i,status:c.status,body:u}),m({message:[`Failed to fetch the ${n} 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: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The status code of the response: ${c.status}`,`- The body of the response: ${u}`].join(`
101
+ `)});return}if(process.env.APIFY_CLI_DEBUG&&!process.env.APIFY_CLI_FORCE){v({message:`Would write asset ${n} to ${a}`});continue}v({message:$s.gray(`Writing ${n} to ${a}...`)});let d=await c.arrayBuffer();try{let u=await Iu(a).then(f=>f.mode).catch(()=>493);await vn(a,Buffer.from(d),{mode:u|448}),$(`[upgrade ${n}] wrote asset to`,a)}catch(u){$("[upgrade] failed to write asset",{error:u}),m({message:[`Failed to write the ${n} 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: ${s.platform} ${s.arch}`,`- The URL of the asset that failed to fetch: ${i.browser_download_url}`,`- The error: ${u.message}`].join(`
102
+ `)})}}}};import{mkdir as od,readdir as sd,stat as id}from"fs/promises";import{join as It}from"path";import Wn from"process";import{gte as nd,minVersion as ad}from"semver";import{fetchManifest as cd,manifestUrl as ld}from"@apify/actor-templates";import{createWriteStream as xu}from"fs";import{pipeline as Ou}from"stream/promises";import{Separator as Rn}from"@inquirer/core";import $n from"chalk";import Ru from"@inquirer/select";var Ye=Ee(async({message:t,choices:e,pageSize:r,loop:o,default:s,instructions:i})=>await Ru({message:t,choices:e,pageSize:r,loop:o,default:s,instructions:i}));import _u from"@inquirer/input";var st=Ee(async({message:t,validate:e,default:r})=>await _u({message:t,validate:e,default:r}),{errorMessageForStdin:"Please provide a valid input based on the command options."});var En=["JavaScript","TypeScript","Python"];async function Es(t){return t?(Dt(t),t):Nu()}l(Es,"ensureValidActorName");async function _n(t,e){let r=await e;if(r instanceof Error)throw r;if(t){let o=r.templates.find(s=>s.name===t);if(!o)throw new Error(`Could not find the selected template: ${t} in the list of templates.`);return o}return On(r)}l(_n,"getTemplateDefinition");async function xn(t,e){let r=await e;if(r instanceof Error)throw r;try{let o=await nr(r.localReadmeSuffixUrl),s=xu(t,{flags:"a"});s.write(`
103
+
104
+ `),await Ou(o,s)}catch(o){x({message:`Could not append local development instructions to README.md. Cause: ${o.message}`})}}l(xn,"enhanceReadmeWithLocalSuffix");async function On(t){let e=await Lu();for(;;){let r=await Du(t,e);if(r){if(await Pu(r))return r}else return On(t)}}l(On,"executePrompts");async function Nu(){return await st({message:"Name of your new Actor:",validate:l(e=>{try{Dt(e)}catch(r){return r.message}return!0},"validate")})}l(Nu,"promptActorName");async function Lu(){return await Ye({message:"Choose the programming language of your new Actor:",choices:En,loop:!1,default:En[0]})}l(Lu,"promptProgrammingLanguage");async function Du(t,e){let r=[...t.templates.filter(s=>s.category.toLowerCase()===e.toLowerCase()).map(s=>({name:s.label,value:s})),new Rn,{name:"Go back",value:!1}];return await Ye({message:"Choose a template for your new Actor. Detailed information about the template will be shown in the next step.",default:r[0],choices:r,loop:!1,pageSize:8})}l(Du,"promptTemplateDefinition");async function Pu(t){let e=[{name:"Install template",value:!0},new Rn,{name:"Go back",value:!1}],r=$n.underline(t.label),o=$n.dim(t.description),i=`Do you want to install the following template?${`
105
+ ${r}:
106
+ ${o}`}`;return await Ye({message:i,default:e[0],choices:e,loop:!1})}l(Pu,"promptTemplateInstallation");import{platform as ku}from"os";import{join as Nn}from"path";import Gr from"process";import{none as Ln,some as Dn}from"@sapphire/result";import{execa as Fu}from"execa";import Uu from"which";var Ge=new Map;async function Pn(t){try{let e=await Fu(t,["-c",'"import platform; print(platform.python_version())"'],{shell:!0,windowsHide:!0,verbose:Gr.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim():null}catch{return null}}l(Pn,"getPythonVersion");async function qt({cwd:t=Gr.cwd(),force:e=!1}={}){let r=Ge.get(t);if(r&&!e)return $("usePythonRuntime",{cacheHit:!0,cwd:t,runtime:r.unwrapOr(null)}),r;let o=ku()==="win32",s=o?["Scripts","python.exe"]:["bin","python3"],i;Gr.env.VIRTUAL_ENV?i=Nn(Gr.env.VIRTUAL_ENV,...s):i=Nn(t,".venv",...s),i=Ve(i);try{let a=await Pn(i);if(a)return Ge.set(t,Dn({executablePath:i,version:a})),$("usePythonRuntime",{cacheHit:!1,cwd:t,runtime:Ge.get(t)?.unwrap()}),Ge.get(t)}catch{}let n=["python3","python",...o?["python3.exe","python.exe"]:[]];for(let a of n)try{let c=Ve(await Uu(a)),d=await Pn(c);if(d)return Ge.set(t,Dn({executablePath:c,version:d})),$("usePythonRuntime",{cacheHit:!1,cwd:t,runtime:Ge.get(t)?.unwrap()}),Ge.get(t)}catch{}return Ge.set(t,Ln),$("usePythonRuntime",{cacheHit:!1,cwd:t,runtime:null}),Ln}l(qt,"usePythonRuntime");import{access as xs,readFile as Ju}from"fs/promises";import{basename as Vn,dirname as Ku,join as G,resolve as Yn}from"path";import qu from"process";import{ok as _s}from"@sapphire/result";import{existsSync as kn,readdirSync as Mu}from"fs";import{join as Kr,resolve as Bu}from"path";import Vu from"configparser";import{readFileSync as ju}from"fs";var Hr=class{static{l(this,"Spider")}name;class_name;start_urls;pathname;constructor(e){this.name=e.name,this.class_name=e.class_name,this.start_urls=e.start_urls,this.pathname=e.pathname}};var Jr=class{static{l(this,"SpiderFileAnalyzer")}pathname;constructor(e){this.pathname=e}getSpiders(){let e=ju(this.pathname,"utf8"),r=/class\s+(\w+)/g,o=[],s=r.exec(e);for(;s;)o.push(new Hr({class_name:s[1],pathname:this.pathname})),s=r.exec(e);return o}};var it=class{static{l(this,"ScrapyProjectAnalyzer")}pathname;configuration=null;settings=null;constructor(e){this.pathname=e,this.settings=null,this.loadScrapyCfg()}static isApplicable(e){return kn(Kr(e,"scrapy.cfg"))}async init(){await this.loadSettings()}loadScrapyCfg(){let e=new Vu,r=Bu(Kr(this.pathname,"scrapy.cfg"));if(!kn(r))throw new Error(`scrapy.cfg not found in "${r}".
107
+ Are you sure there is a Scrapy project there?`);e.read(r),this.configuration=e}async loadSettings(){let e=this.configuration.get("settings","default").split(".")[0],r=await st({message:"Enter the Scrapy BOT_NAME (see settings.py):",default:e}),o=await st({message:"What folder are the Scrapy spider modules stored in? (see SPIDER_MODULES in settings.py):",default:`${e}.spiders`});this.settings={BOT_NAME:r,SPIDER_MODULES:typeof o=="string"?[o]:o}}getName(){return this.settings?.BOT_NAME}getAvailableSpiders(){let e=this.settings?.SPIDER_MODULES;if(!e)throw new Error("SPIDER_MODULES path not found in settings.");let r=[];for(let o of e){let s=Kr(this.pathname,o.replaceAll(".","/")),i=Mu(s,{withFileTypes:!0});for(let n of i)n.isFile()&&n.name.endsWith(".py")&&n.name!=="__init__.py"&&r.push(...new Jr(Kr(s,n.name)).getSpiders())}return r}};import Rs from"process";import{none as Fn,some as Un}from"@sapphire/result";import{execa as Mn}from"execa";import jn from"which";var qr=new Map,Yu={node:["--version"],deno:["eval",'"console.log(process.versions.node)"'],bun:["--eval",'"console.log(process.versions.node)"']};async function Gu(t,e){try{let r=await Mn(t,e,{shell:!0,windowsHide:!0,verbose:Rs.env.APIFY_CLI_DEBUG?"full":void 0});return r.stdout?r.stdout.trim().replace(/^v/,""):null}catch{return null}}l(Gu,"getRuntimeVersion");async function Hu(t){let e=await Mn(t,["--version"],{shell:!0,windowsHide:!0,verbose:Rs.env.APIFY_CLI_DEBUG?"full":void 0});return e.stdout?e.stdout.trim().replace(/^v/,""):null}l(Hu,"getNpmVersion");async function Bn(t=Rs.cwd()){let e=qr.get(t);if(e)return $("useJavaScriptRuntime",{cacheHit:!0,cwd:t,runtime:e.unwrapOr(null)}),e;for(let[r,o]of Object.entries(Yu))try{let s=Ve(await jn(r)),i=await Gu(s,o);if(i){let n={executablePath:s,version:i};if(r==="node"){let a=Ve(await jn("npm").catch(()=>null));a&&(n.pmPath=a,n.pmVersion=await Hu(a),n.pmName="npm")}else n.runtimeShorthand=r,n.pmPath=s,n.pmVersion=i,n.pmName=r;return qr.set(t,Un(n)),$("useJavaScriptRuntime",{cacheHit:!1,cwd:t,runtime:qr.get(t)?.unwrap()}),Un(n)}}catch{}return qr.set(t,Fn),$("useJavaScriptRuntime",{cacheHit:!1,cwd:t,runtime:null}),Fn}l(Bn,"useJavaScriptRuntime");var Gn=new Map;async function Ct({cwd:t=qu.cwd()}={}){let e=Gn.get(t);if(e)return $("useCwdProject",{cacheHit:!0,project:e}),_s(e);let r={type:3},s=await l(async()=>{if(await zu(t)){r.type=2;let c=await qt({cwd:t});r.runtime=c.unwrapOr(void 0);let d=new it(t);if(d.loadScrapyCfg(),d.configuration.hasKey("apify","mainpy_location"))r.entrypoint={path:d.configuration.get("apify","mainpy_location")};else{let u=await Hn(t);u&&(r.entrypoint={path:u})}return}let n=await Hn(t);if(n){r.type=1;let c=await qt({cwd:t});r.entrypoint={path:n},r.runtime=c.unwrapOr(void 0);return}let a=await Wu(t);if(a){r.type=0;let c=await Bn();r.runtime=c.unwrapOr(void 0),a.type==="file"?r.entrypoint={path:a.path}:a.type==="script"&&(r.entrypoint={script:a.script});return}return _s(r)},"check")();return s?.isErr()?($("useCwdProject",{cacheHit:!1,error:s}),s):($("useCwdProject",{cacheHit:!1,project:r}),Gn.set(t,r),_s(r))}l(Ct,"useCwdProject");async function Wu(t){let e=G(t,"package.json");try{let o=await Ju(e,"utf-8"),s=JSON.parse(o);if(s.scripts?.start)return{type:"script",script:"start"};if(s.main)try{return await xs(Yn(t,s.main)),{path:Yn(t,s.main),type:"file"}}catch{}return{type:"unknown-entrypoint"}}catch{}let r=[G(t,"index.js"),G(t,"index.mjs"),G(t,"index.cjs"),G(t,"main.js"),G(t,"main.mjs"),G(t,"main.cjs"),G(t,"src","index.js"),G(t,"src","index.mjs"),G(t,"src","index.cjs"),G(t,"src","main.js"),G(t,"src","main.mjs"),G(t,"src","main.cjs"),G(t,"dist","index.js"),G(t,"dist","index.mjs"),G(t,"dist","index.cjs"),G(t,"dist","main.js"),G(t,"dist","main.mjs"),G(t,"dist","main.cjs")];for(let o of r)try{return await xs(o),{path:o,type:"file"}}catch{}return null}l(Wu,"checkNodeProject");async function Hn(t){let e=Vn(t),r=[G(t,"src","__main__.py"),G(t,"__main__.py"),G(t,e,"__main__.py"),G(t,e.replaceAll("-","_").replaceAll(" ","_"),"__main__.py")];for(let o of r)try{return await xs(o),Vn(Ku(o))}catch{}return null}l(Hn,"checkPythonProject");async function zu(t){return it.isApplicable(t)}l(zu,"checkScrapyProject");import{existsSync as Xu,writeFileSync as Zu}from"fs";import{join as Wr}from"path";import Qu from"process";import ed from"lodash.clonedeep";import{KEY_VALUE_STORE_KEYS as td}from"@apify/consts";import{validateInputSchema as rd}from"@apify/input_schema";var Jn=[".actor/INPUT_SCHEMA.json","./INPUT_SCHEMA.json",".actor/input_schema.json","./input_schema.json"],nt=l(async({forcePath:t,cwd:e}={cwd:Qu.cwd()})=>{if(t)return{inputSchema:ve(t),inputSchemaPath:t};let r=Pe(e);if(typeof r?.input=="object")return{inputSchema:r.input,inputSchemaPath:null};if(typeof r?.input=="string"){let o=Wr(e,ts,r.input);return{inputSchema:ve(o),inputSchemaPath:o}}for(let o of Jn){let s=Wr(e,o);if(Xu(s))return{inputSchema:ve(s),inputSchemaPath:s}}return{inputSchema:null,inputSchemaPath:Wr(e,Jn[0])}},"readInputSchema"),zr=l(async t=>{let e={};try{let{inputSchema:r}=await nt({cwd:t});if(r){let o=new lt({strict:!1});rd(o,r),e=Object.entries(r.properties).reduce((s,[i,n])=>(s[i]=n.type==="boolean"||n.editor==="hidden"?n.default:n.prefill,s),{})}}catch(r){x({message:`Could not create default input based on input schema, creating empty input instead. Cause: ${r.message}`})}finally{let r=Te(),o=Wr(t,r,`${td.INPUT}.json`);Zu(o,JSON.stringify(e,null," "))}},"createPrefilledInputFileFromInputSchema"),Kn=l(t=>{let e={};for(let[r,o]of Object.entries(t.properties))o.default!==void 0&&(e[r]=o.default);return e},"getDefaultsFromInputSchema"),qn=l((t,e)=>{let r=ed(t);r.required=[];for(let[o,s]of Object.entries(t.properties)){let i=t.required?.includes(o),n=s.default!==void 0;i&&!n&&(r.required.push(o),s.type==="array"&&(s.minItems=Math.max(1,s.minItems||0)))}return delete r.$schema,e.compile(r)},"getAjvValidator");var Xr=class extends h{static name="create";static description="Creates an Actor project from a template in a new directory.";static flags={template:A.string({char:"t",description:`Template for the Actor. If not provided, the command will prompt for it.
108
+ Visit ${ld} to find available template names.`,required:!1}),"skip-dependency-install":A.boolean({description:"Skip installing Actor dependencies.",required:!1}),"template-archive-url":A.string({description:"Actor template archive url. Useful for developing new templates.",required:!1,hidden:!0}),"omit-optional-deps":A.boolean({aliases:["no-optional"],description:"Skip installing optional dependencies.",required:!1})};static args={actorName:w.string({required:!1,description:"Name of the Actor and its directory"})};async run(){let{actorName:e}=this.args,{template:r,skipDependencyInstall:o}=this.flags,{templateArchiveUrl:s}=this.flags,i=!1,n=cd().catch(y=>new Error(`Could not fetch template list from server. Cause: ${y?.message}`));e=await Es(e);let a=Wn.cwd(),c=It(a,e);for(;;){let y=await id(c).catch(()=>null),b=y&&await sd(c).then(C=>C.length>0).catch(()=>!1);if(y?.isDirectory()&&b){m({message:`Cannot create new Actor, directory '${e}' already exists. Please provide a different name. You can use "apify init" to create a local Actor environment inside an existing directory.`}),e=await Es(),c=It(a,e);continue}y||await od(c,{recursive:!0});break}let d=null;if(this.telemetryData.fromArchiveUrl=!!s,!s){let y=await _n(r,n);({archiveUrl:s,messages:d}=y),this.telemetryData.templateId=y.id,this.telemetryData.templateName=y.name,this.telemetryData.templateLanguage=y.category,"skipOptionalDeps"in y&&(i=y.skipOptionalDeps)}this.flags.omitOptionalDeps&&(i=!0),await dr({url:s,pathTo:c});let u=ve(It(c,M));await ar(Object.assign(u||er,{name:e}),c),await cr(c),await zr(c);let f=It(c,"package.json"),p=It(c,"README.md");await xn(p,n);let g=!1;o||await(await Ct({cwd:c})).inspectAsync(async b=>{let C=ad(we);if(!b.runtime){switch(b.type){case 0:{x({message:`No Node.js detected! Please install Node.js ${C} or higher to be able to run Node.js Actors locally.`});break}case 2:case 1:{x({message:`No Python detected! Please install Python ${Xe} or higher to be able to run Python Actors locally.`});break}default:}return}let{runtime:T}=b;switch(b.type){case 0:{ur(T.version)||x({message:`You are running Node.js version ${T.version}, which is no longer supported. Please upgrade to Node.js version ${C} or later.`}),await oi(f,{name:e});let I=["install"];if(i)switch(T.pmName){case"npm":{nd(T.pmVersion,"7.0.0")?I.push("--omit=optional"):I.push("--no-optional");break}case"bun":{I.push("--omit=optional");break}case"deno":{I.push("--node-modules-dir");break}default:}await fe({cmd:T.pmPath,args:I,opts:{cwd:c},overrideCommand:T.pmName}),g=!0;break}case 1:case 2:{if(!lr(T.version)){x({message:`Python Actors require Python 3.9 or higher, but you have Python ${T.version}!`}),x({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}let I=It(c,".venv");v({message:`Python version ${T.version} detected.`}),v({message:`Creating a virtual environment in "${I}" and installing dependencies from "requirements.txt"...`}),Wn.env.VIRTUAL_ENV||(await fe({cmd:T.executablePath,args:["-m","venv","--prompt",".",Qs],opts:{cwd:c}}),T=(await qt({cwd:c,force:!0})).unwrap(),b.runtime=T),await fe({cmd:T.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","--upgrade","pip","setuptools","wheel"],opts:{cwd:c}}),await fe({cmd:T.executablePath,args:["-m","pip","install","--no-cache-dir","--no-warn-script-location","-r","requirements.txt"],opts:{cwd:c}}),g=!0;break}default:}}),g?(R({message:`Actor '${e}' was created. To run it, run "cd ${e}" and "apify run".`}),v({message:'To run your code in the cloud, run "apify push" and deploy your code to Apify Console.'}),d?.postCreate&&v({message:d?.postCreate})):R({message:`Actor '${e}' was created. Please install its dependencies to be able to run it using "apify run".`})}};import Xn from"chalk";async function zn(t,e,r){let o=await t[r](e).get().catch(()=>{});if(o)return{[r]:o,[`${r}Client`]:t[r](o.id)};let s=await k(),i=await t[r](`${s.username}/${e}`).get().catch(()=>{});return i?{[r]:i,[`${r}Client`]:t[r](i.id)}:null}l(zn,"tryToGetStorage");async function Re(t,e){return zn(t,e,"dataset")}l(Re,"tryToGetDataset");async function Z(t,e){return zn(t,e,"keyValueStore")}l(Z,"tryToGetKeyValueStore");var Zr=class extends h{static name="create";static description="Creates a new dataset for storing structured data on your account.";static args={datasetName:w.string({description:"Optional name for the Dataset",required:!1})};static enableJsonFlag=!0;async run(){let{datasetName:e}=this.args,r=await S();if(e&&await Re(r,e)){m({message:"A Dataset with this name already exists!"});return}let o=await r.datasets().getOrCreate(e);if(this.flags.json){N(o);return}R({message:`Dataset with ID ${Xn.yellow(o.id)}${e?` (called ${Xn.yellow(e)})`:""} was created.`,stdout:!0})}};import{DownloadItemsFormat as He}from"apify-client";var Zn={[He.JSON]:"application/json",[He.JSONL]:"application/jsonl",[He.CSV]:"text/csv",[He.HTML]:"text/html",[He.RSS]:"application/rss+xml",[He.XML]:"application/xml",[He.XLSX]:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},Qr=class extends h{static name="get-items";static description="Retrieves dataset items in specified format (JSON, CSV, etc).";static flags={limit:A.integer({description:"The amount of elements to get from the dataset. By default, it will return all available items."}),offset:A.integer({description:"The offset in the dataset where to start getting items."}),format:A.string({description:"The format of the returned output. By default, it is set to 'json'",choices:Object.keys(Zn),default:He.JSON})};static args={datasetId:w.string({description:"The ID of the Dataset to export the items for",required:!0})};async run(){let{limit:e,offset:r,format:o}=this.flags,{datasetId:s}=this.args,i=await S(),n=await this.tryToGetDataset(i,s);if(!n){m({message:`Dataset with ID "${s}" not found.`});return}let{datasetClient:a}=n;process.stdout.write("");let c=await a.downloadItems(o,{limit:e,offset:r}),d=Zn[o]??"application/octet-stream";_({message:d}),process.stdout.write(c),process.stdout.write(`
109
+ `)}async tryToGetDataset(e,r){let o=await e.dataset(r).get().catch(()=>{});if(o)return{dataset:o,datasetClient:e.dataset(o.id)};let s=await k(),i=await e.dataset(`${s.username}/${r}`).get().catch(()=>{});return i?{dataset:i,datasetClient:e.dataset(i.id)}:null}};import U from"chalk";function eo(t){let e=Reflect.get(t,"planPricing");return e?Reflect.get(e,"chargeableServiceUnitPricesUsd"):null}l(eo,"getUserPlanPricing");var Qn=new V({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),to=class extends h{static name="info";static description="Prints information about a specific dataset.";static args={storeId:w.string({description:"The dataset store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,r=await S(),o=await Re(r,e);if(!o){m({message:`Key-value store with ID or name "${e}" not found.`});return}let{dataset:s}=o,[i,n,a]=await Promise.all([r.user(s.userId).get().then(P=>P),s.actId?r.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?r.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await r.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){N({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let d=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,p=(s.cleanItemCount||0).toLocaleString("en-US"),g=(s.itemCount||0).toLocaleString("en-US"),y=[`${U.bold(u.toLocaleString("en-US"))} ${U.gray(this.pluralString(u,"read","reads"))}`,`${U.bold(f.toLocaleString("en-US"))} ${U.gray(this.pluralString(f,"write","writes"))}`],b=`Items: ${U.bold(p)} ${U.gray("clean")} / ${U.bold(g)} ${U.gray("total")}
110
+ Operations: ${y.join(" / ")}`;if(i.plan){let P=eo(i.plan);if(P){let Q=P.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),he=Q*24*30,Le=he>1?`$${he.toFixed(2)}`:`$${Q.toFixed(3)}`;b+=`
111
+ Storage size: ${W({bytes:d,shortBytes:!0,precision:1})} / ${U.gray(`${Le} per month`)}`}}else b+=`
112
+ Storage size: ${W({bytes:d,shortBytes:!0,precision:1})}`;let C=[`Dataset ID: ${U.bgGray(s.id)}`,`Name: ${s.name?U.bgGray(s.name):U.bold(U.italic("Unnamed"))}`,`Created: ${U.bold(B.display(s.createdAt))}`,`Modified: ${U.bold(B.display(s.modifiedAt))}`].join(`
113
+ `),T=U.bold("\u2014");s.actRunId&&(a?T=U.bgBlue(a.id):T=U.italic(U.gray("Run removed")));let I=U.bold("\u2014");n&&(I=U.blue(n.title||n.name));let L=U.bold("\u2014");c&&(L=U.blue(c.title||c.name));let D=[`Run: ${T}`,`Actor: ${I}`,`Task: ${L}`].join(`
114
+ `);Qn.pushRow({Row1:C,Row2:D});let Y=Qn.render(2).split(`
115
+ `).map(P=>P.trim());Y.shift();let J=[`${U.bold(s.name||U.italic("Unnamed"))}`,`${U.gray(s.name?`${i.username}/${s.name}`:s.id)} ${U.gray("Owned by")} ${U.blue(i.username)}`,"",Y.join(`
116
+ `),"",b].join(`
117
+ `);_({message:J,stdout:!0})}};import ea from"chalk";var ta=new V({allColumns:["Dataset ID","Name","Items","Size","Created","Modified"],mandatoryColumns:["Dataset ID","Name","Items","Size"],columnAlignments:{Items:"right"}}),ro=class extends h{static name="ls";static description="Prints all datasets on your account.";static flags={offset:A.integer({description:"Number of datasets that will be skipped.",default:0}),limit:A.integer({description:"Number of datasets that will be listed.",default:20}),desc:A.boolean({description:"Sorts datasets in descending order.",default:!1}),unnamed:A.boolean({description:"Lists datasets that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:r,limit:o,json:s,unnamed:i}=this.flags,n=await S(),a=await k(),c=await n.datasets().list({desc:e,offset:r,limit:o,unnamed:i});if(s){N(c);return}if(c.count===0){v({message:"You don't have any Datasets on your account",stdout:!0});return}for(let d of c.items){let u=Reflect.get(d.stats,"s3StorageBytes");ta.pushRow({"Dataset ID":d.id,Created:B.display(d.createdAt),Items:`${d.itemCount}`,Modified:B.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof u=="number"?W({bytes:u,shortBytes:!0,colorFunc:ea.gray,precision:0}):ea.gray("N/A")})}_({message:ta.render(1),stdout:!0})}};import oo from"chalk";var so=class extends h{static name="push-items";static description="Adds data items to specified dataset. Accepts single object or array of objects.";static args={nameOrId:w.string({required:!0,description:"The dataset ID or name to push the objects to",ignoreStdin:!0}),item:w.string({description:"The object or array of objects to be pushed."})};async run(){let{nameOrId:e,item:r}=this.args,o=await S(),s=await Re(o,e);if(!s){m({message:`Dataset with ID or name "${e}" not found.`});return}let{datasetClient:i,dataset:n}=s,a,c=r||Ce;if(!c){m({message:"No items were provided."});return}try{a=JSON.parse(c.toString("utf8"))}catch(u){m({message:`Failed to parse data as JSON string: ${u.message}`});return}if(Array.isArray(a)&&a.length===0){m({message:"No items were provided."});return}let d=n.name?`Dataset named ${oo.yellow(n.name)} (${oo.gray("ID:")} ${oo.yellow(n.id)})`:`Dataset with ID ${oo.yellow(n.id)}`;try{await i.pushItems(a),R({message:`${this.pluralString(Array.isArray(a)?a.length:1,"Object","Objects")} pushed to ${d} successfully.`})}catch(u){let f=u;m({message:`Failed to push items into ${d}
118
+ ${f.message||f}`})}}};import Je from"chalk";var io=class extends h{static name="rename";static description="Change dataset name or removes name with --unname flag.";static flags={unname:A.boolean({description:"Removes the unique name of the dataset."})};static args={nameOrId:w.string({description:"The dataset ID or name to delete.",required:!0}),newName:w.string({description:"The new name for the dataset."})};async run(){let{unname:e}=this.flags,{newName:r,nameOrId:o}=this.args;if(!r&&!e){m({message:"You must provide either a new name or the --unname flag."});return}if(r&&e){m({message:"You cannot provide a new name and the --unname flag."});return}let s=await S(),i=await Re(s,o);if(!i){m({message:`Dataset with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.dataset,c=a?e?`The name of the dataset with ID ${Je.yellow(n)} has been removed (was ${Je.yellow(a)} previously).`:`The name of the dataset with ID ${Je.yellow(n)} was changed from ${Je.yellow(a)} to ${Je.yellow(r)}.`:`The name of the dataset with ID ${Je.yellow(n)} has been set to: ${Je.yellow(r)}`;try{await i.datasetClient.update({name:e?null:r}),R({message:c,stdout:!0})}catch(d){let u=d;m({message:`Failed to rename dataset with ID ${Je.yellow(n)}
119
+ ${u.message||u}`})}}};import Ns from"chalk";var no=class extends h{static name="rm";static description="Permanently removes a dataset.";static args={datasetNameOrId:w.string({description:"The dataset ID or name to delete",required:!0})};async run(){let{datasetNameOrId:e}=this.args,r=await S(),o=await Re(r,e);if(!o){m({message:`Dataset with ID or name "${e}" not found.`});return}if(!await H({message:"Are you sure you want to delete this Dataset?"})){v({message:"Dataset deletion has been aborted."});return}let{id:i,name:n}=o.dataset;try{await o.datasetClient.delete(),R({message:`Dataset with ID ${Ns.yellow(i)}${n?` (called ${Ns.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;m({message:`Failed to delete dataset with ID ${Ns.yellow(i)}
120
+ ${c.message||c}`})}}};var ao=class extends h{static name="datasets";static description="Manages structured data storage and retrieval.";static subcommands=[Zr,Qr,ro,to,no,io,so];async run(){this.printHelp()}};import{existsSync as Ls,mkdirSync as ud,readFileSync as dd,writeFileSync as md}from"fs";import{dirname as pd}from"path";import fd from"cors";import gd from"detect-indent";import Ds from"express";import hd from"open";import{cryptoRandomObjectId as yd}from"@apify/utilities";var oa="https://apify.github.io/input-schema-editor-react/",wd=new URL(oa).origin,ra="v1",co=class extends h{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 args={path:w.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:r}=await nt({forcePath:this.args.path,cwd:process.cwd()});if(e&&!r)throw new Error(`Editing an input schema directly embedded in '${M}' is not yet supported.`);x({message:`This command is still experimental and might break at any time. Use at your own risk.
121
+ `}),v({message:`Editing input schema at "${r}"...`});let o,s=Ds();s.use(fd({origin:wd,allowedHeaders:["Content-Type","Authorization"]})),s.use((f,p,g)=>{p.set("Connection","close"),g()}),s.use(Ds.json());let i=yd();s.use((f,p,g)=>{let{token:y}=f.query;if(!y){let b=f.get("Authorization");if(b){let[C,T,...I]=b.trim().split(/\s+/);C.toLowerCase()==="bearer"&&T&&I.length===0&&(y=T)}}y!==i?(p.status(401),p.send("Authorization failed")):g()});let n=Ds.Router();s.use(`/api/${ra}`,n);let a=" ",c=!0;n.get("/input-schema",(f,p)=>{let g;try{g=Ls(r)?dd(r,{encoding:"utf-8"}):`{}
122
+ `,g.length>3&&(a=gd(g).indent||a),g&&(c=g[g.length-1]===`
123
+ `),Ls(r)?v({message:`Input schema loaded from "${r}"`}):v({message:"Empty input schema initialized."})}catch(b){let C=`Reading input schema from disk failed with: ${b.message}`;m({message:C}),p.status(500),p.send(C);return}let y;try{y=JSON.parse(g||"{}")}catch(b){let C=`Parsing input schema failed with error: ${b.message}`;m({message:C}),p.status(500),p.send(C);return}p.send(y),v({message:"Input schema sent to editor."})}),n.post("/input-schema",(f,p)=>{try{v({message:"Got input schema from editor..."});let g=f.body,y=JSON.stringify(g,null,a);c&&(y+=`
124
+ `);let b=pd(r);Ls(b)||ud(b,{recursive:!0}),md(r,y,{encoding:"utf-8",flag:"w+"}),p.end(),v({message:"Input schema saved to disk."})}catch(g){let y=`Saving input schema failed with error: ${g.message}`;m({message:y}),p.status(500),p.send(y)}}),n.post("/exit",(f,p)=>{f.body.isWindowClosed?v({message:"Editor closed, finishing..."}):v({message:"Editing finished, you can close the editor."}),p.end(),o.close(()=>R({message:"Done."}))}),o=s.listen(0);let{port:d}=o.address();v({message:`Listening for messages from input schema editor on port ${d}...`});let u=`${oa}?localCliPort=${d}&localCliToken=${i}&localCliApiVersion=${ra}`;v({message:`Opening input schema editor at "${u}"...`}),await hd(u)}};import lo from"chalk";var Wt=class extends h{static name="help";static description="Prints out help about a command, or all available commands.";static hidden=!0;static args={commandString:w.string({required:!1,description:"The command to get help for.",catchAll:!0})};async run(){let{commandString:e}=this.args;if(!e||e.toLowerCase().startsWith("help")){let i=yr(this.entrypoint);console.log(i);return}let r=e.toLowerCase(),o=K.get(r);if(!o){let i=Mt(r),n=lo.gray(`Command ${lo.whiteBright(e)} not found`);i.length&&(n+=`
125
+ `,n+=lo.gray(`Did you mean: ${i.map(a=>lo.whiteBright(a)).join(", ")}?`)),m({message:n});return}let s=gr(o);console.log(s)}};import sa from"chalk";var uo=class extends h{static name="info";static description="Prints details about your currently authenticated Apify account.";async run(){await S();let e=await k();if(e){let r={username:e.username,userId:e.id};for(let o of Object.keys(r))console.log(`${sa.gray(o)}: ${sa.bold(r[o])}`)}}};import{basename as Ld}from"path";import Us from"process";import{appendFileSync as Ad,copyFileSync as bd,createWriteStream as Td,existsSync as Ps,mkdirSync as vd,readFileSync as ia,rmSync as Sd,writeFileSync as Cd}from"fs";import{basename as Id,join as ks,relative as na,sep as Fs}from"path";import{fileURLToPath as $d}from"url";import Ed from"@root/walk";import Rd from"configparser";import _d from"handlebars";import{fetchManifest as xd,wrapperManifestUrl as Od}from"@apify/actor-templates";var Nd=[".dockerignore",".gitignore"],mo=$d(new URL("./templates/python-scrapy",import.meta.url));async function aa(t,e,r={bindings:{}}){await Ed.walk(t,async(o,s,i)=>{if(s===t)return;let n=na(t,s),a=n.split(Fs).map(d=>{if(d.startsWith("{")&&d.endsWith("}")){d=d.replace("{","").replace("}","");let u=r.bindings[d];if(!u)throw new Error(`Binding for ${d} not found.`);return u}return d}).join(Fs),c=ks(e,a);if(i.isDirectory())return Ps(c)||vd(c),aa(s,c);n.includes(".template")?Cd(ks(e,a.replace(".template","")),_d.compile(ia(s,"utf8"))(r.bindings)):Ps(c)&&Nd.includes(Id(a))?Ad(c,ia(s)):bd(s,c)})}l(aa,"merge");async function po({projectPath:t}){t||(t=".");let e=new it(t);if(e.configuration.hasSection("apify"))throw new Error("The Scrapy project configuration already contains Apify settings. Are you sure you didn't already wrap this project?");await e.init();let r=await Ye({message:"Pick the Scrapy spider you want to wrap:",choices:e.getAvailableSpiders().map((d,u)=>({name:`${d.class_name} (${d.pathname})`,value:u}))});function o(d){return`.${na(t,d).split(Fs).slice(1).join(".").replace(".py","")}`}l(o,"translatePathToRelativeModuleName");let s={botName:vi(e.settings.BOT_NAME),scrapy_settings_module:e.configuration.get("settings","default"),apify_module_path:`${e.settings.BOT_NAME}.apify`,spider_class_name:e.getAvailableSpiders()[r].class_name,spider_module_name:`${o(e.getAvailableSpiders()[r].pathname)}`,projectFolder:e.settings.BOT_NAME},i=await xd(Od);v({message:"Downloading the latest Scrapy wrapper template..."});let{archiveUrl:n}=i.templates.find(({id:d})=>d==="python-scrapy");Ps(mo)&&Sd(mo,{recursive:!0}),await dr({url:n,pathTo:mo}),v({message:"Wrapping the Scrapy project..."}),await aa(mo,t,{bindings:s});let a=new Rd;a.addSection("apify"),a.set("apify","mainpy_location",e.settings.BOT_NAME);let c=Td(ks(t,"scrapy.cfg"),{flags:"a"});await new Promise(d=>{c.on("open",u=>{c.write(`
126
+ `,()=>{a.write(u),d()})})}),R({message:"The Scrapy project has been wrapped successfully."})}l(po,"wrapScrapyProject");var fo=class extends h{static name="init";static description=`Sets up an Actor project in your current directory by creating actor.json and storage files.
127
+ If the directory contains a Scrapy project in Python, the command automatically creates wrappers so that you can run your scrapers without changes.
128
+ Creates the '${M}' file and the '${ze}' directory in the current directory, but does not touch any other existing files or directories.
129
+
130
+ WARNING: Overwrites existing '${ze}' directory.`;static args={actorName:w.string({required:!1,description:"Name of the Actor. If not provided, you will be prompted for it."})};static flags={yes:A.boolean({char:"y",description:'Automatic yes to prompts; assume "yes" as answer to all prompts. Note that in some cases, the command may still ask for confirmation.',required:!1})};async run(){let{actorName:e}=this.args,r=Us.cwd(),o=await Ct();o.isErr()&&(m({message:o.unwrapErr().message}),Us.exit(1));let s=o.unwrap();if(s.type===2)return v({message:"The current directory looks like a Scrapy project. Using automatic project wrapping."}),this.telemetryData.actorWrapper=zs.SCRAPY,po({projectPath:r});if(!this.flags.yes&&s.type===3&&(x({message:"The current directory does not look like a Node.js or Python project."}),!await H({message:"Do you want to continue?",providedConfirmFromStdin:this.flags.yes})))return;let i=await Me({cwd:r});if(i.isOkAnd(n=>n.exists&&!n.migrated))x({message:`Skipping creation of '${M}', the file already exists in the current directory.`});else{if(i.isErr()){m({message:i.unwrapErr().message}),Us.exitCode=5;return}if(!e){let a=i.isOkAnd(c=>c.exists)?i.unwrap().config.name:null;for(;!a;)try{let c=await st({message:"Actor name:",default:Ld(r)});Dt(c),a=c}catch(c){m({message:c.message})}e=a}let n={...er,...i.unwrap().config};await ar(Object.assign(n,{name:e}),r)}await cr(r),await zr(r),R({message:"The Actor has been initialized in the current directory."})}};var go=class extends h{static name="init-wrap-scrapy";static description=`Wraps your existing Scrapy project to work like an Apify Actor.
131
+
132
+ It adds the following features:
133
+ - Automatic retry of failed requests
134
+ - Automatic proxy rotation
135
+ - Automatic user agent rotation
136
+ ...
137
+ `;static args={path:w.string({required:!1,description:"Optional path to your scrapy project. If not provided, the current directory is used."})};static hidden=!0;async run(){await po({projectPath:this.args.path}),v({message:"Scrapy project wrapped successfully."})}};import ca from"chalk";var ho=class extends h{static name="create";static description="Creates a new key-value store on your account.";static args={"key-value store name":w.string({description:"Optional name for the key-value store",required:!1})};static enableJsonFlag=!0;async run(){let{keyValueStoreName:e}=this.args,r=await S();if(e&&await Z(r,e)){m({message:"Cannot create a key-value store with the same name!"});return}let o=await r.keyValueStores().getOrCreate(e);if(this.flags.json){N(o);return}R({message:`Key-value store with ID ${ca.yellow(o.id)}${e?` (called ${ca.yellow(e)})`:""} was created.`,stdout:!0})}};import Dd from"chalk";var yo=class extends h{static name="delete-value";static description="Delete a value from a key-value store.";static args={"store id":w.string({description:"The key-value store ID to delete the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{storeId:e,itemKey:r}=this.args,o=await S(),s=await Z(o,e);if(!s){m({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:i}=s;if(!await i.getRecord(r)){m({message:`Item with key "${r}" not found in the key-value store.`});return}if(!await H({message:"Are you sure you want to delete this record?"})){v({message:"Key-value store record deletion aborted.",stdout:!0});return}try{await i.deleteRecord(r),v({message:`Record with key "${Dd.yellow(r)}" deleted from the key-value store.`,stdout:!0})}catch(c){let d=c;m({message:`Failed to delete record with key "${r}" from the key-value store.
138
+ ${d.message||d}`})}}};var wo=class extends h{static name="get-value";static description="Retrieves stored value for specified key. Use --only-content-type to check MIME type.";static flags={"only-content-type":A.boolean({description:"Only return the content type of the specified key",default:!1})};static args={keyValueStoreId:w.string({description:"The key-value store ID to get the value from.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0})};async run(){let{onlyContentType:e}=this.flags,{keyValueStoreId:r,itemKey:o}=this.args,s=await S(),i=await Z(s,r);if(!i){m({message:`Key-value store with ID "${r}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.getRecord(o,{stream:!0});if(!a){m({message:`Item with key "${o}" not found in the key-value store.`});return}if(_({message:a.contentType??"application/octet-stream"}),e){a.value.destroy();return}if(a.contentType?.includes("application/json")){let{value:c}=a,d=[];for await(let f of c)d.push(f);let u=Buffer.concat(d).toString();try{let f=JSON.parse(u);_({message:JSON.stringify(f,null,2),stdout:!0})}catch{_({message:u,stdout:!0})}return}a.value.pipe(process.stdout)}};import F from"chalk";var la=new V({allColumns:["Row1","Row2"],mandatoryColumns:["Row1","Row2"]}),Ao=class extends h{static name="info";static description="Shows information about a key-value store.";static args={storeId:w.string({description:"The key-value store ID to print information about.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,r=await S(),o=await Z(r,e);if(!o){m({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStore:s}=o,[i,n,a]=await Promise.all([r.user(s.userId).get().then(P=>P),s.actId?r.actor(s.actId).get():Promise.resolve(void 0),s.actRunId?r.run(s.actRunId).get():Promise.resolve(void 0)]),c;if(a?.actorTaskId&&(c=await r.task(a.actorTaskId).get().catch(()=>{})),this.flags.json){N({...s,user:i,actor:n||null,run:a||null,task:c||null});return}let d=s.stats?.storageBytes||0,u=s.stats?.readCount||0,f=s.stats?.writeCount||0,p=s.stats?.deleteCount||0,g=s.stats?.listCount||0,b=`Operations: ${[`${F.bold(u.toLocaleString("en-US"))} ${F.gray(this.pluralString(u,"read","reads"))}`,`${F.bold(f.toLocaleString("en-US"))} ${F.gray(this.pluralString(f,"write","writes"))}`,`${F.bold(p.toLocaleString("en-US"))} ${F.gray(this.pluralString(p,"delete","deletes"))}`,`${F.bold(g.toLocaleString("en-US"))} ${F.gray(this.pluralString(g,"list","lists"))}`].join(" / ")}`;if(i.plan){let P=eo(i.plan);if(P){let Q=P.KEY_VALUE_STORE_TIMED_STORAGE_GBYTE_HOURS*(d/1e9),he=Q*24*30,Le=he>1?`$${he.toFixed(2)}`:`$${Q.toFixed(3)}`;b+=`
139
+ Storage size: ${W({bytes:d,shortBytes:!0,precision:1})} / ${F.gray(`${Le} per month`)}`}}else b+=`
140
+ Storage size: ${W({bytes:d,shortBytes:!0,precision:1})} / ${F.gray("$unknown per month")}`;let C=[`Store ID: ${F.bgGray(s.id)}`,`Name: ${s.name?F.bgGray(s.name):F.bold(F.italic("Unnamed"))}`,`Created: ${F.bold(B.display(s.createdAt))}`,`Modified: ${F.bold(B.display(s.modifiedAt))}`].join(`
141
+ `),T=F.bold("\u2014");s.actRunId&&(a?T=F.bgBlue(a.id):T=F.italic(F.gray("Run removed")));let I=F.bold("\u2014");n&&(I=F.blue(n.title||n.name));let L=F.bold("\u2014");c&&(L=F.blue(c.title||c.name));let D=[`Run: ${T}`,`Actor: ${I}`,`Task: ${L}`].join(`
142
+ `);la.pushRow({Row1:C,Row2:D});let Y=la.render(2).split(`
143
+ `).map(P=>P.trim());Y.shift();let J=[`${F.bold(s.name||F.italic("Unnamed"))}`,`${F.gray(s.name?`${i.username}/${s.name}`:s.id)} ${F.gray("Owned by")} ${F.blue(i.username)}`,"",Y.join(`
144
+ `),"",b].join(`
145
+ `);_({message:J,stdout:!0})}};var ua=new V({allColumns:["Key","Size"],mandatoryColumns:["Key","Size"]}),bo=class extends h{static name="keys";static description="Lists all keys in a key-value store.";static flags={limit:A.integer({description:"The maximum number of keys to return.",default:20}),"exclusive-start-key":A.string({description:"The key to start the list from."})};static args={storeId:w.string({description:"The key-value store ID to list keys for.",required:!0})};static enableJsonFlag=!0;async run(){let{storeId:e}=this.args,{limit:r,exclusiveStartKey:o}=this.flags,s=await S(),i=await Z(s,e);if(!i){m({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:n}=i,a=await n.listKeys({limit:r,exclusiveStartKey:o});if(this.flags.json){N(a);return}for(let c of a.items)ua.pushRow({Key:c.key,Size:W({bytes:c.size,shortBytes:!0,precision:0})});_({message:ua.render(1),stdout:!0})}};import da from"chalk";var ma=new V({allColumns:["Store ID","Name","Size","Created","Modified"],mandatoryColumns:["Store ID","Name","Size"]}),To=class extends h{static name="ls";static description="Lists all key-value stores on your account.";static flags={offset:A.integer({description:"Number of key-value stores that will be skipped.",default:0}),limit:A.integer({description:"Number of key-value stores that will be listed.",default:20}),desc:A.boolean({description:"Sorts key-value stores in descending order.",default:!1}),unnamed:A.boolean({description:"Lists key-value stores that don't have a name set.",default:!1})};static enableJsonFlag=!0;async run(){let{desc:e,offset:r,limit:o,json:s,unnamed:i}=this.flags,n=await S(),a=await k(),c=await n.keyValueStores().list({desc:e,offset:r,limit:o,unnamed:i});if(s){N(c);return}if(c.count===0){v({message:"You don't have any key-value stores on your account",stdout:!0});return}for(let d of c.items){let f=Reflect.get(d,"stats").s3StorageBytes;ma.pushRow({"Store ID":d.id,Created:B.display(d.createdAt),Modified:B.display(d.modifiedAt),Name:d.name?`${a.username}/${d.name}`:"",Size:typeof f=="number"?W({bytes:f,shortBytes:!0,colorFunc:da.gray,precision:0}):da.gray("N/A")})}_({message:ma.render(1),stdout:!0})}};import Ke from"chalk";var vo=class extends h{static name="rename";static description="Renames a key-value store, or removes its unique name.";static flags={unname:A.boolean({description:"Removes the unique name of the key-value store"})};static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0}),newName:w.string({description:"The new name for the key-value store"})};async run(){let{unname:e}=this.flags,{newName:r,keyValueStoreNameOrId:o}=this.args;if(!r&&!e){m({message:"You must provide either a new name or the --unname flag."});return}if(r&&e){m({message:"You cannot provide a new name and the --unname flag."});return}let s=await S(),i=await Z(s,o);if(!i){m({message:`Key-value store with ID or name "${o}" not found.`});return}let{id:n,name:a}=i.keyValueStore,c=a?e?`The name of the key-value store with ID ${Ke.yellow(n)} has been removed (was ${Ke.yellow(a)} previously).`:`The name of the key-value store with ID ${Ke.yellow(n)} was changed from ${Ke.yellow(a)} to ${Ke.yellow(r)}.`:`The name of the key-value store with ID ${Ke.yellow(n)} has been set to: ${Ke.yellow(r)}`;try{await i.keyValueStoreClient.update({name:e?null:r}),R({message:c,stdout:!0})}catch(d){let u=d;m({message:`Failed to rename key-value store with ID ${Ke.yellow(n)}
146
+ ${u.message||u}`})}}};import js from"chalk";var So=class extends h{static name="rm";static description="Permanently removes a key-value store.";static args={keyValueStoreNameOrId:w.string({description:"The key-value store ID or name to delete",required:!0})};async run(){let{keyValueStoreNameOrId:e}=this.args,r=await S(),o=await Z(r,e);if(!o){m({message:`Key-value store with ID or name "${e}" not found.`});return}if(!await H({message:"Are you sure you want to delete this Key-value store?"})){v({message:"Key-value store deletion has been aborted."});return}let{id:i,name:n}=o.keyValueStore;try{await o.keyValueStoreClient.delete(),R({message:`Key-value store with ID ${js.yellow(i)}${n?` (called ${js.yellow(n)})`:""} has been deleted.`,stdout:!0})}catch(a){let c=a;m({message:`Failed to delete key-value store with ID ${js.yellow(i)}
147
+ ${c.message||c}`})}}};var Co=class extends h{static name="set-value";static description="Stores value with specified key. Set content-type with --content-type flag.";static flags={"content-type":A.string({description:'The MIME content type of the value. By default, "application/json" is assumed.',default:"application/json"})};static args={storeId:w.string({description:"The key-value store ID to set the value in.",required:!0}),itemKey:w.string({description:"The key of the item in the key-value store.",required:!0}),value:w.string({description:"The value to set."})};async run(){let{storeId:e,itemKey:r,value:o}=this.args,{contentType:s}=this.flags,i=await S(),n=await Z(i,e);if(!n){m({message:`Key-value store with ID or name "${e}" not found.`});return}let{keyValueStoreClient:a}=n;try{await a.setRecord({key:r,value:o||process.stdin,contentType:s}),R({message:`Value with key "${r}" set in the key-value store.`,stdout:!0})}catch(c){let d=c;m({message:`Failed to set value with key "${r}" in the key-value store.
148
+ ${d.message||d}`})}}};var Io=class extends h{static name="key-value-stores";static description=`Manages persistent key-value storage.
149
+
150
+ Alias: kvs`;static hiddenAliases=["kvs"];static subcommands=[ho,yo,wo,Ao,bo,To,vo,So,Co];async run(){this.printHelp()}};import Yd from"chalk";import Gd from"computer-name";import Hd from"cors";import Bs from"express";import Jd from"open";import{cryptoRandomObjectId as Kd}from"@apify/utilities";import Pd from"@inquirer/password";var pa=Ee(async({message:t,mask:e})=>await Pd({message:t,mask:e}));import{readFileSync as kd,writeFileSync as Ms}from"fs";import{promisify as Fd}from"util";import Ud from"mixpanel";import{cryptoRandomObjectId as jd}from"@apify/utilities";var fa=Ud.init(ei,{keepAlive:!1}),Md='Apify collects telemetry data about general usage of Apify CLI to help us improve the product. This feature is enabled by default, and you can disable it by setting the "APIFY_CLI_DISABLE_TELEMETRY" environment variable to "1". You can find more information about our telemetry in https://docs.apify.com/cli/docs/telemetry.',Bd=Fd(fa.track.bind(fa)),ga=l(()=>`CLI:${jd()}`,"createLocalDistinctId"),ha=l(async()=>{try{return JSON.parse(kd(De(),"utf-8")).distinctId}catch{let e=(await k()).id||ga();return v({message:Md}),Qe(De()),Ms(De(),JSON.stringify({distinctId:e},null," ")),e}},"getOrCreateLocalDistinctId"),ya=l(()=>{try{Qe(De()),Ms(De(),JSON.stringify({distinctId:ga()},null," "))}catch{}},"regenerateLocalDistinctId"),wa=!process.env.APIFY_CLI_DISABLE_TELEMETRY||["false","0"].includes(process.env.APIFY_CLI_DISABLE_TELEMETRY),Vd=l(async({eventName:t,eventData:e})=>{if(wa)try{let r=ha();await Bd(t,{distinct_id:r,app:"cli",...e})}catch{}},"maybeTrackTelemetry"),Aa=l(async t=>{if(wa)try{let e=ha();Qe(De()),Ms(De(),JSON.stringify({distinctId:t},null," ")),await Vd({eventName:"$create_alias",eventData:{alias:e}})}catch{}},"useApifyIdentity");var Ys="https://console.apify.com/settings/integrations",qd=new URL(Ys).origin,Wd=Ys.includes("localhost")?"http://localhost:3333":void 0,ba="v1",Vs=l(async t=>{let e=await Nt(t,Wd),r=await k();return e?(await Aa(r.id),R({message:`You are logged in to Apify as ${r.username||r.id}. ${Yd.gray(`Your token is stored at ${se()}.`)}`})):m({message:"Login to Apify failed, the provided API token is not valid."}),e},"tryToLogin"),$o=class extends h{static name="login";static description=`Authenticates your Apify account and saves credentials to '${se()}'.
151
+ All other commands use these stored credentials.
152
+
153
+ Run 'apify logout' to remove authentication.`;static flags={token:A.string({char:"t",description:"[Optional] Apify API token",required:!1}),method:A.string({char:"m",description:"[Optional] Method of logging in to Apify",choices:["console","manual"],required:!1})};async run(){let{token:e,method:r}=this.flags;if(e){await Vs(e);return}let o=r;if(r||(o=await Ye({message:"Choose how you want to log in to Apify",choices:[{value:"console",name:"Through Apify Console in your default browser",short:"Through Apify Console"},{value:"manual",name:"Enter API token manually",short:"Manually"}],loop:!0})),o==="console"){let s,i=Bs();i.use(Hd({origin:qd,allowedHeaders:["Content-Type","Authorization"]})),i.use((u,f,p)=>{f.set("Connection","close"),p()}),i.use(Bs.json());let n=Kd();i.use((u,f,p)=>{let{token:g}=u.query;if(!g){let y=u.get("Authorization");if(y){let[b,C,...T]=y.trim().split(/\s+/);b.toLowerCase()==="bearer"&&C&&T.length===0&&(g=C)}}g!==n?(f.status(401),f.send("Authorization failed")):p()});let a=Bs.Router();i.use(`/api/${ba}`,a),a.post("/login-token",async(u,f)=>{try{if(u.body.apiToken)await Vs(u.body.apiToken);else throw new Error("Request did not contain API token");f.end()}catch(p){let g=`Login to Apify failed with error: ${p.message}`;m({message:g}),f.status(500),f.send(g)}s.close()}),a.post("/exit",(u,f)=>{u.body.isWindowClosed?m({message:"Login to Apify failed, the console window was closed."}):u.body.actionCanceled?m({message:"Login to Apify failed, the action was canceled in the Apify Console."}):m({message:"Login to Apify failed."}),f.end(),s.close()}),s=i.listen(0);let{port:c}=s.address(),d=new URL(Ys);d.searchParams.set("localCliCommand","login"),d.searchParams.set("localCliPort",`${c}`),d.searchParams.set("localCliToken",n),d.searchParams.set("localCliApiVersion",ba);try{d.searchParams.set("localCliComputerName",encodeURIComponent(Gd()))}catch{}v({message:`Opening Apify Console at "${d.href}"...`}),await Jd(d.href)}else{console.log("Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations");let s=await pa({message:"token:"});await Vs(s)}}};var Eo=class extends h{static name="logout";static description=`Removes authentication by deleting your API token and account information from '${se()}'.
154
+ Run 'apify login' to authenticate again.`;async run(){await Et(se()),ya(),R({message:"You are logged out from your Apify account."})}};var Ro=class extends vt{static name="pull"};var _o=class extends St{static name="push"};var xo=class extends h{static name="request-queues";static description="Manages URL queues for web scraping and automation tasks.";async run(){this.printHelp()}};import{existsSync as va,renameSync as em}from"fs";import{mkdir as Oo,readFile as tm,stat as Sa,writeFile as Xt}from"fs/promises";import{dirname as No,join as Lo}from"path";import Ne from"process";import rm from"mime";import{minVersion as om}from"semver";import{APIFY_ENV_VARS as Do}from"@apify/consts";import{validateInputSchema as sm,validateInputUsingValidator as Ca}from"@apify/input_schema";import{none as zt,some as zd}from"@sapphire/result";import{execa as Xd}from"execa";var Gs=l(t=>`
155
+ (async () => {
156
+ const [nodeModule, process, path, fs] = await Promise.all([
157
+ import('node:module'),
158
+ import('node:process'),
159
+ import('node:path'),
160
+ import('node:fs/promises'),
161
+ ]);
162
+
163
+ /* we fake a script file here because otherwise node AND deno will fail to resolve modules, but bun works -.- */
164
+ const dirname = path.join(process.cwd(), '__apify_cli_fetch_module_version__.js');
165
+
166
+ const _require = nodeModule.createRequire(dirname);
167
+
168
+ try {
169
+ const modulePath = _require.resolve('${t}');
170
+ const moduleDir = path.dirname(modulePath);
171
+
172
+ const packageJson = await fs.readFile(path.join(moduleDir, 'package.json'), 'utf8').catch(() => null);
173
+
174
+ if (!packageJson) {
175
+ console.log('n/a');
176
+ return;
177
+ }
178
+
179
+ const packageJsonObj = JSON.parse(packageJson);
180
+ console.log(packageJsonObj.version);
181
+ } catch {
182
+ console.log('n/a');
183
+ }
184
+ })();
185
+ `.replaceAll(`
186
+ `," ").replaceAll(" "," "),"jsScript"),Zd=l(t=>`
187
+ try:
188
+ import ${t}
189
+ print(${t}.__version__)
190
+ except:
191
+ print('n/a')
192
+ `,"pyScript"),Qd={node(t){return["-e",`"${Gs(t)}"`]},deno(t){return["eval",`"${Gs(t)}"`]},bun(t){return["--eval",`"${Gs(t)}"`]},python(t){return["-c",`"${Zd(t)}"`]}};async function Ta({moduleName:t,project:e}){if(!e.runtime)return $("useModuleVersion",{status:"no_runtime_found",project:e,moduleName:t}),zt;let r;if(e.type===0)r=e.runtime.runtimeShorthand||"node";else if(e.type===1||e.type===2)r="python";else return $("useModuleVersion",{status:"unsupported_project_type",project:e,moduleName:t}),zt;let o=Qd[r]?.(t);if(!o)return $("useModuleVersion",{status:"no_version_script_found",project:e,moduleName:t}),zt;try{let s=await Xd(e.runtime.executablePath,o,{shell:!0,windowsHide:!0,verbose:process.env.APIFY_CLI_DEBUG?"full":void 0});return s.stdout.trim()==="n/a"?($("useModuleVersion",{status:"no_version_found",project:e,moduleName:t}),zt):($("useModuleVersion",{status:"success",project:e,moduleName:t,version:s.stdout.trim()}),zd(s.stdout.trim()))}catch(s){return $("useModuleVersion",{status:"failed_to_run_version_script",project:e,moduleName:t,error:s}),zt}}l(Ta,"useModuleVersion");var Po=class extends h{static name="run";static description=`Executes Actor locally with simulated Apify environment variables.
193
+ Stores data in local '${ze}' directory.
194
+
195
+ NOTE: For Node.js Actors, customize behavior by modifying the 'start' script in package.json file.`;static flags={purge:A.boolean({char:"p",description:"Whether to purge the default request queue, dataset and key-value store before the run starts.\nFor crawlee projects, this is the default behavior, and the flag is optional.\nUse `--no-purge` to keep the storage folder intact.",required:!1,default:!0,exclusive:["resurrect"]}),resurrect:A.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:A.string({description:["Optional entrypoint for running with injected environment variables.",`
196
+ `,"For Python, it is the module name, or a path to a file.",`
197
+ `,"For Node.js, it is the npm script name, or a path to a JS/MJS file.",'You can also pass in a directory name, provided that directory contains an "index.js" file.'].join(" "),required:!1}),input:A.string({char:"i",description:"Optional JSON input to be given to the Actor.",required:!1,stdin:2,exclusive:["input-file"]}),"input-file":A.string({aliases:["if"],description:"Optional path to a file with JSON input to be given to the Actor. The file must be a valid JSON file. You can also specify `-` to read from standard input.",required:!1,stdin:2,exclusive:["input"]})};async run(){let e=Ne.cwd(),{proxy:r,id:o,token:s}=await k(),i=await Me({cwd:e});if(i.isErr()){let{message:j,cause:Y}=i.unwrapErr();m({message:`${j}${Y?`
198
+ ${Y.message}`:""}`}),Ne.exitCode=5;return}let{config:n}=i.unwrap(),a=ae(),c=await Ct({cwd:e});if(c.isErr()){m({message:c.unwrapErr().message}),Ne.exitCode=5;return}let d=c.unwrap(),{type:u,entrypoint:f,runtime:p}=d;if(u===3)throw new Error("Actor is of an unknown format. Make sure your project is supported by Apify CLI (either a package.json file is present, or a Python entrypoint could be found) or you are in a migrated Scrapy project.");if(!p){switch(u){case 0:m({message:`No Node.js detected! Please install Node.js ${we} (or higher) to be able to run Node.js Actors locally.`});break;case 2:case 1:m({message:`No Python detected! Please install Python ${Xe} (or higher) to be able to run Python Actors locally.`});break;default:m({message:`No runtime detected! Make sure you have Python ${Xe} (or higher) or Node.js ${we} (or higher) installed.`})}return}let g,y;if(this.flags.entrypoint){y=this.flags.entrypoint;let j=Lo(e,this.flags.entrypoint),Y=await Sa(j).catch(()=>null);Y?.isDirectory()?g=1:Y?.isFile()?g=0:g=2}else if(f?.script)g=2,y=f.script;else if(f?.path)g=u!==0?1:0,y=f.path;else{m({message:"No entrypoint detected! Please provide an entrypoint using the --entrypoint flag, or make sure your project has an entrypoint."});return}va(Qo)&&!va(a)&&(em(Qo,a),x({message:`The legacy 'apify_storage' directory was renamed to '${a}' to align it with Apify SDK v3. Contents were left intact.`}));let b=await Ta({moduleName:"crawlee",project:d}),C="0";this.flags.resurrect&&(this.flags.purge=!1),this.flags.purge&&(C="1",b.isNone()&&(await Promise.all([wi(),bi(),Ai()]),v({message:"All default local stores were purged."}))),this.flags.purge||!await Ti()&&!this.flags.resurrect&&x({message:"The storage directory contains a previous state, the Actor will continue where it left off. To start from the initial state, use --purge parameter to clean the storage directory."});let T=await At(e,this.flags.input,this.flags.inputFile);if(T===!1)return;let I=await this.validateAndStoreInput(T),L={[Do.LOCAL_STORAGE_DIR]:a,CRAWLEE_STORAGE_DIR:a,CRAWLEE_PURGE_ON_START:C};if(r&&r.password&&(L[Do.PROXY_PASSWORD]=r.password),o&&(L[Do.USER_ID]=o),s&&(L[Do.TOKEN]=s),n.environmentVariables){let j=fn(n.environmentVariables);Object.assign(L,j)}let D=Object.assign(L,Ne.env);o||x({message:'You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.'});try{switch(u){case 0:{let j=om(we);if(ur(p.version)?D.NODE_OPTIONS=D.NODE_OPTIONS?`${D.NODE_OPTIONS} --max-http-header-size=80000`:"--max-http-header-size=80000":x({message:`You are running Node.js version ${p.version}, which is no longer supported. Please upgrade to Node.js version ${j} or later.`}),g===0||g===1)await fe({cmd:p.executablePath,args:[y],opts:{env:D,cwd:e}});else{let Y=await tm(Lo(e,"package.json"),"utf8").catch(()=>"{}"),J=JSON.parse(Y);if(!J.scripts)throw new Error('No scripts were found in package.json. Please set it up for your project. For more information about that call "apify help run".');if(!J.scripts[y])throw new Error(`The script "${y}" was not found in package.json. Please set it up for your project. For more information about that call "apify help run".`);if(!p.pmPath)throw new Error("No npm executable found! Please make sure your Node.js runtime has npm installed if you want to run package.json scripts locally.");await fe({cmd:p.pmPath,args:["run",y],opts:{env:D,cwd:e},overrideCommand:p.pmName})}break}case 1:case 2:{if(!lr(p.version)){m({message:`Python Actors require Python 3.9 or higher, but you have Python ${p.version}!`}),m({message:"Please install Python 3.9 or higher to be able to run Python Actors locally."});return}g===1?await fe({cmd:p.executablePath,args:["-m",y],opts:{env:D,cwd:e}}):await fe({cmd:p.executablePath,args:[y],opts:{env:D,cwd:e}});break}default:m({message:"Failed to detect the language of your project. Please report this issue to the Apify team with your project structure over at https://github.com/apify/apify-cli/issues"})}}catch(j){let{stderr:Y}=j}finally{if(I)if(I.existingInput){let j=await Sa(I.inputFilePath);if(Math.trunc(j.mtimeMs)-I.writtenAt>=5){x({message:`The "${I.inputFilePath}" file was overwritten during the run. The CLI will not undo the setting of missing default fields from your input schema.`});return}await Xt(I.inputFilePath,I.existingInput.body)}else await Rt(I.inputFilePath)}}async validateAndStoreInput(e){let{inputSchema:r}=await nt({cwd:Ne.cwd()});if(!r){if(!e)return null;let d=Lt(Ne.cwd()),u=Lo(Ne.cwd(),Te(),d?.fileName??"INPUT.json");return await Oo(No(u),{recursive:!0}),await Xt(u,JSON.stringify(e.input,null,2)),{existingInput:d,inputFilePath:u,writtenAt:Date.now()}}let o=new lt({strict:!1,unicodeRegExp:!1});sm(o,r);let s=Kn(r),i=qn(r,o),n=Lt(Ne.cwd()),a=Lo(Ne.cwd(),Te(),n?.fileName??"INPUT.json"),c;switch(e?.source){case"stdin":c=`The input provided through standard input is invalid. Please fix the following errors:
199
+ `;break;case"input":c=`The input provided through the --input flag is invalid. Please fix the following errors:
200
+ `;break;default:e?c=`The input provided through the ${e.source} file is invalid. Please fix the following errors:
201
+ `:c=`The input in your storage is invalid. Please fix the following errors:
202
+ `;break}if(e){let d={...s,...e.input},u=Ca(i,r,d);if(u.length>0)throw new Error(`${c}${u.map(f=>` - ${f.message.replace("Field input.","Field ")}`).join(`
203
+ `)}`);return await Oo(No(a),{recursive:!0}),await Xt(a,JSON.stringify(d,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}if(!n)return await Oo(No(a),{recursive:!0}),await Xt(a,JSON.stringify(s,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()};if(rm.getExtension(n.contentType)==="json"){let d=JSON.parse(n.body.toString("utf-8"));if(Array.isArray(d))throw new Error("The input in your storage is invalid. It should be an object, not an array.");let u={...s,...d},f=Ca(i,r,u);if(f.length>0)throw new Error(`${c}${f.map(p=>` - ${p.message.replace("Field input.","Field ")}`).join(`
204
+ `)}`);return await Oo(No(a),{recursive:!0}),await Xt(a,JSON.stringify(u,null,2)),{existingInput:n,inputFilePath:a,writtenAt:Date.now()}}return null}};import{ACTOR_JOB_STATUSES as ko}from"@apify/consts";var im=[ko.READY,ko.RUNNING],nm=[ko.ABORTING,ko.TIMING_OUT],Fo=class extends h{static name="abort";static description="Aborts an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to abort."})};static flags={force:A.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,r=await S(),o=await r.run(e).get();if(!o){m({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!im.includes(o.status)){nm.includes(o.status)?m({message:`Run with ID "${e}" is already aborting.`,stdout:!0}):m({message:`Run with ID "${e}" is already aborted.`,stdout:!0});return}try{let s=await r.run(e).abort({gracefully:!this.flags.force});if(this.flags.json){N(s);return}this.flags.force?R({message:`Triggered the immediate abort of run "${e}".`,stdout:!0}):R({message:`Triggered the abort of run "${e}", it should finish aborting in up to 30 seconds.`,stdout:!0})}catch(s){let i=s;m({message:`Failed to abort run "${e}".
205
+ ${i.message||i}`,stdout:!0})}}};import E from"chalk";var Zt=new V({allColumns:["","Unit","USD Amount"],mandatoryColumns:["","Unit","USD Amount"],columnAlignments:{Unit:"right","USD Amount":"right"}}),Ia={"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"},Uo=class extends h{static name="info";static description="Prints information about an Actor run.";static args={runId:w.string({required:!0,description:"The run ID to print information about."})};static flags={verbose:A.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,r=await S(),o=await r.run(e).get();if(!o){m({message:`Run with ID "${e}" was not found on your account.`});return}let[s,i,n,a,c]=await Promise.all([r.actor(o.actId).get(),r.build(o.buildId).get(),o.actorTaskId?r.task(o.actorTaskId).get():Promise.resolve(void 0),r.dataset(o.defaultDatasetId).get(),r.requestQueue(o.defaultRequestQueueId).get()]);if(this.flags.json){N({...o,actor:s,build:i,task:n,defaultDataset:a,defaultRequestQueue:c});return}this.addDetailedUsage(o);let d=s?.username?`${s.username}/${s.name}`:s?.name??"unknown-actor",u=[`${E.yellow("Actor")}: ${d} (${E.grey(o.actId)})`];n?u.push(`\u2514\u2500 ${E.yellow("Task")}: ${n.title??n.name} (${E.gray(o.actorTaskId)})`,""):o.actorTaskId?u.push(`\u2514\u2500 ${E.yellow("Task")}: unknown-task (${E.gray(o.actorTaskId)})`,""):u.push("");let f=` (exit code: ${E.gray(o.exitCode!==null?o.exitCode:"N/A")})`;u.push(`${E.yellow("Status")}: ${be(o.status)}${f}`),o.statusMessage&&u.push(`\u2514\u2500 ${E.yellow("Status Message:")} ${o.statusMessage}`);let p=a?.itemCount??0;u.push(`${E.yellow("Results")}: ${E.cyan(p.toLocaleString("en-US"))}`),c?u.push(`${E.yellow("Requests")}: ${E.cyan(c.handledRequestCount.toLocaleString("en-US"))} out of ${E.cyan(c.totalRequestCount.toLocaleString("en-US"))} handled`):u.push(`${E.yellow("Requests")}: ${E.gray("unknown handled")}`);let g=this.flags.verbose?"":E.gray(` (run with ${E.yellow("--verbose")} for a detailed breakdown)`);if(o.usageTotalUsd?u.push(`${E.yellow("Usage")}: ${E.cyan(this.formatUsd(o.usageTotalUsd))}${g}`):u.push(`${E.yellow("Usage")}: $${E.gray("0.000")}${g}`),this.flags.verbose&&u.push(Zt.render(0)),u.push(""),u.push(`${E.yellow("Started")}: ${B.display(o.startedAt)}`),o.finishedAt)u.push(`${E.yellow("Finished")}: ${B.display(o.finishedAt)} (took ${E.gray(oe.format(o.stats.durationMillis))})`);else{let T=Date.now()-o.startedAt.getTime();u.push(`${E.yellow("Finished")}: ${E.gray(`Running for ${oe.format(T)}`)}`)}if(u.push(""),o.stats.resurrectCount?u.push(`${E.yellow("Resurrected")}: Yes, ${E.cyan(o.stats.resurrectCount.toLocaleString("en-US"))} ${this.pluralString(o.stats.resurrectCount,"time","times")}`):u.push(`${E.yellow("Resurrected")}: No`),o.containerUrl&&u.push(`${E.yellow("Container URL")}: ${E.blue(o.containerUrl)}`),u.push(`${E.yellow("Origin")}: ${o.meta.origin}`),s){let T=o.buildNumber.split(".").slice(0,2).join("."),I=s.versions.find(j=>j.versionNumber===T),L=Object.entries(s.taggedBuilds??{}).find(([,j])=>j.buildNumber===o.buildNumber)?.[0],D=[`${E.yellow("Build")}:`,E.cyan(o.buildNumber)];L?D.push(`(${E.yellow(L)})`):D.push(`(${E.gray("N/A")})`),I&&D.push(`| ${E.gray("Actor version:")} ${E.cyan(I.versionNumber)} (${E.yellow(I.buildTag)})`),u.push(D.join(" "))}else u.push(`${E.yellow("Build")}: ${E.cyan(o.buildNumber)}`);u.push(`${E.yellow("Timeout")}: ${o.options.timeoutSecs.toLocaleString("en-US")} seconds`),u.push(`${E.yellow("Memory")}: ${o.options.memoryMbytes} MB`),u.push(""),u.push(`${E.yellow("CPU")}: ${E.gray("Average:")} ${o.stats.cpuAvgUsage.toFixed(2)}% | ${E.gray("Maximum:")} ${o.stats.cpuMaxUsage.toFixed(2)}%`),u.push(`${E.yellow("Memory")}: ${E.gray("Average:")} ${W({bytes:o.stats.memAvgBytes,shortBytes:!0})} | ${E.gray("Maximum:")} ${W({bytes:o.stats.memMaxBytes,shortBytes:!0})}`),u.push("");let y=`https://console.apify.com/actors/${o.actId}/runs/${o.id}`,b=`https://console.apify.com/storage/datasets/${o.defaultDatasetId}`,C=`https://console.apify.com/storage/key-value-stores/${o.defaultKeyValueStoreId}`;u.push(`${E.blue("Export results")}: ${b}`),u.push(`${E.blue("View saved items")}: ${C}`),u.push(`${E.blue("View in Apify Console")}: ${y}`),_({message:u.join(`
206
+ `),stdout:!0})}addDetailedUsage(e){let{usage:r,usageUsd:o}=e;if(!r||!o){for(let s of Object.keys(Ia))Zt.pushRow({"":s,Unit:"N/A","USD Amount":"N/A"});return}for(let[s,i]of Object.entries(Ia)){let n=r[i]??0,a=o[i]??0;switch(i){case"ACTOR_COMPUTE_UNITS":{Zt.pushRow({"":s,Unit:n.toFixed(4),"USD Amount":this.formatUsd(a)});break}case"DATA_TRANSFER_INTERNAL_GBYTES":case"DATA_TRANSFER_EXTERNAL_GBYTES":case"PROXY_RESIDENTIAL_TRANSFER_GBYTES":{Zt.pushRow({"":s,Unit:W({bytes:n*1024*1024*1024,shortBytes:!0}),"USD Amount":this.formatUsd(a)});break}default:Zt.pushRow({"":s,Unit:n.toLocaleString("en-US"),"USD Amount":this.formatUsd(a)})}}}formatUsd(e){return`$${e.toFixed(3)}`}};var jo=class extends h{static name="log";static description="Prints the log of a specific run.";static args={runId:w.string({required:!0,description:"The run ID to get the log from."})};async run(){let{runId:e}=this.args,r=await S(),o=await r.run(e).get();if(!o){m({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}v({message:`Log for run with ID "${e}":
207
+ `,stdout:!0});try{await Se({job:o,apifyClient:r})}catch(s){m({message:`Failed to get log for run with ID "${e}": ${s.message}`})}}};import ge from"chalk";var $a=new V({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"}}),Mo=class extends h{static name="ls";static description="Lists all runs of the Actor.";static flags={offset:A.integer({description:"Number of runs that will be skipped.",default:0}),limit:A.integer({description:"Number of runs that will be listed.",default:10}),desc:A.boolean({description:"Sort runs in descending order.",default:!1}),compact:A.boolean({description:"Display a compact table.",default:!1,char:"c"})};static args={actorId:w.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:r,offset:o,compact:s,json:i}=this.flags,{actorId:n}=this.args,a=await S(),c=await Fe({providedActorNameOrId:n,client:a});if(!c.valid){m({message:`${c.reason}. Please run this command in an Actor directory, or specify the Actor ID.`});return}let d=await a.actor(c.id).runs().list({desc:e,limit:r,offset:o});if(i){N(d);return}if(!d.items.length){_({message:"There are no recent runs found for this Actor."});return}let u=[`${ge.reset("Showing")} ${ge.yellow(d.items.length)} out of ${ge.yellow(d.total)} runs for Actor ${ge.yellow(c.userFriendlyId)} (${ge.gray(c.id)})`],f=new Map(await Promise.all(d.items.map(async p=>a.dataset(p.defaultDatasetId).get().then(g=>[p.id,ge.yellow(g?.itemCount??0)],()=>[p.id,ge.gray("N/A")]))));for(let p of d.items){let g;if(p.finishedAt){let y=p.finishedAt.getTime()-p.startedAt.getTime();g=ge.gray(`${oe.format(y,void 0,{left:""})}`)}else{let y=Date.now()-p.startedAt.getTime();g=ge.gray(`Running for ${oe.format(y,void 0,{left:""})}`)}$a.pushRow({ID:ge.gray(p.id),Status:be(p.status),Results:f.get(p.id)||ge.gray("N/A"),Usage:ge.cyan(`$${(p.usageTotalUsd??0).toFixed(3)}`),"Started At":Pt.display(p.startedAt),Took:g,"Build No.":p.buildNumber,Origin:p.meta.origin??"UNKNOWN"})}u.push($a.render(s?0:1)),_({message:u.join(`
208
+ `),stdout:!0})}};import{ACTOR_JOB_STATUSES as Bo}from"@apify/consts";var am=[Bo.SUCCEEDED,Bo.FAILED,Bo.ABORTED,Bo.TIMED_OUT],Vo=class extends h{static name="resurrect";static description="Resurrects an aborted or finished Actor Run.";static args={runId:w.string({required:!0,description:"The run ID to resurrect."})};static enableJsonFlag=!0;async run(){let{runId:e}=this.args,r=await S(),o=await r.run(e).get();if(!o){m({message:`Run with ID "${e}" was not found on your account.`,stdout:!0});return}if(!am.includes(o.status)){m({message:`Run with ID "${e}" cannot be resurrected, as it is still running or in the process of aborting.`,stdout:!0});return}try{let s=await r.run(e).resurrect();if(this.flags.json){N(s);return}R({message:`Run with ID "${e}" was resurrected successfully.`,stdout:!0})}catch(s){let i=s;m({message:`Failed to resurrect run "${e}".
209
+ ${i.message||i}`,stdout:!0})}}};import{ACTOR_JOB_STATUSES as Yo}from"@apify/consts";var cm=[Yo.SUCCEEDED,Yo.FAILED,Yo.ABORTED,Yo.TIMED_OUT],Go=class extends h{static name="rm";static description="Deletes an Actor Run.";static args={runId:w.string({description:"The run ID to delete.",required:!0})};async run(){let{runId:e}=this.args,r=await S(),o=await r.run(e).get();if(!o){m({message:`Run with ID "${e}" was not found on your account.`});return}if(!cm.includes(o.status)){m({message:`Run with ID "${e}" cannot be deleted, as it is still running or in the process of aborting.`});return}if(!await H({message:"Are you sure you want to delete this Actor Run?"})){v({message:`Deletion of run "${e}" was canceled.`});return}try{await r.run(e).delete(),R({message:`Run with ID "${e}" was deleted.`})}catch(i){let n=i;m({message:`Failed to delete run "${e}".
210
+ ${n.message||n}`})}}};var Ho=class extends h{static name="runs";static description="Manages Actor run operations ";static subcommands=[Fo,Uo,jo,Mo,Vo,Go];async run(){this.printHelp()}};var Jo=class extends h{static name="add";static description="Adds a new secret to '~/.apify' for use in Actor environment variables.";static args={name:w.string({required:!0,description:"Name of the secret"}),value:w.string({required:!0,description:"Value of the secret"})};async run(){let{name:e,value:r}=this.args;dn(e,r)}};var Ko=class extends h{static name="rm";static description="Permanently deletes a secret from your stored credentials.";static args={name:w.string({required:!0,description:"Name of the secret"})};async run(){let{name:e}=this.args;mn(e)}};var qo=class extends h{static name="secrets";static description=`Manages secure environment variables for Actors.
211
+
212
+ Example:
213
+ $ apify secrets add mySecret TopSecretValue123
214
+
215
+ The "mySecret" value can be used in an environment variable defined in '${M}' file by adding the "@"
216
+ prefix:
217
+
218
+ {
219
+ "actorSpecification": 1,
220
+ "name": "my_actor",
221
+ "environmentVariables": { "SECRET_ENV_VAR": "@mySecret" },
222
+ "version": "0.1"
223
+ }
224
+
225
+ When the Actor is pushed to Apify cloud, the "SECRET_ENV_VAR" and its value is stored as a secret environment variable
226
+ of the Actor.`;static subcommands=[Jo,Ko];async run(){this.printHelp()}};import Ea from"chalk";var Wo=class extends h{static name="run";static description=`Executes predefined Actor task remotely using local key-value store for input.
227
+ Customize with --memory and --timeout flags.
228
+ `;static flags=Tt("Task");static args={taskId:w.string({required:!0,description:'Name or ID of the Task to run (e.g. "my-task" or "E2jjCZBezvAZnX8Rb").'})};async run(){let e=await S(),r=await k(),o=r.username||r.id,{id:s,userFriendlyId:i,title:n}=await this.resolveTaskId(e,o),a={waitForFinish:2};this.flags.build&&(a.build=this.flags.build),this.flags.timeout&&(a.timeout=this.flags.timeout),this.flags.memory&&(a.memory=this.flags.memory);let c,d,u=bt(e,{actorOrTaskData:{id:s,userFriendlyId:i,title:n},runOptions:a,type:"Task",printRunLogs:!0});for await(let f of u)c=`https://console.apify.com/actors/${f.actId}/runs/${f.id}`,d=`https://console.apify.com/storage/datasets/${f.defaultDatasetId}`;_({message:["",`${Ea.blue("Export results")}: ${d}`,`${Ea.blue("View on Apify Console")}: ${c}`].join(`
229
+ `),stdout:!0})}async resolveTaskId(e,r){let{taskId:o}=this.args;if(o?.includes("/")){let s=await e.task(o).get();if(!s)throw new Error(`Cannot find Task with ID '${o}' in your account.`);return{id:s.id,userFriendlyId:`${r}/${s.name}`,title:s.title,task:s}}if(o){let s=await e.task(`${r}/${o.toLowerCase()}`).get();if(!s)throw new Error(`Cannot find Task with name '${o}' in your account.`);return{id:s.id,userFriendlyId:`${r}/${s.name}`,title:s.title,task:s}}throw new Error("Please provide a valid Task ID or name.")}};var zo=class extends h{static name="task";static description="Manages scheduled and predefined Actor configurations.";static subcommands=[Wo];async run(){this.printHelp()}};import lm from"process";import{validateInputSchema as um}from"@apify/input_schema";var Xo=class extends h{static name="validate-schema";static description=`Validates Actor input schema from one of these locations (in priority order):
230
+ 1. Object in '${M}' under "input" key
231
+ 2. JSON file path in '${M}' "input" key
232
+ 3. .actor/INPUT_SCHEMA.json
233
+ 4. INPUT_SCHEMA.json
234
+
235
+ Optionally specify custom schema path to validate.`;static args={path:w.string({required:!1,description:"Optional path to your INPUT_SCHEMA.json file. If not provided ./INPUT_SCHEMA.json is used."})};static hiddenAliases=["vis"];async run(){let{inputSchema:e,inputSchemaPath:r}=await nt({forcePath:this.args.path,cwd:lm.cwd()});if(!e)throw new Error(`Input schema has not been found at ${r}.`);r?v({message:`Validating input schema stored at ${r}`}):v({message:`Validating input schema embedded in '${M}'`});let o=new lt({strict:!1});um(o,e),R({message:"Input schema is valid."})}};var N_=[vr,Pr,Mr,ao,Io,xo,Ho,qo,zo,Br,Kt,Jt,Xr,co,uo,go,fo,$o,Eo,Ro,_o,Po,Xo,Wt],L_=[yt,ht,gt,ft,pt,mt,Wt,Kt,Jt];export{br as a,Kf as b,qf as c,N_ as d,L_ as e};
236
+ //# sourceMappingURL=chunk-A3JEYXK4.js.map