diff --git a/package.json b/package.json index 4143e8d1c..4b4382be1 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ }, "homepage": "https://github.com/apify/apify-cli#readme", "engines": { - "node": ">=22" + "node": ">=22.15.0" }, "dependencies": { "@apify/actor-memory-expression": "^1.0.3", @@ -86,7 +86,7 @@ "@skyra/jaro-winkler": "^1.1.1", "adm-zip": "~0.6.1", "ajv": "~8.20.0", - "apify-client": "^2.26.0", + "apify-client": "^3.0.0-rc.2", "archiver": "~8.0.0", "axios": "^1.21.1", "chalk": "~6.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f56e0d2dd..368e521d9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -230,8 +230,8 @@ importers: specifier: ~8.20.0 version: 8.20.0 apify-client: - specifier: ^2.26.0 - version: 2.26.0(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1) + specifier: ^3.0.0-rc.2 + version: 3.0.0-rc.2(axios@1.21.1(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)) archiver: specifier: ~8.0.0 version: 8.0.0(bare-buffer@3.7.1) @@ -4678,6 +4678,15 @@ packages: apify-client@2.26.0: resolution: {integrity: sha512-IVoJLHAwVh0jWTB8hLIiA55cmkS5QSTN30b2MjvXO9MyjyD2dVT7+wYAPhWfsFsteeCXOIaAK3GcCJyWAXzQbQ==} + apify-client@3.0.0-rc.2: + resolution: {integrity: sha512-KEXG3Jk7yqpzoDTMJuhYHKgTtUR8z0HD/u5ZztPHLV3UlpyGCPtYd30jV2fWZtWKWrLdedJAJ7Ps28QaYgOdwQ==} + engines: {node: '>=22.15.0'} + peerDependencies: + axios: ^1.21.1 + peerDependenciesMeta: + axios: + optional: true + apify@3.7.2: resolution: {integrity: sha512-I4R5Qd1X11vk5/1U0CxKSsMhNwER/3MntePEQb9Pbtf942OhQLh5IURrJZufqtpimkqRy44SlQMU6UhPdoFXhA==} engines: {node: '>=16.0.0'} @@ -5194,6 +5203,10 @@ packages: resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} engines: {node: '>= 0.6'} + content-type@3.1.1: + resolution: {integrity: sha512-GW4qUsfFo59d0HbUibDlWv5wPz+vAAcaTWbKIuKCf0JkC7wWkSyf8f13IpXn5JkeMlB2P8iTSSIjwXljorg2vA==} + engines: {node: '>=22'} + convert-source-map@1.9.0: resolution: {integrity: sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==} @@ -14879,6 +14892,19 @@ snapshots: - debug - supports-color + apify-client@3.0.0-rc.2(axios@1.21.1(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)): + dependencies: + '@apify/consts': 3.1.0 + '@apify/log': 3.0.2 + '@apify/utilities': 3.1.1 + '@apify/validations': 1.1.4 + ansi-colors: 4.1.3 + content-type: 3.1.1 + tslib: 2.9.1 + zod: 4.6.7 + optionalDependencies: + axios: 1.21.1(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1) + apify@3.7.2(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1): dependencies: '@apify/consts': 2.58.1 @@ -15438,6 +15464,8 @@ snapshots: content-type@1.0.5: {} + content-type@3.1.1: {} + convert-source-map@1.9.0: {} convert-source-map@2.0.0: {} diff --git a/scripts/build-cli-bundles.ts b/scripts/build-cli-bundles.ts index 6926b20d0..14241f85e 100644 --- a/scripts/build-cli-bundles.ts +++ b/scripts/build-cli-bundles.ts @@ -107,15 +107,9 @@ for (const entryPoint of entryPoints) { // entrypoint file name (`bundle.ts`) - install/upgrade and the asset matcher all key off `apify-cli`. const cliName = 'apify-cli'; - const lines = readFileSync(entryPoint, 'utf-8').split('\n'); - lines.splice(1, 0, 'import "proxy-agent";'); - // Step 1: create one fat JS file with node resolver to ensure no imports point to non-node export conditions const result = await build({ entrypoints: [entryPoint], - files: { - [entryPoint]: lines.join('\n'), - }, define: { __APIFY_CLI_SKILL__: JSON.stringify(APIFY_CLI_SKILL), __APIFY_WINDOWS_UPGRADE_SCRIPT__: JSON.stringify(WINDOWS_UPGRADE_SCRIPT), @@ -131,12 +125,8 @@ for (const entryPoint of entryPoints) { const entrypointResultFilePath = result.outputs[0]!.path; - // Fix apify client js (it now lazy loads proxy-agent, which makes bun skip it from the bundle). // Kept in memory only — the per-target write below is what lands on disk before each compile. - const fatEntrypointContent = (await result.outputs[0]!.text()).replace( - `(0, utils_1.dynamicNodeImport)("proxy-agent")`, - `Promise.resolve().then(() => import_proxy_agent)`, - ); + const fatEntrypointContent = await result.outputs[0]!.text(); // `replaceAll` is silent if the placeholder is gone, shipping a bundle that falls back to // plaintext storage. Validate once up front and fail loud. @@ -162,7 +152,7 @@ for (const entryPoint of entryPoints) { // Point the keyring import at this target's native subpackage so --compile embeds its // `.node`. Rewrite every iteration so the compiled file is never the stale, unpatched - // Bun output — the proxy-agent fix above lands on disk here too, not just the keyring swap. + // Bun output. const subpackage = keyringSubpackage(os, arch, isMusl); await writeFile(entrypointResultFilePath, fatEntrypointContent.replaceAll(KEYRING_PLACEHOLDER, subpackage)); diff --git a/src/commands/actor/get-public-url.ts b/src/commands/actor/get-public-url.ts index 6b5cb8001..1b515b477 100644 --- a/src/commands/actor/get-public-url.ts +++ b/src/commands/actor/get-public-url.ts @@ -50,7 +50,7 @@ export class ActorGetPublicUrlCommand extends ApifyCommand { } if (this.flags.timeout !== undefined) { - runOpts.timeout = this.flags.timeout; + runOpts.runTimeoutSecs = this.flags.timeout; } if (this.flags.memory) { @@ -181,7 +181,7 @@ export class ActorsCallCommand extends ApifyCommand { } let runStarted = false; - let run: ActorRun; + let run: Run; const iterator = runActorOrTaskOnCloud(apifyClient, { actorOrTaskData: { @@ -217,12 +217,12 @@ export class ActorsCallCommand extends ApifyCommand { // basic version info - const expectedActorVersion = run.buildNumber.split('.').slice(0, 2).join('.'); + const expectedActorVersion = run.buildNumber?.split('.').slice(0, 2).join('.'); const actorVersion = actorData.versions.find((item) => item.versionNumber === expectedActorVersion); const runVersionTaggedAs = Object.entries( - (actorData.taggedBuilds ?? {}) as Record, + (actorData.taggedBuilds ?? {}) as Record, ).find(([, data]) => data.buildNumber === yieldedRun.buildNumber)?.[0]; const messageParts = [`${chalk.yellow('Build')}:`, chalk.cyan(run.buildNumber)]; @@ -270,7 +270,7 @@ export class ActorsCallCommand extends ApifyCommand { if (this.flags.outputDataset && run!.status === ACTOR_JOB_STATUSES.SUCCEEDED) { const datasetId = run!.defaultDatasetId; - let info: Dataset; + let info: DatasetResource; let retries = 4; // Why is this needed? Sometimes, when fetching the dataset info right after the run ends, the object doesn't have the stats up-to-date. diff --git a/src/commands/actors/info.ts b/src/commands/actors/info.ts index 2ab6f068a..cde4542d4 100644 --- a/src/commands/actors/info.ts +++ b/src/commands/actors/info.ts @@ -1,4 +1,12 @@ -import type { Actor, ActorChargeEvent, ActorTaggedBuild, ApifyApiError, ApifyClient, Build, User } from 'apify-client'; +import type { + ActorResource, + ActorChargeEvent, + TaggedBuildInfo, + ApifyApiError, + ApifyClient, + Build, + UserPrivateInfo, +} from 'apify-client'; import chalk from 'chalk'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; @@ -9,9 +17,9 @@ import { CompactMode, ResponsiveTable } from '../../lib/commands/responsive-tabl import { error, simpleLog } from '../../lib/outputs.js'; import { DurationFormatter, getLoggedClientOrThrow, printJsonToStdout, TimestampFormatter } from '../../lib/utils.js'; -interface HydratedActorInfo extends Omit { - taggedBuilds?: Record; - actorMaker?: User; +interface HydratedActorInfo extends Omit { + taggedBuilds?: Record; + actorMaker?: UserPrivateInfo; } // apify-client's ActorChargeEvent declares eventPriceUsd as required and is missing @@ -188,7 +196,7 @@ export class ActorsInfoCommand extends ApifyCommand { if (actorInfo.actorMaker) { message.push( '', - `${chalk.yellow('Made by:')} ${chalk.cyan(actorInfo.actorMaker.profile.name ?? actorInfo.actorMaker.username)}`, + `${chalk.yellow('Made by:')} ${chalk.cyan(actorInfo.actorMaker.profile?.name ?? actorInfo.actorMaker.username)}`, ); // Missing types who? @@ -230,7 +238,7 @@ export class ActorsInfoCommand extends ApifyCommand { break; } case 'PRICE_PER_DATASET_ITEM': { - const pricePerOneKItems = latestPricingInfo.pricePerUnitUsd * 1000; + const pricePerOneKItems = (latestPricingInfo.pricePerUnitUsd ?? 0) * 1000; message.push( `${chalk.yellow('Pricing information:')} ${chalk.bgGray(`$${pricePerOneKItems.toFixed(2)} / 1,000 results`)}`, diff --git a/src/commands/actors/ls.ts b/src/commands/actors/ls.ts index 8ecaacaa7..11a0aed8b 100644 --- a/src/commands/actors/ls.ts +++ b/src/commands/actors/ls.ts @@ -1,5 +1,5 @@ import { Time } from '@sapphire/duration'; -import type { Actor, ActorRunListItem, ActorTaggedBuild, PaginatedList } from 'apify-client'; +import type { ActorListItem, ActorResource, RunListItem, TaggedBuildInfo, PaginatedList } from 'apify-client'; import chalk from 'chalk'; import type { ACTOR_JOB_STATUSES } from '@apify/consts'; @@ -79,19 +79,9 @@ const myRecentlyUsedTable = new ResponsiveTable({ }, }); -interface HydratedListData { - id: string; - createdAt: Date; - modifiedAt: Date; - name: string; - username: string; - title: string; - stats: { - totalRuns: number; - lastRunStartedAt: string | null; - }; - actor: Actor | null; - lastRun: ActorRunListItem | null; +interface HydratedListData extends ActorListItem { + actor: ActorResource | null; + lastRun: RunListItem | null; } export class ActorsLsCommand extends ApifyCommand { @@ -180,14 +170,14 @@ export class ActorsLsCommand extends ApifyCommand { limit: 1, offset: 0, total: 0, - }) satisfies PaginatedList, + }) satisfies PaginatedList, ); return { ...actorData, actor: actor ?? null, - lastRun: (runs.items[0] ?? null) as ActorRunListItem | null, - } as HydratedListData; + lastRun: (runs.items[0] ?? null) as RunListItem | null, + }; }), ), }; @@ -217,7 +207,7 @@ export class ActorsLsCommand extends ApifyCommand { 6; for (const item of actorList.items) { - const lastRunDisplayedTimestamp = item.stats.lastRunStartedAt + const lastRunDisplayedTimestamp = item.stats?.lastRunStartedAt ? MultilineTimestampFormatter.display(item.stats.lastRunStartedAt) : ''; @@ -238,7 +228,7 @@ export class ActorsLsCommand extends ApifyCommand { const defaultBuild = item.actor ? (() => { const buildVersionToTag = Object.entries( - (item.actor.taggedBuilds ?? {}) as Record, + (item.actor.taggedBuilds ?? {}) as Record, ).find( ([tag, data]) => data.buildNumber === item.actor!.defaultRunOptions.build || tag === item.actor!.defaultRunOptions.build, diff --git a/src/commands/actors/pull.ts b/src/commands/actors/pull.ts index 6db6365cd..ad6f1a2b2 100644 --- a/src/commands/actors/pull.ts +++ b/src/commands/actors/pull.ts @@ -2,6 +2,7 @@ import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import process from 'node:process'; +import type { SourceCodeFile, SourceCodeFolder } from 'apify-client'; import { downloadTemplate } from 'giget'; import jju from 'jju'; import { gt } from 'semver'; @@ -31,6 +32,9 @@ const extractGitHubZip = async (url: string, directoryPath: string) => { zipFile.extractEntryTo(entries[0].entryName, directoryPath, false); }; +const isSourceFolder = (file: SourceCodeFile | SourceCodeFolder): file is SourceCodeFolder => + 'folder' in file && file.folder; + export class ActorsPullCommand extends ApifyCommand { static override name = 'pull' as const; @@ -192,10 +196,9 @@ export class ActorsPullCommand extends ApifyCommand { for (const { file, target } of files) { mkdirSync(dirname(target), { recursive: true }); - // @ts-expect-error TODO: is this an actual field? - if (!file.folder) { - const fileContent = - file.format === 'BASE64' ? Buffer.from(file.content, 'base64').toString() : file.content; + if (!isSourceFolder(file)) { + const content = file.content ?? ''; + const fileContent = file.format === 'BASE64' ? Buffer.from(content, 'base64').toString() : content; if (target === join(root, LOCAL_CONFIG_PATH)) { const actorJson = jju.parse(fileContent); diff --git a/src/commands/actors/push.ts b/src/commands/actors/push.ts index e98d8f285..c0de542a1 100644 --- a/src/commands/actors/push.ts +++ b/src/commands/actors/push.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, relative, resolve } from 'node:path'; import process from 'node:process'; -import type { Actor, ActorCollectionCreateOptions, ActorDefaultRunOptions, ApifyClient, Build } from 'apify-client'; +import type { ActorResource, ActorCollectionCreateOptions, DefaultRunOptions, ApifyClient, Build } from 'apify-client'; import chalk from 'chalk'; import { isCI } from 'ci-info'; import open from 'open'; @@ -811,7 +811,7 @@ export class ActorsPushCommand extends ApifyCommand { const redirectUrlPart = isOrganizationLoggedIn ? `/organization/${userInfo.id}` : ''; let actorId: string; - let actor: Actor; + let actor: ActorResource; let isActorCreatedNow = false; // User can override Actor version and build tag, attributes in localConfig will remain same. @@ -845,7 +845,7 @@ export class ActorsPushCommand extends ApifyCommand { } else { const { templates } = await fetchManifest(); const actorTemplate = templates.find((t) => t.name === actorConfig!.template); - const defaultRunOptions = (actorTemplate?.defaultRunOptions || DEFAULT_RUN_OPTIONS) as ActorDefaultRunOptions; + const defaultRunOptions = (actorTemplate?.defaultRunOptions || DEFAULT_RUN_OPTIONS) as DefaultRunOptions; const newActor: ActorCollectionCreateOptions = { name: actorConfig!.name as string, title: actorConfig!.title as string | undefined, @@ -1182,7 +1182,7 @@ Skipping push. Use --force to override.`, let standbyUrl: string | undefined; if (outcome.ok && actorConfig!.usesStandbyMode) { - const pushedActor = (await actorClient.get()) as (Actor & { standbyUrl?: string | null }) | undefined; + const pushedActor = (await actorClient.get()) as (ActorResource & { standbyUrl?: string | null }) | undefined; standbyUrl = pushedActor?.standbyUrl ?? undefined; } diff --git a/src/commands/actors/search.ts b/src/commands/actors/search.ts index dd1978c6f..c479f731f 100644 --- a/src/commands/actors/search.ts +++ b/src/commands/actors/search.ts @@ -1,7 +1,6 @@ -import { ApifyClient } from 'apify-client'; import chalk from 'chalk'; -import { getAnonymousApifyClientOptions } from '../../lib/auth.js'; +import { createApifyClient, getAnonymousApifyClientOptions } from '../../lib/auth.js'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; import { Args } from '../../lib/command-framework/args.js'; import { Flags } from '../../lib/command-framework/flags.js'; @@ -23,7 +22,7 @@ function formatPricingModel(model?: string): string { return pricingModelLabels[model] ?? model; } -function truncateDescription(description?: string, maxLength = 60): string { +function truncateDescription(description?: string | null, maxLength = 60): string { if (!description) return ''; if (description.length <= maxLength) return description; @@ -97,7 +96,7 @@ export class ActorsSearchCommand extends ApifyCommand } if (this.flags.timeout !== undefined) { - runOpts.timeout = this.flags.timeout; + runOpts.runTimeoutSecs = this.flags.timeout; } if (this.flags.memory) { @@ -129,7 +129,7 @@ export class ActorsStartCommand extends ApifyCommand printRunLogs: false, }); - let run: ActorRun | undefined; + let run: Run | undefined; for await (const yieldedRun of iterator) { run = yieldedRun; diff --git a/src/commands/builds/add-tag.ts b/src/commands/builds/add-tag.ts index 398a89d4e..ee4d9a54a 100644 --- a/src/commands/builds/add-tag.ts +++ b/src/commands/builds/add-tag.ts @@ -1,4 +1,4 @@ -import type { ActorTaggedBuild, ApifyApiError } from 'apify-client'; +import type { TaggedBuildInfo, ApifyApiError } from 'apify-client'; import chalk from 'chalk'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; @@ -67,7 +67,7 @@ export class BuildsAddTagCommand extends ApifyCommand; + const existingTaggedBuilds = (actor.taggedBuilds ?? {}) as Record; const existingTagData = existingTaggedBuilds[tag]; if (existingTagData?.buildId === buildId) { diff --git a/src/commands/builds/info.ts b/src/commands/builds/info.ts index 307183152..f9ce44166 100644 --- a/src/commands/builds/info.ts +++ b/src/commands/builds/info.ts @@ -57,7 +57,7 @@ export class BuildsInfoCommand extends ApifyCommand { if (actor?.taggedBuilds) { for (const [tag, buildData] of Object.entries(actor.taggedBuilds)) { - if (buildData.buildId === build.id) { + if (buildData?.buildId === build.id) { buildTag = tag; break; } diff --git a/src/commands/builds/ls.ts b/src/commands/builds/ls.ts index 34a40bcdb..deb97e48a 100644 --- a/src/commands/builds/ls.ts +++ b/src/commands/builds/ls.ts @@ -1,4 +1,4 @@ -import type { BuildCollectionClientListItem } from 'apify-client'; +import type { BuildListItem } from 'apify-client'; import chalk from 'chalk'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; @@ -99,7 +99,7 @@ export class BuildsLsCommand extends ApifyCommand { const buildTagToActorVersion = Object.entries(actorInfo.taggedBuilds ?? {}).reduce( (acc, [tag, data]) => { - acc[data.buildNumber!] = tag; + if (data?.buildNumber) acc[data.buildNumber] = tag; return acc; }, @@ -167,7 +167,7 @@ export class BuildsLsCommand extends ApifyCommand { buildsForVersion, buildTagToActorVersion, }: { - buildsForVersion: BuildCollectionClientListItem[]; + buildsForVersion: BuildListItem[]; buildTagToActorVersion: Record; }) { const table = tableFactory(); diff --git a/src/commands/builds/remove-tag.ts b/src/commands/builds/remove-tag.ts index 4b467df90..099ddefbb 100644 --- a/src/commands/builds/remove-tag.ts +++ b/src/commands/builds/remove-tag.ts @@ -1,4 +1,4 @@ -import type { ActorTaggedBuild, ApifyApiError } from 'apify-client'; +import type { TaggedBuildInfo, ApifyApiError } from 'apify-client'; import chalk from 'chalk'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; @@ -60,7 +60,7 @@ export class BuildsRemoveTagCommand extends ApifyCommand; + const existingTaggedBuilds = (actor.taggedBuilds ?? {}) as Record; const existingTagData = existingTaggedBuilds[tag]; // Check if the tag exists diff --git a/src/commands/builds/rm.ts b/src/commands/builds/rm.ts index 78ff6640d..d69112958 100644 --- a/src/commands/builds/rm.ts +++ b/src/commands/builds/rm.ts @@ -1,4 +1,4 @@ -import type { ActorTaggedBuild } from 'apify-client'; +import type { TaggedBuildInfo } from 'apify-client'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; import { Args } from '../../lib/command-framework/args.js'; @@ -58,7 +58,7 @@ export class BuildsRmCommand extends ApifyCommand { if (actor?.taggedBuilds) { // If this build is tagged in the actor, console asks you to write the tag. - for (const [tag, buildData] of Object.entries(actor.taggedBuilds) as [string, ActorTaggedBuild][]) { + for (const [tag, buildData] of Object.entries(actor.taggedBuilds) as [string, TaggedBuildInfo][]) { if (buildId === buildData.buildId) { confirmationPrompt = tag; break; diff --git a/src/commands/datasets/get-items.ts b/src/commands/datasets/get-items.ts index e70570451..6933364f9 100644 --- a/src/commands/datasets/get-items.ts +++ b/src/commands/datasets/get-items.ts @@ -1,4 +1,4 @@ -import { type ApifyClient, type Dataset, type DatasetClient, DownloadItemsFormat } from 'apify-client'; +import { type ApifyClient, type DatasetResource, type DatasetClient, DownloadItemsFormat } from 'apify-client'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; import { Args } from '../../lib/command-framework/args.js'; @@ -95,7 +95,7 @@ export class DatasetsGetItems extends ApifyCommand { private async tryToGetDataset( client: ApifyClient, datasetId: string, - ): Promise<{ dataset: Dataset | undefined; datasetClient: DatasetClient } | null> { + ): Promise<{ dataset: DatasetResource | undefined; datasetClient: DatasetClient } | null> { const byIdOrName = await client .dataset(datasetId) .get() diff --git a/src/commands/datasets/ls.ts b/src/commands/datasets/ls.ts index f2aeca97c..0f04997ea 100644 --- a/src/commands/datasets/ls.ts +++ b/src/commands/datasets/ls.ts @@ -80,7 +80,7 @@ export class DatasetsLsCommand extends ApifyCommand { for (const dataset of rawDatasetList.items) { // TODO: update apify-client types - const size = Reflect.get(dataset.stats, 's3StorageBytes') as number | undefined; + const size = Reflect.get(dataset.stats ?? {}, 's3StorageBytes') as number | undefined; table.pushRow({ 'Dataset ID': dataset.id, diff --git a/src/commands/key-value-stores/get-value.ts b/src/commands/key-value-stores/get-value.ts index 7afdbaa32..214206067 100644 --- a/src/commands/key-value-stores/get-value.ts +++ b/src/commands/key-value-stores/get-value.ts @@ -1,3 +1,5 @@ +import { pipeline } from 'node:stream/promises'; + import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; import { Args } from '../../lib/command-framework/args.js'; import { Flags } from '../../lib/command-framework/flags.js'; @@ -69,7 +71,7 @@ export class KeyValueStoresGetValueCommand extends ApifyCommand u!), info.actId ? apifyClient.actor(info.actId).get() : Promise.resolve(undefined), diff --git a/src/commands/runs/info.ts b/src/commands/runs/info.ts index 12b4eefd0..e536ca4c0 100644 --- a/src/commands/runs/info.ts +++ b/src/commands/runs/info.ts @@ -1,4 +1,4 @@ -import type { ActorRun, ActorRunUsage, ActorTaggedBuild } from 'apify-client'; +import type { Run, RunUsage, TaggedBuildInfo } from 'apify-client'; import chalk from 'chalk'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; @@ -25,7 +25,7 @@ const usageTable = new ResponsiveTable({ }, }); -const usageMapping: Record = { +const usageMapping: Record = { 'Actor compute units': 'ACTOR_COMPUTE_UNITS', 'Dataset reads': 'DATASET_READS', 'Dataset writes': 'DATASET_WRITES', @@ -179,7 +179,7 @@ export class RunsInfoCommand extends ApifyCommand { if (run.finishedAt) { message.push( - `${chalk.yellow('Finished')}: ${TimestampFormatter.display(run.finishedAt)} (took ${chalk.gray(ShortDurationFormatter.format(run.stats.durationMillis))})`, + `${chalk.yellow('Finished')}: ${TimestampFormatter.display(run.finishedAt)} (took ${chalk.gray(ShortDurationFormatter.format(run.stats.durationMillis ?? 0))})`, ); } else { const diff = Date.now() - run.startedAt.getTime(); @@ -209,11 +209,11 @@ export class RunsInfoCommand extends ApifyCommand { // build if (actor) { // Compute detailed view - const expectedActorVersion = run.buildNumber.split('.').slice(0, 2).join('.'); + const expectedActorVersion = run.buildNumber?.split('.').slice(0, 2).join('.'); const actorVersion = actor.versions.find((item) => item.versionNumber === expectedActorVersion); - const runVersionTaggedAs = Object.entries((actor.taggedBuilds ?? {}) as Record).find( + const runVersionTaggedAs = Object.entries((actor.taggedBuilds ?? {}) as Record).find( ([, data]) => data.buildNumber === run.buildNumber, )?.[0]; @@ -248,13 +248,13 @@ export class RunsInfoCommand extends ApifyCommand { // CPU avg/max message.push( - `${chalk.yellow('CPU')}: ${chalk.gray('Average:')} ${run.stats.cpuAvgUsage.toFixed(2)}% | ${chalk.gray('Maximum:')} ${run.stats.cpuMaxUsage.toFixed(2)}%`, + `${chalk.yellow('CPU')}: ${chalk.gray('Average:')} ${(run.stats.cpuAvgUsage ?? 0).toFixed(2)}% | ${chalk.gray('Maximum:')} ${(run.stats.cpuMaxUsage ?? 0).toFixed(2)}%`, ); // memory avg/max message.push( - `${chalk.yellow('Memory')}: ${chalk.gray('Average:')} ${prettyPrintBytes({ bytes: run.stats.memAvgBytes, shortBytes: true })} | ${chalk.gray('Maximum:')} ${prettyPrintBytes({ bytes: run.stats.memMaxBytes, shortBytes: true })}`, + `${chalk.yellow('Memory')}: ${chalk.gray('Average:')} ${prettyPrintBytes({ bytes: run.stats.memAvgBytes ?? 0, shortBytes: true })} | ${chalk.gray('Maximum:')} ${prettyPrintBytes({ bytes: run.stats.memMaxBytes ?? 0, shortBytes: true })}`, ); // url @@ -272,7 +272,7 @@ export class RunsInfoCommand extends ApifyCommand { simpleLog({ message: message.join('\n'), stdout: true }); } - private addDetailedUsage(run: ActorRun) { + private addDetailedUsage(run: Run) { const { usage, usageUsd } = run; if (!usage || !usageUsd) { diff --git a/src/commands/runs/ls.ts b/src/commands/runs/ls.ts index 56ef7e42f..4c7aa6024 100644 --- a/src/commands/runs/ls.ts +++ b/src/commands/runs/ls.ts @@ -148,7 +148,7 @@ export class RunsLsCommand extends ApifyCommand { Usage: chalk.cyan(`$${(run.usageTotalUsd ?? 0).toFixed(3)}`), 'Started At': MultilineTimestampFormatter.display(run.startedAt), Took: tookString, - 'Build No.': run.buildNumber, + 'Build No.': run.buildNumber ?? chalk.gray('N/A'), Origin: run.meta.origin ?? 'UNKNOWN', }); } diff --git a/src/commands/task/run.ts b/src/commands/task/run.ts index cd073701b..93d4067c3 100644 --- a/src/commands/task/run.ts +++ b/src/commands/task/run.ts @@ -1,4 +1,4 @@ -import type { ActorRun, ApifyClient, TaskStartOptions } from 'apify-client'; +import type { Run, ApifyClient, TaskStartOptions } from 'apify-client'; import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; import { Args } from '../../lib/command-framework/args.js'; @@ -55,14 +55,14 @@ export class TaskRunCommand extends ApifyCommand { } if (this.flags.timeout !== undefined) { - runOpts.timeout = this.flags.timeout; + runOpts.runTimeoutSecs = this.flags.timeout; } if (this.flags.memory) { runOpts.memory = this.flags.memory; } - let run!: ActorRun; + let run!: Run; const iterator = runActorOrTaskOnCloud(apifyClient, { actorOrTaskData: { @@ -97,7 +97,7 @@ export class TaskRunCommand extends ApifyCommand { return { id: task.id, userFriendlyId: `${usernameOrId}/${task.name}`, - title: task.title, + title: task.title ?? undefined, task, }; } @@ -113,7 +113,7 @@ export class TaskRunCommand extends ApifyCommand { return { id: task.id, userFriendlyId: `${usernameOrId}/${task.name}`, - title: task.title, + title: task.title ?? undefined, task, }; } diff --git a/src/entrypoints/_shared.ts b/src/entrypoints/_shared.ts index a48884133..9d043767d 100644 --- a/src/entrypoints/_shared.ts +++ b/src/entrypoints/_shared.ts @@ -16,6 +16,7 @@ import { useCLIMetadata } from '../lib/hooks/useCLIMetadata.js'; import { shouldSkipVersionCheck } from '../lib/hooks/useCLIVersionCheck.js'; import { useCommandSuggestions } from '../lib/hooks/useCommandSuggestions.js'; import { error } from '../lib/outputs.js'; +import { useProxyFromEnv } from '../lib/proxy.js'; import { cliDebugPrint } from '../lib/utils/cliDebugPrint.js'; const cliMetadata = useCLIMetadata(); @@ -133,6 +134,8 @@ async function runVersionCheck(entrypoint: string, maybeCommandName?: string) { } export async function runCLI(entrypoint: string) { + useProxyFromEnv(); + // Clean up a legacy multi-bundle install (apify + actor + apify-cli) into the new single-bundle // layout (apify-cli binary + apify/actor wrapper scripts) on the first run after an upgrade. migrateLegacyBundleInstallIfNeeded(); diff --git a/src/lib/actor.ts b/src/lib/actor.ts index 09dd31e07..93ecfc7a5 100644 --- a/src/lib/actor.ts +++ b/src/lib/actor.ts @@ -5,11 +5,10 @@ import type { MemoryStorageOptions } from '@crawlee/memory-storage'; import { MemoryStorage } from '@crawlee/memory-storage'; import type { StorageClient } from '@crawlee/types'; import type { ApifyClientOptions } from 'apify-client'; -import { ApifyClient } from 'apify-client'; import { ACTOR_ENV_VARS, APIFY_ENV_VARS, KEY_VALUE_STORE_KEYS, LOCAL_ACTOR_ENV_VARS } from '@apify/consts'; -import { describeAuthFailure, getApifyClientOptionsForToken, resolveAuth } from './auth.js'; +import { createApifyClient, describeAuthFailure, getApifyClientOptionsForToken, resolveAuth } from './auth.js'; import { getLocalStorageDir } from './utils.js'; export const APIFY_STORAGE_TYPES = { @@ -40,10 +39,11 @@ export const getApifyStorageClient = async ( throw new Error(describeAuthFailure(auth)); } - return new ApifyClient({ + // crawlee types StorageClient against the apify-client v2 models, which v3 only makes more nullable. + return createApifyClient({ ...getApifyClientOptionsForToken(auth.token), ...options, - }); + }) as unknown as StorageClient; }; /** diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 04448c5a0..800730388 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -1,8 +1,7 @@ import { existsSync } from 'node:fs'; import process from 'node:process'; -import { ApifyApiError, ApifyClient, type ApifyClientOptions } from 'apify-client'; -import { AxiosHeaders } from 'axios'; +import { ApifyApiError, ApifyClient, type ApifyClientOptions, FetchHttpClient } from 'apify-client'; import { APIFY_ENV_VARS } from '@apify/consts'; @@ -26,7 +25,7 @@ import { } from './credentials.js'; import { clearOAuthSession, getAccessToken } from './oauth/session.js'; import { warning } from './outputs.js'; -import { ActorRuntimeNotRunningError, runtimeDownInterceptor, targetsConnectedRuntime } from './runtime/client.js'; +import { ActorRuntimeNotRunningError, runtimeDownFetch, targetsConnectedRuntime } from './runtime/client.js'; import { resolveApiBaseUrl } from './runtime/target.js'; import type { AuthJSON } from './types.js'; import { cliDebugPrint } from './utils/cliDebugPrint.js'; @@ -227,27 +226,11 @@ export function describeAuthFailure(auth: ResolvedAuth | undefined, error?: unkn } } -type CJSAxiosHeaders = import('axios', { with: { 'resolution-mode': 'require' } }).AxiosRequestConfig['headers']; - /** Base URL and headers, with no token and so no credential lookup. */ -export const getAnonymousApifyClientOptions = (apiBaseUrl?: string): ApifyClientOptions => { - const baseUrl = apiBaseUrl || resolveApiBaseUrl(); - return { - baseUrl, - requestInterceptors: [ - (config) => { - config.headers ??= new AxiosHeaders() as CJSAxiosHeaders; - - for (const [key, value] of Object.entries(APIFY_CLIENT_DEFAULT_HEADERS)) { - config.headers![key] = value; - } - - return config; - }, - ...(targetsConnectedRuntime(baseUrl) ? [runtimeDownInterceptor] : []), - ], - }; -}; +export const getAnonymousApifyClientOptions = (apiBaseUrl?: string): ApifyClientOptions => ({ + baseUrl: apiBaseUrl || resolveApiBaseUrl(), + headers: APIFY_CLIENT_DEFAULT_HEADERS, +}); /** Options for a caller that already holds a token, so nothing is resolved. */ export const getApifyClientOptionsForToken = (token: string, apiBaseUrl?: string): ApifyClientOptions => ({ @@ -255,6 +238,19 @@ export const getApifyClientOptionsForToken = (token: string, apiBaseUrl?: string token, }); +/** Builds the client for `options`. One for the connected runtime reports a stopped container at once. */ +export function createApifyClient(options: ApifyClientOptions): ApifyClient { + if (!targetsConnectedRuntime(options.baseUrl)) return new ApifyClient(options); + + const { baseUrl, publicBaseUrl, ...httpClientOptions } = options; + return ApifyClient.withCustomHttpClient({ + baseUrl, + publicBaseUrl, + token: options.token, + httpClient: new FetchHttpClient({ ...httpClientOptions, fetch: runtimeDownFetch }), + }); +} + /** * The only credential writer in the CLI. Returns `null` when the token is rejected, writing nothing. * Any OAuth session of the account is dropped; an OAuth login saves its new session right after. @@ -263,7 +259,7 @@ export async function loginWithToken( token: string, apiBaseUrl?: string, ): Promise<{ client: ApifyClient; userInfo: AuthJSON } | null> { - const apifyClient = new ApifyClient(getApifyClientOptionsForToken(token, apiBaseUrl)); + const apifyClient = createApifyClient(getApifyClientOptionsForToken(token, apiBaseUrl)); let userInfo; try { @@ -273,7 +269,7 @@ export async function loginWithToken( return null; } - if (!userInfo.id) { + if (!userInfo?.id) { throw new Error('The Apify API returned no user ID for this token, so the login cannot be stored.'); } @@ -282,7 +278,7 @@ export async function loginWithToken( // Brings a stored account to the current shape first, or the upsert below would find nothing to keep. await ensureCredentialsCurrent(); - const { organizationOwnerUserId } = userInfo as { organizationOwnerUserId?: string }; + const { organizationOwnerUserId } = userInfo; upsertProfile(userInfo.id, { username: userInfo.username, name: userInfo.username || userInfo.id, diff --git a/src/lib/commands/agent-output.ts b/src/lib/commands/agent-output.ts index 5d9021b32..40dbdb861 100644 --- a/src/lib/commands/agent-output.ts +++ b/src/lib/commands/agent-output.ts @@ -1,4 +1,4 @@ -import type { ActorRun, ApifyClient, Build } from 'apify-client'; +import type { Run, ApifyClient, Build } from 'apify-client'; import chalk from 'chalk'; import { ACTOR_JOB_STATUSES, ACTOR_JOB_TERMINAL_STATUSES, ACTOR_JOB_TYPES } from '@apify/consts'; @@ -47,7 +47,7 @@ export interface WaitForJobOptions { maxWaitMillis?: number; } -export interface WaitForJobResult { +export interface WaitForJobResult { job: T; /** * True when the wait gave up because `maxWaitMillis` elapsed before the job reached a terminal @@ -59,7 +59,7 @@ export interface WaitForJobResult interface JobTypeMap { BUILD: Build; - RUN: ActorRun; + RUN: Run; } export async function waitForTerminalStatus( diff --git a/src/lib/commands/run-on-cloud.ts b/src/lib/commands/run-on-cloud.ts index 615f695d8..74f5a89e8 100644 --- a/src/lib/commands/run-on-cloud.ts +++ b/src/lib/commands/run-on-cloud.ts @@ -1,6 +1,6 @@ import process from 'node:process'; -import type { ActorRun, ActorStartOptions, ApifyClient, TaskStartOptions } from 'apify-client'; +import type { Run, ActorStartOptions, ApifyClient, TaskStartOptions } from 'apify-client'; import chalk from 'chalk'; import { ACTOR_JOB_STATUSES, ACTOR_JOB_TYPES } from '@apify/consts'; @@ -49,15 +49,15 @@ async function startActorWithExtraParams( input: { inputToUse: unknown; contentType: string } | null, runOptions: ActorStartOptions, extraStartParams: Record, -): Promise { - const { waitForFinish, timeout, memory, build } = runOptions; +): Promise { + const { waitForFinish, runTimeoutSecs, memory, build } = runOptions; const response = await apifyClient.httpClient.call<{ data: { id: string } }>({ url: `${apifyClient.actor(actorId).url}/runs`, method: 'POST', data: input?.inputToUse, headers: input ? { 'content-type': input.contentType } : undefined, - params: { waitForFinish, timeout, memory, build, ...extraStartParams }, + params: { waitForFinish, timeout: runTimeoutSecs, memory, build, ...extraStartParams }, }); return (await apifyClient.run(response.data.data.id).get())!; @@ -99,7 +99,7 @@ export async function* runActorOrTaskOnCloud(apifyClient: ApifyClient, options: } } - let run: ActorRun; + let run: Run; try { if (extraStartParams && type === 'Actor') { diff --git a/src/lib/commands/run-result.ts b/src/lib/commands/run-result.ts index 842f8e3fd..a46569041 100644 --- a/src/lib/commands/run-result.ts +++ b/src/lib/commands/run-result.ts @@ -1,6 +1,6 @@ import process from 'node:process'; -import type { ActorRun, ApifyClient } from 'apify-client'; +import type { Run, ApifyClient } from 'apify-client'; import chalk from 'chalk'; import { ACTOR_JOB_STATUSES } from '@apify/consts'; @@ -21,7 +21,7 @@ const OPERATION_LABELS: Record = { /** How many trailing log lines to surface as the failure reason. */ const LOG_TAIL_LINES = 10; -function isSucceeded(run: ActorRun): boolean { +function isSucceeded(run: Run): boolean { return run.status === ACTOR_JOB_STATUSES.SUCCEEDED; } @@ -30,7 +30,7 @@ function isSucceeded(run: ActorRun): boolean { * callers (CI, shell chains, agents) can tell a started run from a successful one. * Failed runs propagate the Actor's own exit code when present (mirroring `apify run`). */ -export function getRunExitCode(run: ActorRun): number { +export function getRunExitCode(run: Run): number { switch (run.status) { case ACTOR_JOB_STATUSES.SUCCEEDED: return 0; @@ -46,7 +46,7 @@ export function getRunExitCode(run: ActorRun): number { } /** A generic, status-specific reason used when the platform did not provide a status message. */ -function genericReason(run: ActorRun): string { +function genericReason(run: Run): string { switch (run.status) { case ACTOR_JOB_STATUSES.ABORTED: case ACTOR_JOB_STATUSES.ABORTING: @@ -63,7 +63,7 @@ function genericReason(run: ActorRun): string { * Fetches the last few log lines of a finished run to explain a failure. Returns an empty * array on success or when the log cannot be retrieved (best-effort, never throws). */ -export async function fetchRunLogTail(apifyClient: ApifyClient, run: ActorRun): Promise { +export async function fetchRunLogTail(apifyClient: ApifyClient, run: Run): Promise { if (isSucceeded(run)) { return []; } @@ -72,7 +72,7 @@ export async function fetchRunLogTail(apifyClient: ApifyClient, run: ActorRun): } export interface RunResultOptions { - run: ActorRun; + run: Run; operation: RunResultOperation; logTail: string[]; } @@ -157,7 +157,7 @@ export function printRunResultSummary({ run, operation, logTail }: RunResultOpti export interface FinalizeRunOptions { apifyClient: ApifyClient; - run: ActorRun; + run: Run; operation: RunResultOperation; json: boolean; silent?: boolean; diff --git a/src/lib/commands/storages.ts b/src/lib/commands/storages.ts index 1fbd6cdc7..987df2e23 100644 --- a/src/lib/commands/storages.ts +++ b/src/lib/commands/storages.ts @@ -1,13 +1,19 @@ -import type { ApifyClient, Dataset, DatasetClient, KeyValueStore, KeyValueStoreClient } from 'apify-client'; +import type { + ApifyClient, + DatasetResource, + DatasetClient, + KeyValueStoreResource, + KeyValueStoreClient, +} from 'apify-client'; import { getCurrentUserInfo } from '../utils.js'; type ReturnTypeForStorage = T extends 'dataset' ? { - dataset: Dataset; + dataset: DatasetResource; datasetClient: DatasetClient; } - : { keyValueStore: KeyValueStore; keyValueStoreClient: KeyValueStoreClient }; + : { keyValueStore: KeyValueStoreResource; keyValueStoreClient: KeyValueStoreClient }; async function tryToGetStorage( client: ApifyClient, @@ -44,13 +50,13 @@ async function tryToGetStorage( export async function tryToGetDataset( client: ApifyClient, datasetId: string, -): Promise<{ dataset: Dataset; datasetClient: DatasetClient } | null> { +): Promise<{ dataset: DatasetResource; datasetClient: DatasetClient } | null> { return tryToGetStorage(client, datasetId, 'dataset'); } export async function tryToGetKeyValueStore( client: ApifyClient, keyValueStoreId: string, -): Promise<{ keyValueStore: KeyValueStore; keyValueStoreClient: KeyValueStoreClient } | null> { +): Promise<{ keyValueStore: KeyValueStoreResource; keyValueStoreClient: KeyValueStoreClient } | null> { return tryToGetStorage(client, keyValueStoreId, 'keyValueStore'); } diff --git a/src/lib/git-source/gitSource.ts b/src/lib/git-source/gitSource.ts index fcd7385cd..9f2c4eae5 100644 --- a/src/lib/git-source/gitSource.ts +++ b/src/lib/git-source/gitSource.ts @@ -111,7 +111,7 @@ export interface GitAccount { export const toGitAccount = ({ id, username, organizationOwnerUserId }: AuthJSON): GitAccount => ({ id, username, - organizationOwnerUserId, + organizationOwnerUserId: organizationOwnerUserId ?? undefined, }); /** diff --git a/src/lib/hooks/useRentalSunsetNotice.ts b/src/lib/hooks/useRentalSunsetNotice.ts index 52d5beb09..43afcab43 100644 --- a/src/lib/hooks/useRentalSunsetNotice.ts +++ b/src/lib/hooks/useRentalSunsetNotice.ts @@ -111,7 +111,7 @@ async function fetchRentalActorCount(username: string) { try { // axios rather than `fetch`, so the lookup honors HTTP_PROXY/HTTPS_PROXY/NO_PROXY like every - // other request the CLI makes - Node's global fetch ignores them. + // other request the CLI makes - Node's global fetch ignores them before 24.14. const { data } = await axios.get<{ data?: { total?: number } }>(url.href, { params: { username, diff --git a/src/lib/proxy.ts b/src/lib/proxy.ts new file mode 100644 index 000000000..7cb034d3d --- /dev/null +++ b/src/lib/proxy.ts @@ -0,0 +1,23 @@ +import http from 'node:http'; +import process from 'node:process'; + +const PROXY_ENV_VARS = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']; + +/** + * Sends the CLI's `fetch` requests, the Apify API client's included, through the proxy the environment names. + * Node.js older than 24.14 can't do that at runtime and needs `NODE_USE_ENV_PROXY=1`. Bun reads the variables itself. + */ +export function useProxyFromEnv( + env: NodeJS.ProcessEnv = process.env, + setGlobalProxyFromEnv: typeof http.setGlobalProxyFromEnv | undefined = http.setGlobalProxyFromEnv, +) { + if (!PROXY_ENV_VARS.some((name) => env[name])) return; + if (env.NODE_USE_ENV_PROXY === '1' || process.versions.bun) return; + if (!setGlobalProxyFromEnv) return; + + try { + setGlobalProxyFromEnv(env); + } catch { + // An unusable proxy URL fails the first request instead, with an error that names it. + } +} diff --git a/src/lib/runtime/client.ts b/src/lib/runtime/client.ts index 8baefb56b..3151aafaf 100644 --- a/src/lib/runtime/client.ts +++ b/src/lib/runtime/client.ts @@ -1,13 +1,10 @@ import process from 'node:process'; -import type { ApifyClientOptions } from 'apify-client'; -import axios from 'axios'; +import type { FetchFunction } from 'apify-client'; import { findRunningRuntimeEngine, runtimeApiUrl } from './docker.js'; import { configuredRuntimePorts, isConnectedToActorRuntime } from './target.js'; -type RequestInterceptor = NonNullable[number]; - export class ActorRuntimeNotRunningError extends Error { constructor(port: number) { super( @@ -29,19 +26,16 @@ export function targetsConnectedRuntime(baseUrl: string | undefined, env: NodeJS * Runs on every attempt of every request to the connected runtime. A refused connection triggers one * engine status check: a stopped container means a plain error, which apify-client doesn't retry, so * the command fails at once instead of after eight backoffs. A running container (still booting, or - * under load) rethrows the original axios error and keeps the client's normal retry policy. + * under load) rethrows the original fetch error and keeps the client's normal retry policy. */ -export const runtimeDownInterceptor: RequestInterceptor = (config) => { - const send = axios.getAdapter((config.adapter ?? axios.defaults.adapter) as never); - config.adapter = async (requestConfig) => { - try { - return await send(requestConfig); - } catch (err) { - if ((err as { code?: string }).code === 'ECONNREFUSED' && !(await findRunningRuntimeEngine())) { - throw new ActorRuntimeNotRunningError(configuredRuntimePorts().api); - } - throw err; +export const runtimeDownFetch: FetchFunction = async (input, init) => { + try { + return await fetch(input, init); + } catch (err) { + const code = ((err as Error).cause as { code?: string } | undefined)?.code; + if (code === 'ECONNREFUSED' && !(await findRunningRuntimeEngine())) { + throw new ActorRuntimeNotRunningError(configuredRuntimePorts().api); } - }; - return config; + throw err; + } }; diff --git a/src/lib/server-actor.ts b/src/lib/server-actor.ts index 129ffdcad..63b5c0cfa 100644 --- a/src/lib/server-actor.ts +++ b/src/lib/server-actor.ts @@ -1,6 +1,6 @@ import { setTimeout as delay } from 'node:timers/promises'; -import type { Actor, ApifyClient, Build } from 'apify-client'; +import type { ActorResource, ApifyClient, Build } from 'apify-client'; import { HTTP_METHODS } from './commands/http-request.js'; import { resolveActorContext } from './commands/resolve-actor-context.js'; @@ -20,9 +20,9 @@ const OPENAPI_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head' // apify-client 2.25.0 types omit `standbyUrl`, `actorStandby.tenancy`, the build's web server fields and // `buildNumber` on build list items; the API returns all of them. -type ActorWithServerFields = Actor & { +type ActorWithServerFields = ActorResource & { standbyUrl?: string | null; - actorStandby?: Actor['actorStandby'] & { tenancy?: string }; + actorStandby?: ActorResource['actorStandby'] & { tenancy?: string }; }; type ActorDefinitionWithServerFields = NonNullable & { @@ -38,7 +38,7 @@ export interface ServerActor { tenancy?: string; pricingModel?: string; buildRef?: string; - taggedBuilds: Actor['taggedBuilds']; + taggedBuilds: ActorResource['taggedBuilds']; standby: NonNullable; } @@ -102,7 +102,7 @@ function describeCallerCost(pricingModel: string | undefined): string { } /** Points callers of the input interface to the server interface; dual-mode Actors are legitimate, so it only informs. */ -export function getServerInterfaceHint(actor: Actor, userFriendlyId: string): string | undefined { +export function getServerInterfaceHint(actor: ActorResource, userFriendlyId: string): string | undefined { if (!actor.actorStandby?.isEnabled) { return undefined; } @@ -150,7 +150,7 @@ export async function resolveServerActor(client: ApifyClient, target: string | u standbyUrl: actor.standbyUrl, tenancy: actor.actorStandby.tenancy, pricingModel: getEffectivePricingModel(actor.pricingInfos), - buildRef: actor.actorStandby.build, + buildRef: actor.actorStandby.build ?? undefined, taggedBuilds: actor.taggedBuilds, standby: actor.actorStandby, }; diff --git a/src/lib/types.ts b/src/lib/types.ts index cbb83cd7d..81db21205 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -5,9 +5,9 @@ export interface AuthJSON { id?: string; username?: string; proxy?: { - password: string; + password?: string | null; }; - organizationOwnerUserId?: string; + organizationOwnerUserId?: string | null; } export function OverrideClassName(clazz: T): typeof BuiltApifyCommand { diff --git a/src/lib/utils.ts b/src/lib/utils.ts index cbf925200..c441a085a 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -12,13 +12,14 @@ import { mkdir, readFile } from 'node:fs/promises'; import { homedir } from 'node:os'; import { dirname, join, relative, resolve, sep } from 'node:path'; import process from 'node:process'; +import { Readable } from 'node:stream'; import { finished } from 'node:stream/promises'; import { DurationFormatter as SapphireDurationFormatter, TimeTypes } from '@sapphire/duration'; import { Timestamp } from '@sapphire/timestamp'; import AdmZip from 'adm-zip'; import _Ajv2019 from 'ajv/dist/2019.js'; -import { type ActorRun, ApifyClient, type Build } from 'apify-client'; +import type { ApifyClient, Build, Run } from 'apify-client'; import { ZipArchive } from 'archiver'; import axios from 'axios'; import escapeStringRegexp from 'escape-string-regexp'; @@ -43,6 +44,7 @@ import { import { lookUpActiveProfile, lookUpProfile } from './auth-file.js'; import { + createApifyClient, describeAuthFailure, getAnonymousApifyClientOptions, getApifyClientOptionsForToken, @@ -164,7 +166,7 @@ async function getLoggedClient(): Promise<{ client: ApifyClient | null; auth?: R const auth = await resolveAuth(); if (!auth) return { client: null }; - const apifyClient = new ApifyClient(getApifyClientOptionsForToken(auth.token)); + const apifyClient = createApifyClient(getApifyClientOptionsForToken(auth.token)); try { const userInfo = (await apifyClient.user('me').get()) as AuthJSON; @@ -188,10 +190,11 @@ export async function getCurrentUserInfo(): Promise { if (cachedUserInfo?.token === auth.token) return cachedUserInfo.userInfo; if (auth.source !== 'env') return getLocalUserInfo(auth.profile?.id); - const apifyClient = new ApifyClient({ + const apifyClient = createApifyClient({ ...getApifyClientOptionsForToken(auth.token), maxRetries: 1, - timeoutSecs: 10, + timeoutShortSecs: 10, + timeoutMaxSecs: 10, }); const userInfo = (await apifyClient.user('me').get()) as AuthJSON; cachedUserInfo = { token: auth.token, userInfo }; @@ -684,12 +687,12 @@ export const outputJobLog = async ({ timeoutMillis, apifyClient, }: { - job: ActorRun | Build; + job: Run | Build; timeoutMillis?: number; apifyClient?: ApifyClient; }) => { const { id: logId, status } = job; - const client = apifyClient || new ApifyClient(getAnonymousApifyClientOptions()); + const client = apifyClient || createApifyClient(getAnonymousApifyClientOptions()); // In case job was already done just output log if (ACTOR_JOB_TERMINAL_STATUSES.includes(status as never)) { @@ -704,12 +707,14 @@ export const outputJobLog = async ({ } // In other case stream it to stderr - const stream = await client.log(logId).stream(); + const webStream = await client.log(logId).stream(); - if (!stream) { + if (!webStream) { return 'no-logs'; } + const stream = Readable.fromWeb(webStream); + return new Promise<'no-logs' | 'finished' | 'timeouts'>((resolve, reject) => { let nodeTimeout: NodeJS.Timeout | null = null; diff --git a/test/api/commands/builds/tags.test.ts b/test/api/commands/builds/tags.test.ts index 2c7999d74..a37f5c74c 100644 --- a/test/api/commands/builds/tags.test.ts +++ b/test/api/commands/builds/tags.test.ts @@ -1,4 +1,4 @@ -import type { Actor, Build } from 'apify-client'; +import type { ActorResource, Build } from 'apify-client'; import { testRunCommand } from '../../../../src/lib/command-framework/apify-command.js'; import { waitForBuildToFinish } from '../../../__setup__/build-utils.js'; @@ -19,7 +19,7 @@ const { lastLogMessage } = useConsoleSpy(); const TEST_TIMEOUT = 120_000; describe('[api] apify builds add-tag / remove-tag', () => { - let testActor: Actor; + let testActor: ActorResource; let testBuild: Build; beforeAll(async () => { diff --git a/test/local/commands/run-timeout-flag.test.ts b/test/local/commands/run-timeout-flag.test.ts index 1fd68ff18..d05327850 100644 --- a/test/local/commands/run-timeout-flag.test.ts +++ b/test/local/commands/run-timeout-flag.test.ts @@ -100,18 +100,18 @@ describe.each(commands)('$name --timeout', ({ command, args }) => { it('sends --timeout 0 as a zero timeout (no timeout), not as an omitted option', async () => { await testRunCommand(command as never, { ...args, flags_timeout: 0 } as never); - expect(sentRunOptions()).toMatchObject({ timeout: 0 }); + expect(sentRunOptions()).toMatchObject({ runTimeoutSecs: 0 }); }); it('sends a positive --timeout as is', async () => { await testRunCommand(command as never, { ...args, flags_timeout: 120 } as never); - expect(sentRunOptions()).toMatchObject({ timeout: 120 }); + expect(sentRunOptions()).toMatchObject({ runTimeoutSecs: 120 }); }); it("leaves the timeout to the Actor's default when the flag is omitted", async () => { await testRunCommand(command as never, { ...args } as never); - expect(sentRunOptions()).not.toHaveProperty('timeout'); + expect(sentRunOptions()).not.toHaveProperty('runTimeoutSecs'); }); }); diff --git a/test/local/lib/agent-output.test.ts b/test/local/lib/agent-output.test.ts index d344207ae..79d4aae06 100644 --- a/test/local/lib/agent-output.test.ts +++ b/test/local/lib/agent-output.test.ts @@ -1,4 +1,4 @@ -import type { ActorRun, ApifyClient, Build } from 'apify-client'; +import type { Run, ApifyClient, Build } from 'apify-client'; import { ACTOR_JOB_TYPES } from '@apify/consts'; @@ -11,9 +11,9 @@ import { import { CommandExitCodes } from '../../../src/lib/consts.js'; const makeBuild = (status: Build['status']): Build => ({ id: 'build123', status }) as Build; -const makeRun = (status: ActorRun['status']): ActorRun => ({ id: 'run123', status }) as ActorRun; +const makeRun = (status: Run['status']): Run => ({ id: 'run123', status }) as Run; -const fakeClient = ({ builds = [], runs = [] }: { builds?: (Build | undefined)[]; runs?: (ActorRun | undefined)[] }) => +const fakeClient = ({ builds = [], runs = [] }: { builds?: (Build | undefined)[]; runs?: (Run | undefined)[] }) => ({ build: () => ({ get: async () => builds.shift() }), run: () => ({ get: async () => runs.shift() }), diff --git a/test/local/lib/output-job-log.test.ts b/test/local/lib/output-job-log.test.ts index 61cebebd6..7d653079d 100644 --- a/test/local/lib/output-job-log.test.ts +++ b/test/local/lib/output-job-log.test.ts @@ -1,12 +1,10 @@ -import { Readable } from 'node:stream'; - import { ACTOR_JOB_STATUSES } from '@apify/consts'; import { outputJobLog } from '../../../src/lib/utils.js'; const runningJob = { id: 'job-id', status: ACTOR_JOB_STATUSES.RUNNING } as never; -function clientReturning(stream: Readable | undefined) { +function clientReturning(stream: ReadableStream | undefined) { return { log: () => ({ stream: async () => stream }) } as never; } @@ -15,16 +13,22 @@ describe('outputJobLog', () => { await expect(outputJobLog({ job: runningJob, apifyClient: clientReturning(undefined) })).resolves.toBe('no-logs'); }); - it('resolves when the stream closes without emitting end', async () => { - const stream = new Readable({ read() {} }); - setTimeout(() => stream.destroy(), 10); + it('resolves when the stream closes', async () => { + const stream = new ReadableStream({ + start(controller) { + setTimeout(() => controller.close(), 10); + }, + }); await expect(outputJobLog({ job: runningJob, apifyClient: clientReturning(stream) })).resolves.toBe('finished'); }); it('rejects when the stream errors', async () => { - const stream = new Readable({ read() {} }); - setTimeout(() => stream.destroy(new Error('socket hang up')), 10); + const stream = new ReadableStream({ + start(controller) { + setTimeout(() => controller.error(new Error('socket hang up')), 10); + }, + }); await expect(outputJobLog({ job: runningJob, apifyClient: clientReturning(stream) })).rejects.toThrow( 'socket hang up', @@ -32,7 +36,7 @@ describe('outputJobLog', () => { }); it('returns timeouts when the budget elapses first', async () => { - const stream = new Readable({ read() {} }); + const stream = new ReadableStream(); await expect( outputJobLog({ job: runningJob, apifyClient: clientReturning(stream), timeoutMillis: 10 }), diff --git a/test/local/lib/proxy.test.ts b/test/local/lib/proxy.test.ts new file mode 100644 index 000000000..f439fa0b1 --- /dev/null +++ b/test/local/lib/proxy.test.ts @@ -0,0 +1,36 @@ +import { useProxyFromEnv } from '../../../src/lib/proxy.js'; + +describe('useProxyFromEnv()', () => { + const setGlobalProxyFromEnv = vi.fn(() => () => {}); + + beforeEach(() => { + setGlobalProxyFromEnv.mockClear(); + }); + + it('turns the proxy on when the environment names one', () => { + const env = { https_proxy: 'http://proxy.example.com:3128' }; + useProxyFromEnv(env, setGlobalProxyFromEnv); + + expect(setGlobalProxyFromEnv).toHaveBeenCalledExactlyOnceWith(env); + }); + + it('does nothing without a proxy variable', () => { + useProxyFromEnv({ NO_PROXY: 'localhost' }, setGlobalProxyFromEnv); + + expect(setGlobalProxyFromEnv).not.toHaveBeenCalled(); + }); + + it('leaves it to Node.js when NODE_USE_ENV_PROXY is set', () => { + useProxyFromEnv({ HTTP_PROXY: 'http://proxy.example.com:3128', NODE_USE_ENV_PROXY: '1' }, setGlobalProxyFromEnv); + + expect(setGlobalProxyFromEnv).not.toHaveBeenCalled(); + }); + + it('ignores a proxy URL that Node.js rejects', () => { + setGlobalProxyFromEnv.mockImplementationOnce(() => { + throw new TypeError('Invalid URL'); + }); + + expect(() => useProxyFromEnv({ HTTP_PROXY: 'not a url' }, setGlobalProxyFromEnv)).not.toThrow(); + }); +}); diff --git a/test/local/lib/run-result.test.ts b/test/local/lib/run-result.test.ts index 6b837152d..2afd159d9 100644 --- a/test/local/lib/run-result.test.ts +++ b/test/local/lib/run-result.test.ts @@ -1,4 +1,4 @@ -import type { ActorRun, ApifyClient } from 'apify-client'; +import type { Run, ApifyClient } from 'apify-client'; import { buildRunResultJson, @@ -8,7 +8,7 @@ import { printRunResultSummary, } from '../../../src/lib/commands/run-result.js'; -const makeRun = (overrides: Partial = {}): ActorRun => +const makeRun = (overrides: Partial = {}): Run => ({ id: 'run123', actId: 'actor456', @@ -17,7 +17,7 @@ const makeRun = (overrides: Partial = {}): ActorRun => defaultDatasetId: 'dataset789', defaultKeyValueStoreId: 'kvs012', ...overrides, - }) as ActorRun; + }) as Run; const fakeClientWithLog = (log: string | undefined) => ({ diff --git a/test/local/lib/runtime-client.test.ts b/test/local/lib/runtime-client.test.ts index 3441aa978..516b80b5c 100644 --- a/test/local/lib/runtime-client.test.ts +++ b/test/local/lib/runtime-client.test.ts @@ -1,14 +1,8 @@ import { createServer } from 'node:net'; import process from 'node:process'; -import { ApifyClient } from 'apify-client'; - -import { getAnonymousApifyClientOptions } from '../../../src/lib/auth.js'; -import { - ActorRuntimeNotRunningError, - runtimeDownInterceptor, - targetsConnectedRuntime, -} from '../../../src/lib/runtime/client.js'; +import { createApifyClient, getAnonymousApifyClientOptions } from '../../../src/lib/auth.js'; +import { ActorRuntimeNotRunningError, targetsConnectedRuntime } from '../../../src/lib/runtime/client.js'; import { updateActorRuntimeConfig } from '../../../src/lib/runtime/config.js'; import * as docker from '../../../src/lib/runtime/docker.js'; import { setConnectedToActorRuntime } from '../../../src/lib/runtime/target.js'; @@ -56,29 +50,21 @@ describe('runtime/client', () => { }); }); - describe('getAnonymousApifyClientOptions()', () => { - it('adds the runtime interceptor only while connected', () => { - expect(getAnonymousApifyClientOptions().requestInterceptors).toHaveLength(1); + describe('createApifyClient()', () => { + it('checks the runtime engine only while connected', async () => { + const baseUrl = `http://localhost:${await freePort()}`; + const client = createApifyClient({ ...getAnonymousApifyClientOptions(baseUrl), maxRetries: 0 }); - setConnectedToActorRuntime(true); - expect(getAnonymousApifyClientOptions().requestInterceptors).toContain(runtimeDownInterceptor); - expect(getAnonymousApifyClientOptions('http://localhost:3333').requestInterceptors).toContain( - runtimeDownInterceptor, - ); - expect(getAnonymousApifyClientOptions('https://api.apify.com').requestInterceptors).toHaveLength(1); - - process.env.APIFY_CLIENT_BASE_URL = 'http://localhost:9999'; - expect(getAnonymousApifyClientOptions().requestInterceptors).toHaveLength(1); + await expect(client.user('me').get()).rejects.toMatchObject({ cause: { code: 'ECONNREFUSED' } }); + expect(findRunningRuntimeEngine).not.toHaveBeenCalled(); }); - }); - describe('runtimeDownInterceptor', () => { it('fails at once when the connection is refused and the runtime container is not running', async () => { setConnectedToActorRuntime(true); updateActorRuntimeConfig({ apiPort: await freePort() }); findRunningRuntimeEngine.mockResolvedValue(null); - const client = new ApifyClient({ ...getAnonymousApifyClientOptions(), token: 'local-dev-token' }); + const client = createApifyClient({ ...getAnonymousApifyClientOptions(), token: 'local-dev-token' }); const started = Date.now(); await expect(client.user('me').get()).rejects.toBeInstanceOf(ActorRuntimeNotRunningError); @@ -91,14 +77,14 @@ describe('runtime/client', () => { updateActorRuntimeConfig({ apiPort: await freePort() }); findRunningRuntimeEngine.mockResolvedValue('docker'); - const client = new ApifyClient({ + const client = createApifyClient({ ...getAnonymousApifyClientOptions(), token: 'local-dev-token', maxRetries: 2, minDelayBetweenRetriesMillis: 10, }); - await expect(client.user('me').get()).rejects.toMatchObject({ code: 'ECONNREFUSED' }); + await expect(client.user('me').get()).rejects.toMatchObject({ cause: { code: 'ECONNREFUSED' } }); expect(findRunningRuntimeEngine).toHaveBeenCalledTimes(3); }); }); diff --git a/test/local/lib/server-actor.test.ts b/test/local/lib/server-actor.test.ts index 267aa0c61..3ad1e00a9 100644 --- a/test/local/lib/server-actor.test.ts +++ b/test/local/lib/server-actor.test.ts @@ -1,7 +1,7 @@ import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; -import type { Actor, ApifyClient, Build } from 'apify-client'; +import type { ActorResource, ApifyClient, Build } from 'apify-client'; import type { ServerActor } from '../../../src/lib/server-actor.js'; import { @@ -262,13 +262,13 @@ describe('server-actor', () => { describe('getServerInterfaceHint()', () => { it('points to apify server request for an Actor with a server interface', () => { - const actor = { actorStandby: { isEnabled: true } } as Actor; + const actor = { actorStandby: { isEnabled: true } } as ActorResource; expect(getServerInterfaceHint(actor, 'apify/web-fetch')).toContain('apify server request apify/web-fetch'); }); it('gives no hint for an Actor without one', () => { - expect(getServerInterfaceHint({} as Actor, 'apify/hello-world')).toBeUndefined(); + expect(getServerInterfaceHint({} as ActorResource, 'apify/hello-world')).toBeUndefined(); }); });