apify-client 3.0.0-beta.1 → 3.0.0-beta.100

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 (131) hide show
  1. package/README.md +21 -5
  2. package/dist/apify_api_error.d.ts +64 -22
  3. package/dist/apify_api_error.js +100 -30
  4. package/dist/apify_client.d.ts +150 -35
  5. package/dist/apify_client.js +198 -118
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/base/api_client.d.ts +9 -9
  9. package/dist/base/api_client.js +41 -45
  10. package/dist/base/resource_client.d.ts +24 -10
  11. package/dist/base/resource_client.js +78 -48
  12. package/dist/base/resource_collection_client.d.ts +15 -6
  13. package/dist/base/resource_collection_client.js +40 -21
  14. package/dist/body_parser.d.ts +3 -4
  15. package/dist/body_parser.js +20 -32
  16. package/dist/bundle.js +47 -52
  17. package/dist/bundle.js.map +1 -1
  18. package/dist/generated/api.d.ts +3363 -1185
  19. package/dist/generated/api.js +1 -2
  20. package/dist/generated/schemas.d.ts +8146 -0
  21. package/dist/generated/schemas.js +1866 -0
  22. package/dist/http_clients/axios.d.ts +61 -0
  23. package/dist/http_clients/axios.js +119 -0
  24. package/dist/http_clients/base.d.ts +391 -0
  25. package/dist/http_clients/base.js +650 -0
  26. package/dist/http_clients/index.d.ts +4 -0
  27. package/dist/http_clients/index.js +2 -0
  28. package/dist/http_compressors/base.d.ts +40 -0
  29. package/dist/http_compressors/base.js +9 -0
  30. package/dist/http_compressors/brotli.d.ts +33 -0
  31. package/dist/http_compressors/brotli.js +39 -0
  32. package/dist/http_compressors/gzip.d.ts +33 -0
  33. package/dist/http_compressors/gzip.js +39 -0
  34. package/dist/http_compressors/index.d.ts +8 -0
  35. package/dist/http_compressors/index.js +3 -0
  36. package/dist/http_compressors/resolve.d.ts +24 -0
  37. package/dist/http_compressors/resolve.js +30 -0
  38. package/dist/http_compressors/zstd.d.ts +34 -0
  39. package/dist/http_compressors/zstd.js +43 -0
  40. package/dist/index.d.ts +38 -32
  41. package/dist/index.js +36 -36
  42. package/dist/invalid_response_body_error.d.ts +14 -0
  43. package/dist/invalid_response_body_error.js +18 -0
  44. package/dist/lazy_schema.d.ts +8 -0
  45. package/dist/lazy_schema.js +11 -0
  46. package/dist/models.d.ts +196 -278
  47. package/dist/models.js +14 -15
  48. package/dist/resource_clients/actor.d.ts +115 -45
  49. package/dist/resource_clients/actor.js +187 -116
  50. package/dist/resource_clients/actor_collection.d.ts +21 -17
  51. package/dist/resource_clients/actor_collection.js +26 -21
  52. package/dist/resource_clients/actor_env_var.d.ts +13 -6
  53. package/dist/resource_clients/actor_env_var.js +21 -14
  54. package/dist/resource_clients/actor_env_var_collection.d.ts +18 -22
  55. package/dist/resource_clients/actor_env_var_collection.js +23 -20
  56. package/dist/resource_clients/actor_server.d.ts +149 -0
  57. package/dist/resource_clients/actor_server.js +199 -0
  58. package/dist/resource_clients/actor_version.d.ts +30 -10
  59. package/dist/resource_clients/actor_version.js +29 -23
  60. package/dist/resource_clients/actor_version_collection.d.ts +20 -21
  61. package/dist/resource_clients/actor_version_collection.js +25 -20
  62. package/dist/resource_clients/build.d.ts +24 -11
  63. package/dist/resource_clients/build.js +43 -26
  64. package/dist/resource_clients/build_collection.d.ts +10 -8
  65. package/dist/resource_clients/build_collection.js +13 -13
  66. package/dist/resource_clients/dataset.d.ts +87 -40
  67. package/dist/resource_clients/dataset.js +159 -175
  68. package/dist/resource_clients/dataset_collection.d.ts +13 -9
  69. package/dist/resource_clients/dataset_collection.js +29 -21
  70. package/dist/resource_clients/key_value_store.d.ts +110 -28
  71. package/dist/resource_clients/key_value_store.js +177 -99
  72. package/dist/resource_clients/key_value_store_collection.d.ts +13 -9
  73. package/dist/resource_clients/key_value_store_collection.js +29 -21
  74. package/dist/resource_clients/log.d.ts +42 -23
  75. package/dist/resource_clients/log.js +156 -85
  76. package/dist/resource_clients/request_queue.d.ts +77 -38
  77. package/dist/resource_clients/request_queue.js +251 -172
  78. package/dist/resource_clients/request_queue_collection.d.ts +12 -8
  79. package/dist/resource_clients/request_queue_collection.js +23 -20
  80. package/dist/resource_clients/run.d.ts +134 -34
  81. package/dist/resource_clients/run.js +225 -84
  82. package/dist/resource_clients/run_collection.d.ts +8 -6
  83. package/dist/resource_clients/run_collection.js +18 -18
  84. package/dist/resource_clients/schedule.d.ts +20 -11
  85. package/dist/resource_clients/schedule.js +36 -30
  86. package/dist/resource_clients/schedule_collection.d.ts +10 -6
  87. package/dist/resource_clients/schedule_collection.js +20 -17
  88. package/dist/resource_clients/store_collection.d.ts +9 -7
  89. package/dist/resource_clients/store_collection.js +18 -18
  90. package/dist/resource_clients/task.d.ts +44 -21
  91. package/dist/resource_clients/task.js +116 -86
  92. package/dist/resource_clients/task_collection.d.ts +13 -9
  93. package/dist/resource_clients/task_collection.js +19 -16
  94. package/dist/resource_clients/user.d.ts +22 -13
  95. package/dist/resource_clients/user.js +46 -47
  96. package/dist/resource_clients/webhook.d.ts +21 -12
  97. package/dist/resource_clients/webhook.js +35 -30
  98. package/dist/resource_clients/webhook_collection.d.ts +11 -7
  99. package/dist/resource_clients/webhook_collection.js +20 -17
  100. package/dist/resource_clients/webhook_dispatch.d.ts +9 -6
  101. package/dist/resource_clients/webhook_dispatch.js +11 -10
  102. package/dist/resource_clients/webhook_dispatch_collection.d.ts +7 -5
  103. package/dist/resource_clients/webhook_dispatch_collection.js +13 -13
  104. package/dist/response_validation_error.d.ts +27 -0
  105. package/dist/response_validation_error.js +38 -0
  106. package/dist/runtime/node.d.ts +6 -0
  107. package/dist/runtime/node.js +87 -0
  108. package/dist/runtime/types.d.ts +60 -0
  109. package/dist/runtime/types.js +1 -0
  110. package/dist/runtime/web.d.ts +5 -0
  111. package/dist/runtime/web.js +21 -0
  112. package/dist/schemas.d.ts +381 -0
  113. package/dist/schemas.js +37 -0
  114. package/dist/statistics.d.ts +1 -6
  115. package/dist/statistics.js +7 -11
  116. package/dist/timeouts.d.ts +84 -0
  117. package/dist/timeouts.js +37 -0
  118. package/dist/timezones.d.ts +1 -1
  119. package/dist/timezones.js +1 -2
  120. package/dist/utils.d.ts +99 -70
  121. package/dist/utils.js +251 -229
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +48 -47
  125. package/dist/argument_validation_error.d.ts +0 -17
  126. package/dist/argument_validation_error.js +0 -157
  127. package/dist/http_client.d.ts +0 -88
  128. package/dist/http_client.js +0 -260
  129. package/dist/index.mjs +0 -42
  130. package/dist/interceptors.d.ts +0 -19
  131. package/dist/interceptors.js +0 -110
package/package.json CHANGED
@@ -1,23 +1,28 @@
1
1
  {
2
2
  "name": "apify-client",
3
- "version": "3.0.0-beta.1",
3
+ "version": "3.0.0-beta.100",
4
4
  "description": "Apify API client for JavaScript",
5
5
  "engines": {
6
- "node": ">=22.0.0"
6
+ "node": ">=22.15.0"
7
7
  },
8
+ "type": "module",
8
9
  "main": "dist/index.js",
9
- "module": "dist/index.mjs",
10
10
  "types": "dist/index.d.ts",
11
11
  "browser": "dist/bundle.js",
12
12
  "unpkg": "dist/bundle.js",
13
+ "imports": {
14
+ "#runtime": {
15
+ "node": "./dist/runtime/node.js",
16
+ "default": "./dist/runtime/web.js"
17
+ }
18
+ },
13
19
  "exports": {
14
20
  "./package.json": "./package.json",
15
21
  "./browser": "./dist/bundle.js",
16
22
  ".": {
17
- "import": "./dist/index.mjs",
18
- "require": "./dist/index.js",
19
23
  "types": "./dist/index.d.ts",
20
- "browser": "./dist/bundle.js"
24
+ "browser": "./dist/bundle.js",
25
+ "default": "./dist/index.js"
21
26
  }
22
27
  },
23
28
  "keywords": [
@@ -54,64 +59,59 @@
54
59
  ],
55
60
  "apify": {
56
61
  "openapiSpec": {
57
- "version": "v2-2026-08-03T111309Z"
62
+ "version": "v2-2026-11-09T143926Z"
58
63
  }
59
64
  },
60
65
  "dependencies": {
61
- "@apify/consts": "^2.50.0",
62
- "@apify/log": "^2.2.6",
63
- "@apify/utilities": "^2.23.2",
64
- "@crawlee/types": "^3.3.0",
65
- "ansi-colors": "^4.1.1",
66
- "async-retry": "^1.3.3",
67
- "axios": "^1.16.0",
68
- "content-type": "^1.0.5",
69
- "proxy-agent": "^6.5.0",
70
- "tslib": "^2.5.0",
71
- "type-fest": "^4.0.0",
72
- "zod": "^4.0.0"
66
+ "@apify/consts": "^3.0.1",
67
+ "@apify/log": "^3.0.1",
68
+ "@apify/utilities": "^3.1.0",
69
+ "@apify/validations": "^1.1.2",
70
+ "ansi-colors": "^4.1.3",
71
+ "axios": "^1.21.0",
72
+ "content-type": "^3.1.1",
73
+ "proxy-agent": "^8.0.2",
74
+ "tslib": "^2.9.1",
75
+ "type-fest": "^5.10.0",
76
+ "zod": "^4.6.7"
73
77
  },
74
78
  "devDependencies": {
75
79
  "@apify/oxlint-config": "^0.3.0",
76
80
  "@apify/tsconfig": "^0.2.0",
77
- "@crawlee/puppeteer": "^3.2.2",
78
- "@rsbuild/core": "^2.0.0",
79
- "@rsbuild/plugin-node-polyfill": "^1.3.0",
80
- "@rspack/cli": "^2.0.0",
81
- "@rspack/core": "^2.0.0",
82
- "@types/async-retry": "^1.4.5",
81
+ "@crawlee/puppeteer": "4.0.0-rc.2",
82
+ "@rsbuild/core": "^2.3.1",
83
+ "@rsbuild/plugin-node-polyfill": "^1.4.6",
84
+ "@rspack/cli": "^2.3.1",
85
+ "@rspack/core": "^2.3.1",
83
86
  "@types/compression": "^1.8.1",
84
- "@types/content-type": "^1.1.5",
85
- "@types/express": "^5.0.0",
86
- "@types/node": "^24.0.0",
87
- "ajv": "^8.17.1",
88
- "body-parser": "^2.0.0",
89
- "compression": "^1.7.4",
87
+ "@types/express": "^5.0.6",
88
+ "@types/node": "^26.6.6",
89
+ "ajv": "^8.20.0",
90
+ "body-parser": "^2.4.0",
91
+ "compression": "^1.8.2",
90
92
  "esbuild": "0.28.2",
91
- "express": "^5.0.0",
92
- "gen-esm-wrapper": "^1.1.2",
93
- "openapi-typescript": "7.13.0",
94
- "oxfmt": "0.65.0",
95
- "oxlint": "1.79.0",
96
- "oxlint-tsgolint": "7.0.2001",
97
- "puppeteer": "^25.0.0",
98
- "rimraf": "^6.0.0",
99
- "rolldown": "^1.0.0-rc.4",
100
- "typescript": "^6.0.0",
101
- "vitest": "^4.0.16",
102
- "webpack": "^5.105.2",
103
- "webpack-cli": "^7.0.0"
93
+ "express": "^5.3.0",
94
+ "oxfmt": "0.77.0",
95
+ "oxlint": "1.93.0",
96
+ "oxlint-tsgolint": "7.0.2006",
97
+ "puppeteer": "^25.16.0",
98
+ "rimraf": "^6.1.4",
99
+ "rolldown": "^1.2.16",
100
+ "typescript": "^7.0.2",
101
+ "typescript-v6": "npm:typescript@^6.0.3",
102
+ "vitest": "^5.1.0",
103
+ "webpack": "^5.112.2",
104
+ "webpack-cli": "^7.3.1"
104
105
  },
105
106
  "devEngines": {
106
107
  "packageManager": {
107
108
  "name": "pnpm",
108
- "version": "10.33.4",
109
+ "version": "12.18.0",
109
110
  "onFail": "warn"
110
111
  }
111
112
  },
112
113
  "scripts": {
113
114
  "build": "pnpm clean && pnpm build:node && pnpm build:browser",
114
- "postbuild": "gen-esm-wrapper dist/index.js dist/index.mjs",
115
115
  "clean": "rimraf dist tsconfig.tsbuildinfo",
116
116
  "test": "pnpm build && vitest run --project unit",
117
117
  "test:integration": "vitest run --project integration",
@@ -121,6 +121,7 @@
121
121
  "lint:fix": "oxlint --type-aware --fix",
122
122
  "tsc-check-tests": "tsc --noEmit --project test/tsconfig.json",
123
123
  "tsc-check-scripts": "tsc --noEmit --project tsconfig.scripts.json",
124
+ "tsc-check-docs": "tsc --noEmit --project docs/tsconfig.json",
124
125
  "format": "oxfmt",
125
126
  "format:check": "oxfmt --check",
126
127
  "api:extract": "pnpm build && pnpm dlx github:apify/api-extractor-report --packages=. --extract-command='pnpm api:extract'",
@@ -128,6 +129,6 @@
128
129
  "build:node": "tsc",
129
130
  "build:browser": "rsbuild build",
130
131
  "spec:fetch": "node scripts/openapi_spec.mts fetch",
131
- "generate:types": "node scripts/openapi_spec.mts fetch && node scripts/generate_types.mts && node scripts/openapi_spec.mts record-version"
132
+ "generate:models": "node scripts/openapi_spec.mts fetch && node scripts/generate_types.mts && node scripts/generate_schemas.mts && node scripts/openapi_spec.mts record-version"
132
133
  }
133
134
  }
@@ -1,17 +0,0 @@
1
- import type { z } from 'zod';
2
- /**
3
- * Thrown when an argument fails schema validation.
4
- *
5
- * Its `message` is a human-readable sentence naming the offending field and the
6
- * value it received (rather than a raw JSON dump). The structured
7
- * {@link https://zod.dev | zod} issues are available on `issues`, and the
8
- * original `ZodError` on `cause`, for programmatic inspection.
9
- *
10
- * `apify-client` sits below `@crawlee/core` and the Apify SDK in the dependency
11
- * graph, so it defines its own error type rather than importing one from them.
12
- */
13
- export declare class ArgumentValidationError extends Error {
14
- /** Structured issues from the underlying schema check. */
15
- readonly issues: z.ZodError['issues'];
16
- constructor(error: z.ZodError, value: unknown, label?: string);
17
- }
@@ -1,157 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ArgumentValidationError = void 0;
4
- /** Formats a zod issue path like `groups[0]` or `countryCode`. */
5
- function formatIssuePath(path) {
6
- let out = '';
7
- for (const key of path) {
8
- if (typeof key === 'number')
9
- out += `[${key}]`;
10
- else
11
- out += out ? `.${String(key)}` : String(key);
12
- }
13
- return out;
14
- }
15
- /** Reads the value at `path` from the validated input, to include in the error. */
16
- function valueAtPath(root, path) {
17
- let current = root;
18
- for (const key of path) {
19
- if (current === null || typeof current !== 'object')
20
- return undefined;
21
- current = current[key];
22
- }
23
- return current;
24
- }
25
- /**
26
- * How much of a received string the message renders. A rejected argument can be arbitrarily large - a
27
- * whole JSON payload passed where an object was expected - and its full text would swamp the message.
28
- */
29
- const MAX_RECEIVED_STRING_LENGTH = 80;
30
- /** Renders a primitive received value for an error; skips objects/Dates (noisy). */
31
- function describeReceived(value) {
32
- switch (typeof value) {
33
- case 'string':
34
- // An empty string would render as bare backticks - make it visible.
35
- if (value === '')
36
- return "''";
37
- return value.length > MAX_RECEIVED_STRING_LENGTH
38
- ? `${value.slice(0, MAX_RECEIVED_STRING_LENGTH)}...`
39
- : value;
40
- case 'number':
41
- case 'boolean':
42
- return String(value);
43
- case 'bigint':
44
- // Keep the `n` suffix, so a rejected bigint is not mistaken for a number.
45
- return `${value}n`;
46
- default:
47
- return undefined;
48
- }
49
- }
50
- /**
51
- * Renders the issue's own sentence, except where zod's contradicts itself: a value of the expected type
52
- * that fails that type's implicit constraint is still reported as the wrong *type*, giving "expected
53
- * number, received number" for `Infinity` / `NaN` and "expected date, received Date" for an invalid
54
- * `Date`. Name the constraint that actually failed instead.
55
- */
56
- function describeIssue(issue, value) {
57
- if (issue.code === 'invalid_type') {
58
- if (issue.expected === 'number' && typeof value === 'number') {
59
- return 'Invalid input: expected a finite number';
60
- }
61
- // A tag check, not `instanceof`, so a `Date` from another realm is named too.
62
- if (issue.expected === 'date' && Object.prototype.toString.call(value) === '[object Date]') {
63
- return 'Invalid input: expected a valid date';
64
- }
65
- }
66
- return issue.message;
67
- }
68
- /**
69
- * How many issue lines the message renders, before a closing "... and N more" line. Validating a
70
- * large array - a dataset push, a request batch - can fail on every element, and rendering all of
71
- * them would make the message megabytes long. The full set stays on `issues` either way.
72
- */
73
- const MAX_RENDERED_LINES = 10;
74
- /**
75
- * How deep into the value the lines for `issue` would sit, as a path length. Computed without
76
- * rendering anything, so a union can weigh its arms before any string is built.
77
- */
78
- function deepestIssueDepth(issue, baseDepth) {
79
- const depth = baseDepth + issue.path.length;
80
- if (issue.code === 'invalid_union') {
81
- let deepest = -1;
82
- for (const arm of issue.errors) {
83
- for (const nested of arm)
84
- deepest = Math.max(deepest, deepestIssueDepth(nested, depth));
85
- }
86
- return deepest;
87
- }
88
- return depth;
89
- }
90
- /** Collects one line per issue into `lines`; a union expands into a line per deepest-failing arm. */
91
- function collectIssueLines(issue, root, basePath, lines, counter) {
92
- const path = [...basePath, ...issue.path];
93
- // A union's own message is a bare "Invalid input" - the useful part is in `errors`,
94
- // whose paths are relative to the union, hence passing `path` down as the base.
95
- if (issue.code === 'invalid_union') {
96
- // Only the arms that reached deepest are reported. An arm that failed nearer the root rejected a
97
- // shape the value never had - for `[{ ok: 1 }, 2]` against `object | string | array`, the object
98
- // and string arms fail on the whole array, and only the array arm can point at `[1]`. When every
99
- // arm fails at the same depth, as for an argument of an outright wrong type, they are all kept.
100
- const armDepths = issue.errors.map((arm) => arm.reduce((deepest, nested) => Math.max(deepest, deepestIssueDepth(nested, path.length)), -1));
101
- const deepest = Math.max(...armDepths);
102
- for (const [index, arm] of issue.errors.entries()) {
103
- if (armDepths[index] !== deepest)
104
- continue;
105
- for (const nested of arm)
106
- collectIssueLines(nested, root, path, lines, counter);
107
- }
108
- return;
109
- }
110
- counter.total += 1;
111
- if (lines.length >= MAX_RENDERED_LINES)
112
- return;
113
- const location = path.length ? ` at \`${formatIssuePath(path)}\`` : '';
114
- const value = valueAtPath(root, path);
115
- const received = describeReceived(value);
116
- const got = received === undefined ? '' : `, got \`${received}\``;
117
- lines.push(`${describeIssue(issue, value)}${location}${got}`);
118
- }
119
- /**
120
- * Formats a `ZodError` as a plain, human-readable message that names the
121
- * offending field *and* the value it received (e.g. ``must match pattern
122
- * /^[A-Z]{2}$/ at `countryCode`, got `CZE` ``) - closer to the old `ow` errors
123
- * than zod's default, which omits the received value.
124
- */
125
- function formatZodError(error, root, label) {
126
- const lines = [];
127
- const counter = { total: 0 };
128
- for (const issue of error.issues)
129
- collectIssueLines(issue, root, [], lines, counter);
130
- // The label names the validated interface, the way ow's errors ended with "in object `X`".
131
- const rendered = label ? lines.map((line) => `${line} in \`${label}\``) : [...lines];
132
- const hidden = counter.total - lines.length;
133
- if (hidden > 0)
134
- rendered.push(`... and ${hidden} more problem${hidden === 1 ? '' : 's'}`);
135
- return rendered.join('\n');
136
- }
137
- /**
138
- * Thrown when an argument fails schema validation.
139
- *
140
- * Its `message` is a human-readable sentence naming the offending field and the
141
- * value it received (rather than a raw JSON dump). The structured
142
- * {@link https://zod.dev | zod} issues are available on `issues`, and the
143
- * original `ZodError` on `cause`, for programmatic inspection.
144
- *
145
- * `apify-client` sits below `@crawlee/core` and the Apify SDK in the dependency
146
- * graph, so it defines its own error type rather than importing one from them.
147
- */
148
- class ArgumentValidationError extends Error {
149
- /** Structured issues from the underlying schema check. */
150
- issues;
151
- constructor(error, value, label) {
152
- super(formatZodError(error, value, label), { cause: error });
153
- this.name = 'ArgumentValidationError';
154
- this.issues = error.issues;
155
- }
156
- }
157
- exports.ArgumentValidationError = ArgumentValidationError;
@@ -1,88 +0,0 @@
1
- import type http from 'node:http';
2
- import type https from 'node:https';
3
- import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
4
- import type { Log } from '@apify/log';
5
- import type { RequestInterceptorFunction } from './interceptors';
6
- import type { Statistics } from './statistics';
7
- export declare class HttpClient {
8
- stats: Statistics;
9
- maxRetries: number;
10
- minDelayBetweenRetriesMillis: number;
11
- userProvidedRequestInterceptors: RequestInterceptorFunction[];
12
- logger: Log;
13
- timeoutMillis: number;
14
- httpAgent?: http.Agent;
15
- httpsAgent?: https.Agent;
16
- axios: AxiosInstance;
17
- workflowKey?: string;
18
- private nodeInitPromise?;
19
- private userAgentSuffix?;
20
- constructor(options: HttpClientOptions);
21
- private ensureNodeInit;
22
- private initNode;
23
- call<T = any>(config: ApifyRequestConfig): Promise<ApifyResponse<T>>;
24
- private _informAboutStreamNoRetry;
25
- /**
26
- * Successful responses are returned, errors and unsuccessful
27
- * status codes are retried. See the following functions for the
28
- * retrying logic.
29
- */
30
- private _createRequestHandler;
31
- private _isStatusOk;
32
- /**
33
- * Handles all unexpected errors that can happen, but are not
34
- * Apify API typed errors. E.g. network errors, timeouts and so on.
35
- */
36
- private _handleRequestError;
37
- /**
38
- * Axios calls req.abort() on timeouts so timeout errors will
39
- * have a code ECONNABORTED.
40
- */
41
- private _isTimeoutError;
42
- /**
43
- * We don't want to retry every exception thrown from Axios.
44
- * The common denominator for retryable errors are network issues.
45
- * @param {Error} err
46
- * @private
47
- */
48
- private _isRetryableError;
49
- /**
50
- * When a network connection to our API is interrupted in the middle of streaming
51
- * a response, the request often does not fail, but simply contains
52
- * an incomplete response. This can often be fixed by retrying.
53
- */
54
- private _isResponseBodyInvalid;
55
- /**
56
- * When a network request is attempted by axios and fails,
57
- * it throws an AxiosError, which will have the request
58
- * and config (and other) properties.
59
- */
60
- private _isNetworkError;
61
- /**
62
- * We retry 429 (rate limit) and 500+.
63
- * For status codes 300-499 (except 429) we do not retry the request,
64
- * because it's probably caused by invalid url (redirect 3xx) or invalid user input (4xx).
65
- */
66
- private _isStatusCodeRetryable;
67
- private _onRequestRetry;
68
- }
69
- export interface ApifyRequestConfig extends AxiosRequestConfig {
70
- stringifyFunctions?: boolean;
71
- forceBuffer?: boolean;
72
- doNotRetryTimeouts?: boolean;
73
- }
74
- export interface ApifyResponse<T = any> extends AxiosResponse<T> {
75
- config: ApifyRequestConfig & InternalAxiosRequestConfig;
76
- }
77
- export interface HttpClientOptions {
78
- apifyClientStats: Statistics;
79
- maxRetries: number;
80
- minDelayBetweenRetriesMillis: number;
81
- requestInterceptors: RequestInterceptorFunction[];
82
- timeoutSecs: number;
83
- logger: Log;
84
- token?: string;
85
- workflowKey?: string;
86
- /** @internal */
87
- userAgentSuffix?: string | string[];
88
- }
@@ -1,260 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpClient = void 0;
4
- const tslib_1 = require("tslib");
5
- const async_retry_1 = tslib_1.__importDefault(require("async-retry"));
6
- const axios_1 = tslib_1.__importStar(require("axios"));
7
- const consts_1 = require("@apify/consts");
8
- const apify_api_error_1 = require("./apify_api_error");
9
- const interceptors_1 = require("./interceptors");
10
- const utils_1 = require("./utils");
11
- const { version } = (0, utils_1.getVersionData)();
12
- const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
13
- class HttpClient {
14
- stats;
15
- maxRetries;
16
- minDelayBetweenRetriesMillis;
17
- userProvidedRequestInterceptors;
18
- logger;
19
- timeoutMillis;
20
- httpAgent;
21
- httpsAgent;
22
- axios;
23
- workflowKey;
24
- nodeInitPromise;
25
- userAgentSuffix;
26
- constructor(options) {
27
- const { token } = options;
28
- this.stats = options.apifyClientStats;
29
- this.maxRetries = options.maxRetries;
30
- this.minDelayBetweenRetriesMillis = options.minDelayBetweenRetriesMillis;
31
- this.userProvidedRequestInterceptors = options.requestInterceptors;
32
- this.timeoutMillis = options.timeoutSecs * 1000;
33
- this.logger = options.logger;
34
- this.workflowKey = options.workflowKey || process.env[consts_1.APIFY_ENV_VARS.WORKFLOW_KEY];
35
- this.userAgentSuffix = options.userAgentSuffix;
36
- this._onRequestRetry = this._onRequestRetry.bind(this);
37
- this.axios = axios_1.default.create({
38
- // Disable axios's built-in proxy handling since we're using custom agents
39
- proxy: false,
40
- paramsSerializer: (params) => {
41
- const formattedParams = Object.entries(params)
42
- .filter(([, value]) => value !== undefined)
43
- .map(([key, value]) => {
44
- if (value instanceof Date) {
45
- return [key, value.toISOString()];
46
- }
47
- const updatedValue = typeof value === 'boolean' ? Number(value) : value;
48
- return [key, String(updatedValue)];
49
- });
50
- return new URLSearchParams(formattedParams).toString();
51
- },
52
- validateStatus: null,
53
- // Using interceptors for this functionality.
54
- transformRequest: undefined,
55
- transformResponse: undefined,
56
- responseType: 'arraybuffer',
57
- timeout: this.timeoutMillis,
58
- // maxBodyLength needs to be Infinity, because -1 falls back to a 10 MB default
59
- // from an axios subdependency - 'follow-redirects'
60
- maxBodyLength: Infinity,
61
- // maxContentLength must be -1, because Infinity will cause axios to run super slow
62
- // thanks to a bug that's now fixed, but not released yet https://github.com/axios/axios/pull/3738
63
- maxContentLength: -1,
64
- });
65
- // Clean all default headers because they only make a mess and their merging is difficult to understand and buggy.
66
- this.axios.defaults.headers = new axios_1.AxiosHeaders();
67
- // If workflow key is available, pass it as a header
68
- if (this.workflowKey) {
69
- this.axios.defaults.headers['X-Apify-Workflow-Key'] = this.workflowKey;
70
- }
71
- // Attach Authorization header for all requests if token was provided
72
- if (token) {
73
- this.axios.defaults.headers.Authorization = `Bearer ${token}`;
74
- }
75
- interceptors_1.requestInterceptors.forEach((i) => this.axios.interceptors.request.use(i));
76
- this.userProvidedRequestInterceptors.forEach((i) => this.axios.interceptors.request.use(i));
77
- interceptors_1.responseInterceptors.forEach((i) => this.axios.interceptors.response.use(i));
78
- }
79
- async ensureNodeInit() {
80
- if (!(0, utils_1.isNode)())
81
- return;
82
- this.nodeInitPromise ??= this.initNode();
83
- return this.nodeInitPromise;
84
- }
85
- async initNode() {
86
- if (!(0, utils_1.isNode)())
87
- return;
88
- const [{ ProxyAgent }, os] = await Promise.all([import('proxy-agent'), import('node:os')]);
89
- // We want to keep sockets alive for better performance.
90
- // Enhanced agent configuration based on agentkeepalive best practices:
91
- // - Nagle's algorithm disabled for lower latency
92
- // - Free socket timeout to prevent socket leaks
93
- // - LIFO scheduling to reuse recent sockets
94
- // - Socket TTL for connection freshness
95
- const agentOptions = {
96
- keepAlive: true,
97
- // Timeout for inactive sockets
98
- // Prevents socket leaks from idle connections
99
- timeout: this.timeoutMillis,
100
- // Keep alive timeout for free sockets (15 seconds)
101
- // Node.js will close unused sockets after this period
102
- keepAliveMsecs: 15_000,
103
- // Maximum number of sockets per host
104
- maxSockets: 256,
105
- maxFreeSockets: 256,
106
- // LIFO scheduling - reuse most recently used sockets for better performance
107
- scheduling: 'lifo',
108
- };
109
- // Use ProxyAgent which automatically detects proxy from environment variables
110
- // and supports CONNECT tunneling
111
- const proxyAgent = new ProxyAgent(agentOptions);
112
- this.httpAgent = proxyAgent;
113
- this.httpsAgent = proxyAgent;
114
- // Disable Nagle's algorithm for lower latency
115
- // This sends data immediately instead of buffering small packets
116
- const setNoDelay = (socket) => {
117
- socket.setNoDelay(true);
118
- };
119
- this.httpAgent.on('socket', setNoDelay);
120
- this.httpsAgent.on('socket', setNoDelay);
121
- this.axios.defaults.httpAgent = this.httpAgent;
122
- this.axios.defaults.httpsAgent = this.httpsAgent;
123
- // Works only in Node. Cannot be set in browser
124
- const isAtHome = !!process.env[consts_1.APIFY_ENV_VARS.IS_AT_HOME];
125
- let userAgent = `ApifyClient/${version} (${os.platform()}; Node/${process.version}); isAtHome/${isAtHome}`;
126
- if (this.userAgentSuffix) {
127
- userAgent += `; ${(0, utils_1.asArray)(this.userAgentSuffix).join('; ')}`;
128
- }
129
- this.axios.defaults.headers['User-Agent'] = userAgent;
130
- }
131
- async call(config) {
132
- await this.ensureNodeInit();
133
- this.stats.calls++;
134
- const makeRequest = this._createRequestHandler(config);
135
- return (0, async_retry_1.default)(makeRequest, {
136
- retries: this.maxRetries,
137
- minTimeout: this.minDelayBetweenRetriesMillis,
138
- onRetry: this._onRequestRetry,
139
- });
140
- }
141
- _informAboutStreamNoRetry() {
142
- this.logger.warningOnce('Request body was a stream - retrying will not work, as part of it was already consumed.');
143
- this.logger.warningOnce('If you want Apify client to handle retries for you, collect the stream into a buffer before sending it.');
144
- }
145
- /**
146
- * Successful responses are returned, errors and unsuccessful
147
- * status codes are retried. See the following functions for the
148
- * retrying logic.
149
- */
150
- _createRequestHandler(config) {
151
- const makeRequest = async (stopTrying, attempt) => {
152
- this.stats.requests++;
153
- let response;
154
- const requestIsStream = (0, utils_1.isStream)(config.data);
155
- try {
156
- if (requestIsStream) {
157
- // Handling redirects is not possible without buffering - part of the stream has already been sent and can't be recovered
158
- // when server sends the redirect. Therefore we need to override this in Axios config to prevent it from buffering the body.
159
- // see also axios/axios#1045
160
- config = { ...config, maxRedirects: 0 };
161
- }
162
- // Increase timeout with each attempt. Max timeout is bounded by the client timeout.
163
- config.timeout = Math.min(this.timeoutMillis, (config.timeout ?? this.timeoutMillis) * 2 ** (attempt - 1));
164
- response = await this.axios.request(config);
165
- if (this._isStatusOk(response.status))
166
- return response;
167
- }
168
- catch (err) {
169
- return (0, utils_1.cast)(this._handleRequestError(err, config, stopTrying));
170
- }
171
- if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE) {
172
- this.stats.addRateLimitError(attempt);
173
- }
174
- const apiError = new apify_api_error_1.ApifyApiError(response, attempt);
175
- if (this._isStatusCodeRetryable(response.status)) {
176
- if (requestIsStream) {
177
- this._informAboutStreamNoRetry();
178
- }
179
- else {
180
- // allow a retry
181
- throw apiError;
182
- }
183
- }
184
- stopTrying(apiError);
185
- return response;
186
- };
187
- return makeRequest;
188
- }
189
- _isStatusOk(statusCode) {
190
- return statusCode < 300;
191
- }
192
- /**
193
- * Handles all unexpected errors that can happen, but are not
194
- * Apify API typed errors. E.g. network errors, timeouts and so on.
195
- */
196
- _handleRequestError(err, config, stopTrying) {
197
- if (this._isTimeoutError(err) && config.doNotRetryTimeouts) {
198
- return stopTrying(err);
199
- }
200
- if (this._isRetryableError(err)) {
201
- if ((0, utils_1.isStream)(config.data)) {
202
- this._informAboutStreamNoRetry();
203
- }
204
- else {
205
- throw err;
206
- }
207
- }
208
- return stopTrying(err);
209
- }
210
- /**
211
- * Axios calls req.abort() on timeouts so timeout errors will
212
- * have a code ECONNABORTED.
213
- */
214
- _isTimeoutError(err) {
215
- return err.code === 'ECONNABORTED';
216
- }
217
- /**
218
- * We don't want to retry every exception thrown from Axios.
219
- * The common denominator for retryable errors are network issues.
220
- * @param {Error} err
221
- * @private
222
- */
223
- _isRetryableError(err) {
224
- return this._isNetworkError(err) || this._isResponseBodyInvalid(err);
225
- }
226
- /**
227
- * When a network connection to our API is interrupted in the middle of streaming
228
- * a response, the request often does not fail, but simply contains
229
- * an incomplete response. This can often be fixed by retrying.
230
- */
231
- _isResponseBodyInvalid(err) {
232
- return err instanceof interceptors_1.InvalidResponseBodyError;
233
- }
234
- /**
235
- * When a network request is attempted by axios and fails,
236
- * it throws an AxiosError, which will have the request
237
- * and config (and other) properties.
238
- */
239
- _isNetworkError(err) {
240
- const hasRequest = err.request && typeof err.request === 'object';
241
- const hasConfig = err.config && typeof err.config === 'object';
242
- return hasRequest && hasConfig;
243
- }
244
- /**
245
- * We retry 429 (rate limit) and 500+.
246
- * For status codes 300-499 (except 429) we do not retry the request,
247
- * because it's probably caused by invalid url (redirect 3xx) or invalid user input (4xx).
248
- */
249
- _isStatusCodeRetryable(statusCode) {
250
- const isRateLimitError = statusCode === RATE_LIMIT_EXCEEDED_STATUS_CODE;
251
- const isInternalError = statusCode >= 500;
252
- return isRateLimitError || isInternalError;
253
- }
254
- _onRequestRetry(error, attempt) {
255
- if (attempt === Math.round(this.maxRetries / 2)) {
256
- this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${error.stack}`);
257
- }
258
- }
259
- }
260
- exports.HttpClient = HttpClient;