apify-client 3.0.0-beta.12 → 3.0.0-beta.120
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.
- package/README.md +23 -2
- package/dist/apify_api_error.d.ts +14 -28
- package/dist/apify_api_error.js +33 -23
- package/dist/apify_client.d.ts +125 -10
- package/dist/apify_client.js +133 -48
- package/dist/apify_client_error.d.ts +10 -0
- package/dist/apify_client_error.js +10 -0
- package/dist/axios.d.ts +2 -0
- package/dist/axios.js +1 -0
- package/dist/base/api_client.d.ts +7 -7
- package/dist/base/api_client.js +36 -36
- package/dist/base/resource_client.d.ts +13 -8
- package/dist/base/resource_client.js +60 -34
- package/dist/base/resource_collection_client.d.ts +12 -4
- package/dist/base/resource_collection_client.js +34 -11
- package/dist/body_parser.d.ts +4 -5
- package/dist/body_parser.js +19 -26
- package/dist/bundle.js +41 -35
- package/dist/bundle.js.map +1 -1
- package/dist/generated/api.d.ts +3259 -1060
- package/dist/generated/schemas.d.ts +2608 -1028
- package/dist/generated/schemas.js +600 -238
- package/dist/http_clients/axios.d.ts +80 -0
- package/dist/http_clients/axios.js +165 -0
- package/dist/http_clients/base.d.ts +402 -0
- package/dist/http_clients/base.js +680 -0
- package/dist/http_clients/fetch.d.ts +53 -0
- package/dist/http_clients/fetch.js +219 -0
- package/dist/http_clients/index.d.ts +4 -0
- package/dist/http_clients/index.js +2 -0
- package/dist/http_compressors/base.d.ts +40 -0
- package/dist/http_compressors/base.js +9 -0
- package/dist/http_compressors/brotli.d.ts +33 -0
- package/dist/http_compressors/brotli.js +39 -0
- package/dist/http_compressors/gzip.d.ts +33 -0
- package/dist/http_compressors/gzip.js +39 -0
- package/dist/http_compressors/index.d.ts +8 -0
- package/dist/http_compressors/index.js +3 -0
- package/dist/http_compressors/resolve.d.ts +24 -0
- package/dist/http_compressors/resolve.js +30 -0
- package/dist/http_compressors/zstd.d.ts +34 -0
- package/dist/http_compressors/zstd.js +43 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +5 -1
- package/dist/invalid_response_body_error.d.ts +14 -0
- package/dist/invalid_response_body_error.js +18 -0
- package/dist/models.d.ts +177 -240
- package/dist/models.js +6 -4
- package/dist/resource_clients/actor.d.ts +94 -23
- package/dist/resource_clients/actor.js +129 -43
- package/dist/resource_clients/actor_collection.d.ts +15 -11
- package/dist/resource_clients/actor_collection.js +9 -3
- package/dist/resource_clients/actor_env_var.d.ts +11 -4
- package/dist/resource_clients/actor_env_var.js +16 -6
- package/dist/resource_clients/actor_env_var_collection.d.ts +9 -4
- package/dist/resource_clients/actor_env_var_collection.js +11 -4
- package/dist/resource_clients/actor_server.d.ts +149 -0
- package/dist/resource_clients/actor_server.js +195 -0
- package/dist/resource_clients/actor_version.d.ts +19 -6
- package/dist/resource_clients/actor_version.js +19 -8
- package/dist/resource_clients/actor_version_collection.d.ts +10 -4
- package/dist/resource_clients/actor_version_collection.js +12 -4
- package/dist/resource_clients/build.d.ts +18 -7
- package/dist/resource_clients/build.js +33 -15
- package/dist/resource_clients/build_collection.d.ts +7 -5
- package/dist/resource_clients/build_collection.js +4 -1
- package/dist/resource_clients/dataset.d.ts +83 -37
- package/dist/resource_clients/dataset.js +99 -109
- package/dist/resource_clients/dataset_collection.d.ts +10 -6
- package/dist/resource_clients/dataset_collection.js +13 -2
- package/dist/resource_clients/key_value_store.d.ts +108 -33
- package/dist/resource_clients/key_value_store.js +134 -53
- package/dist/resource_clients/key_value_store_collection.d.ts +10 -6
- package/dist/resource_clients/key_value_store_collection.js +13 -2
- package/dist/resource_clients/log.d.ts +41 -25
- package/dist/resource_clients/log.js +142 -65
- package/dist/resource_clients/request_queue.d.ts +77 -31
- package/dist/resource_clients/request_queue.js +178 -93
- package/dist/resource_clients/request_queue_collection.d.ts +9 -5
- package/dist/resource_clients/request_queue_collection.js +9 -3
- package/dist/resource_clients/run.d.ts +119 -29
- package/dist/resource_clients/run.js +188 -49
- package/dist/resource_clients/run_collection.d.ts +5 -3
- package/dist/resource_clients/run_collection.js +4 -1
- package/dist/resource_clients/schedule.d.ts +15 -6
- package/dist/resource_clients/schedule.js +25 -10
- package/dist/resource_clients/schedule_collection.d.ts +6 -2
- package/dist/resource_clients/schedule_collection.js +9 -3
- package/dist/resource_clients/store_collection.d.ts +10 -4
- package/dist/resource_clients/store_collection.js +4 -1
- package/dist/resource_clients/task.d.ts +35 -12
- package/dist/resource_clients/task.js +75 -35
- package/dist/resource_clients/task_collection.d.ts +9 -5
- package/dist/resource_clients/task_collection.js +9 -3
- package/dist/resource_clients/user.d.ts +16 -7
- package/dist/resource_clients/user.js +34 -16
- package/dist/resource_clients/webhook.d.ts +16 -7
- package/dist/resource_clients/webhook.js +25 -10
- package/dist/resource_clients/webhook_collection.d.ts +8 -4
- package/dist/resource_clients/webhook_collection.js +9 -3
- package/dist/resource_clients/webhook_dispatch.d.ts +4 -1
- package/dist/resource_clients/webhook_dispatch.js +7 -2
- package/dist/resource_clients/webhook_dispatch_collection.d.ts +3 -1
- package/dist/resource_clients/webhook_dispatch_collection.js +4 -1
- package/dist/response_validation_error.d.ts +2 -1
- package/dist/response_validation_error.js +2 -1
- package/dist/runtime/node.d.ts +6 -0
- package/dist/runtime/node.js +111 -0
- package/dist/runtime/types.d.ts +82 -0
- package/dist/runtime/types.js +1 -0
- package/dist/runtime/web.d.ts +5 -0
- package/dist/runtime/web.js +60 -0
- package/dist/schemas.d.ts +372 -4
- package/dist/schemas.js +26 -4
- package/dist/statistics.d.ts +1 -6
- package/dist/statistics.js +2 -2
- package/dist/timeouts.d.ts +84 -0
- package/dist/timeouts.js +37 -0
- package/dist/timezones.d.ts +1 -1
- package/dist/utils.d.ts +115 -61
- package/dist/utils.js +220 -161
- package/dist/wait_for_resources.d.ts +8 -0
- package/dist/wait_for_resources.js +39 -0
- package/package.json +53 -38
- package/dist/http_client.d.ts +0 -88
- package/dist/http_client.js +0 -255
- package/dist/interceptors.d.ts +0 -19
- package/dist/interceptors.js +0 -105
package/dist/utils.js
CHANGED
|
@@ -4,7 +4,61 @@ import { parseArgument } from '@apify/validations';
|
|
|
4
4
|
import { ResponseValidationError } from './response_validation_error.js';
|
|
5
5
|
// @ts-ignore if we enable `resolveJsonModule`, we end up with a `src` folder in `dist`
|
|
6
6
|
import packageJson from '../package.json' with { type: 'json' };
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Smallest request body, in bytes, that is worth compressing. A smaller body already fits in a single network
|
|
9
|
+
* packet, so compressing it costs CPU time without saving a round trip, and the compression format itself can
|
|
10
|
+
* make it larger.
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export const MIN_COMPRESS_BYTES = 1024;
|
|
14
|
+
const textEncoder = new TextEncoder();
|
|
15
|
+
// Only the version, so a bundler can drop the rest of the manifest.
|
|
16
|
+
export const { version } = packageJson;
|
|
17
|
+
/** Media type prefixes whose payloads carry their own compression, so compressing the request body is wasted work. */
|
|
18
|
+
const ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES = ['audio/', 'image/', 'video/'];
|
|
19
|
+
/** Exact media types whose payloads carry their own compression. */
|
|
20
|
+
const ALREADY_COMPRESSED_MEDIA_TYPES = new Set([
|
|
21
|
+
'application/epub+zip',
|
|
22
|
+
'application/gzip',
|
|
23
|
+
'application/java-archive',
|
|
24
|
+
'application/vnd.android.package-archive',
|
|
25
|
+
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
26
|
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
27
|
+
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
28
|
+
'application/vnd.rar',
|
|
29
|
+
'application/x-7z-compressed',
|
|
30
|
+
'application/x-bzip',
|
|
31
|
+
'application/x-bzip2',
|
|
32
|
+
'application/x-gzip',
|
|
33
|
+
'application/x-rar-compressed',
|
|
34
|
+
'application/x-xz',
|
|
35
|
+
'application/x-zip-compressed',
|
|
36
|
+
'application/zip',
|
|
37
|
+
'application/zstd',
|
|
38
|
+
'font/woff',
|
|
39
|
+
'font/woff2',
|
|
40
|
+
]);
|
|
41
|
+
/** Uncompressed media types that sit under an already-compressed prefix, so compressing them still pays off. */
|
|
42
|
+
const COMPRESSIBLE_MEDIA_TYPES = new Set([
|
|
43
|
+
'audio/aiff',
|
|
44
|
+
'audio/basic',
|
|
45
|
+
'audio/l16',
|
|
46
|
+
'audio/l24',
|
|
47
|
+
'audio/midi',
|
|
48
|
+
'audio/vnd.wave',
|
|
49
|
+
'audio/wav',
|
|
50
|
+
'audio/wave',
|
|
51
|
+
'audio/x-aiff',
|
|
52
|
+
'audio/x-wav',
|
|
53
|
+
'image/bmp',
|
|
54
|
+
'image/tiff',
|
|
55
|
+
'image/vnd.adobe.photoshop',
|
|
56
|
+
'image/vnd.microsoft.icon',
|
|
57
|
+
'image/x-icon',
|
|
58
|
+
'image/x-ms-bmp',
|
|
59
|
+
]);
|
|
60
|
+
/** Structured syntax suffixes marking a media type as text even under an already-compressed prefix (`image/svg+xml`). */
|
|
61
|
+
const COMPRESSIBLE_MEDIA_TYPE_SUFFIXES = ['+json', '+xml'];
|
|
8
62
|
export { parseArgument };
|
|
9
63
|
/**
|
|
10
64
|
* Accepts any non-null, non-array object as a predicate for `z.custom()`.
|
|
@@ -26,36 +80,30 @@ export const anyObjectSchema = z.custom(isNonArrayObject, {
|
|
|
26
80
|
// any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
|
|
27
81
|
// in per parse keeps them intact without reaching into the zod config the whole process shares.
|
|
28
82
|
const { localeError } = z.locales.en();
|
|
83
|
+
const RESPONSE_ENVELOPE_SCHEMA = z.object({ data: z.unknown() });
|
|
29
84
|
/**
|
|
30
|
-
* Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
85
|
+
* Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope and validates the
|
|
86
|
+
* result against `schema`, one of the schemas generated from the OpenAPI specification. The validated copy is what
|
|
87
|
+
* callers get, so it is the schema's output -- unknown fields and unknown enum values included, since the schemas let
|
|
88
|
+
* both through, date-time fields turned into `Date` objects, and URL fields normalized, since `z.url()` hands back the
|
|
89
|
+
* parsed URL's serialization.
|
|
35
90
|
*
|
|
36
91
|
* Throws {@link ResponseValidationError} when the response does not match the specification.
|
|
37
92
|
* @internal
|
|
38
93
|
*/
|
|
39
|
-
export function parseResponse(response, schema
|
|
40
|
-
const
|
|
94
|
+
export function parseResponse(response, schema) {
|
|
95
|
+
const { method = 'GET', url = '' } = response.config;
|
|
96
|
+
const envelope = RESPONSE_ENVELOPE_SCHEMA.safeParse(response.data, { error: localeError });
|
|
97
|
+
if (!envelope.success) {
|
|
98
|
+
throw new ResponseValidationError(envelope.error, response.data, { method, url });
|
|
99
|
+
}
|
|
100
|
+
const { data } = envelope.data;
|
|
41
101
|
const result = schema.safeParse(data, { error: localeError });
|
|
42
102
|
if (!result.success) {
|
|
43
|
-
const { method = 'GET', url = '' } = response.config;
|
|
44
103
|
throw new ResponseValidationError(result.error, data, { method, url });
|
|
45
104
|
}
|
|
46
105
|
return result.data;
|
|
47
106
|
}
|
|
48
|
-
/**
|
|
49
|
-
* Returns object's 'data' property or throws if parameter is not an object,
|
|
50
|
-
* or an object without a 'data' property.
|
|
51
|
-
*/
|
|
52
|
-
export function pluckData(obj) {
|
|
53
|
-
if (typeof obj === 'object' && obj) {
|
|
54
|
-
if (typeof obj.data !== 'undefined')
|
|
55
|
-
return obj.data;
|
|
56
|
-
}
|
|
57
|
-
throw new Error(`Expected response object with a "data" property, but received: ${obj}`);
|
|
58
|
-
}
|
|
59
107
|
/**
|
|
60
108
|
* Swallows a 404 Not Found API error and rethrows anything else.
|
|
61
109
|
*/
|
|
@@ -75,151 +123,111 @@ export function catchNotFoundForResourceOrThrow(err, resourceId) {
|
|
|
75
123
|
throw err;
|
|
76
124
|
catchNotFoundOrThrow(err);
|
|
77
125
|
}
|
|
78
|
-
/**
|
|
79
|
-
* Traverses JSON structure and converts fields that end with "At" to a Date object (fields such as "modifiedAt" or
|
|
80
|
-
* "createdAt").
|
|
81
|
-
*
|
|
82
|
-
* If you want parse other fields as well, you can provide a custom matcher function shouldParseField(). This
|
|
83
|
-
* admittedly awkward approach allows this function to be reused for various purposes without introducing potential
|
|
84
|
-
* breaking changes.
|
|
85
|
-
*
|
|
86
|
-
* If the field cannot be converted to Date, it is left as is.
|
|
87
|
-
*/
|
|
88
|
-
export function parseDateFields(input, shouldParseField = null, depth = 0) {
|
|
89
|
-
// Don't go too deep to avoid stack overflows (especially if there is a circular reference). The depth of 4
|
|
90
|
-
// corresponds to obj.items.[x].someArrayField.[y].field, which is what a list response looks like: it
|
|
91
|
-
// nests one level deeper than the single resource it wraps, because both the item array and the nested
|
|
92
|
-
// array spend a level.
|
|
93
|
-
//
|
|
94
|
-
// In a list response it also reaches one level into caller-owned blobs the API stores verbatim, so a
|
|
95
|
-
// listed request's `userData.foo.somethingAt` comes back as a `Date` rather than the string it was
|
|
96
|
-
// written as.
|
|
97
|
-
// TODO: Consider removing this limitation. It might came across as an annoying surprise as it's not communicated.
|
|
98
|
-
if (depth > 4) {
|
|
99
|
-
return input;
|
|
100
|
-
}
|
|
101
|
-
if (Array.isArray(input))
|
|
102
|
-
return input.map((child) => parseDateFields(child, shouldParseField, depth + 1));
|
|
103
|
-
if (!input || typeof input !== 'object')
|
|
104
|
-
return input;
|
|
105
|
-
return Object.entries(input).reduce((output, [k, v]) => {
|
|
106
|
-
const isValObject = !!v && typeof v === 'object';
|
|
107
|
-
if (k.endsWith('At') || (shouldParseField && shouldParseField(k))) {
|
|
108
|
-
if (v) {
|
|
109
|
-
const d = new Date(v);
|
|
110
|
-
output[k] = Number.isNaN(d.getTime()) ? v : d;
|
|
111
|
-
}
|
|
112
|
-
else {
|
|
113
|
-
output[k] = v;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
else if (isValObject || Array.isArray(v)) {
|
|
117
|
-
output[k] = parseDateFields(v, shouldParseField, depth + 1);
|
|
118
|
-
}
|
|
119
|
-
else {
|
|
120
|
-
output[k] = v;
|
|
121
|
-
}
|
|
122
|
-
return output;
|
|
123
|
-
}, {});
|
|
124
|
-
}
|
|
125
126
|
/**
|
|
126
127
|
* Helper function that converts array of webhooks to base64 string
|
|
127
128
|
*/
|
|
128
129
|
export function stringifyWebhooksToBase64(webhooks) {
|
|
129
130
|
if (!webhooks)
|
|
130
131
|
return;
|
|
131
|
-
|
|
132
|
-
if (isNode()) {
|
|
133
|
-
return Buffer.from(webhooksJson, 'utf8').toString('base64');
|
|
134
|
-
}
|
|
135
|
-
const encoder = new TextEncoder();
|
|
136
|
-
const uint8Array = encoder.encode(webhooksJson);
|
|
137
|
-
return btoa(String.fromCharCode(...uint8Array));
|
|
132
|
+
return bytesToBase64(textEncoder.encode(JSON.stringify(webhooks)));
|
|
138
133
|
}
|
|
139
|
-
let brotliCompressPromisified;
|
|
140
134
|
/**
|
|
141
|
-
*
|
|
135
|
+
* Encodes bytes as base64. `btoa()` takes a binary string, and the bytes are turned into one in slices,
|
|
136
|
+
* because spreading them all into a single `String.fromCharCode()` call overflows the argument limit on
|
|
137
|
+
* inputs of a few tens of kilobytes.
|
|
142
138
|
*/
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const options = { params: { [constants.BROTLI_PARAM_QUALITY]: 6 } };
|
|
149
|
-
brotliCompressPromisified = async (input) => compress(input, options);
|
|
139
|
+
export function bytesToBase64(bytes) {
|
|
140
|
+
const SLICE_LENGTH = 0x8000;
|
|
141
|
+
let binary = '';
|
|
142
|
+
for (let i = 0; i < bytes.length; i += SLICE_LENGTH) {
|
|
143
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + SLICE_LENGTH));
|
|
150
144
|
}
|
|
151
|
-
return
|
|
145
|
+
return btoa(binary);
|
|
152
146
|
}
|
|
153
|
-
let gzipPromisified;
|
|
154
147
|
/**
|
|
155
|
-
*
|
|
148
|
+
* Concatenates byte chunks into one array.
|
|
156
149
|
*/
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
150
|
+
export function concatBytes(chunks) {
|
|
151
|
+
const result = new Uint8Array(chunks.reduce((length, chunk) => length + chunk.length, 0));
|
|
152
|
+
let offset = 0;
|
|
153
|
+
for (const chunk of chunks) {
|
|
154
|
+
result.set(chunk, offset);
|
|
155
|
+
offset += chunk.length;
|
|
162
156
|
}
|
|
163
|
-
return
|
|
157
|
+
return result;
|
|
164
158
|
}
|
|
165
159
|
/**
|
|
166
|
-
*
|
|
167
|
-
*
|
|
160
|
+
* Views a request body as bytes: a string is UTF-8 encoded, binary values are viewed in place. Anything else
|
|
161
|
+
* - a stream, a `Blob`, form data - is `undefined`.
|
|
162
|
+
* @internal
|
|
168
163
|
*/
|
|
169
|
-
export
|
|
170
|
-
if (
|
|
171
|
-
return
|
|
172
|
-
|
|
173
|
-
// skip it instead of throwing for unsupported types.
|
|
174
|
-
if (typeof value !== 'string' && !Buffer.isBuffer(value))
|
|
175
|
-
return undefined;
|
|
176
|
-
const areDataLargeEnough = Buffer.byteLength(value) >= MIN_COMPRESS_BYTES;
|
|
177
|
-
if (!areDataLargeEnough)
|
|
178
|
-
return undefined;
|
|
179
|
-
try {
|
|
180
|
-
return { data: await brotliValue(value), encoding: 'br' };
|
|
181
|
-
}
|
|
182
|
-
catch {
|
|
183
|
-
// Runtimes that only provide a partial `node:zlib` (bundler polyfills, edge runtimes with
|
|
184
|
-
// Node compatibility shims) may not implement brotli, but usually do implement gzip.
|
|
185
|
-
}
|
|
186
|
-
try {
|
|
187
|
-
return { data: await gzipValue(value), encoding: 'gzip' };
|
|
188
|
-
}
|
|
189
|
-
catch {
|
|
190
|
-
// Same reasoning as above: compression is a best-effort optimization, so skip it instead
|
|
191
|
-
// of failing the request.
|
|
164
|
+
export function toBytes(value) {
|
|
165
|
+
if (typeof value === 'string')
|
|
166
|
+
return textEncoder.encode(value);
|
|
167
|
+
if (!isBuffer(value))
|
|
192
168
|
return undefined;
|
|
193
|
-
|
|
169
|
+
return ArrayBuffer.isView(value)
|
|
170
|
+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
|
171
|
+
: new Uint8Array(value);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Decides whether a request body with the given content type is worth compressing.
|
|
175
|
+
*
|
|
176
|
+
* Images, audio, video and archives already carry their own compression. Running them through brotli, gzip or
|
|
177
|
+
* zstd burns CPU, holds a second full copy of the body in memory, and usually produces output slightly larger than
|
|
178
|
+
* the input. Formats that are raw despite such a media type, for example `image/bmp` or `audio/wav`, are still
|
|
179
|
+
* compressed. A body with no content type is assumed to be compressible.
|
|
180
|
+
* @internal
|
|
181
|
+
*/
|
|
182
|
+
export function isCompressibleContentType(contentType) {
|
|
183
|
+
if (!contentType)
|
|
184
|
+
return true;
|
|
185
|
+
// `Content-Type` is case-insensitive and may carry parameters, for example `text/plain; charset=utf-8`.
|
|
186
|
+
const mediaType = contentType.split(';', 1)[0].trim().toLowerCase();
|
|
187
|
+
if (COMPRESSIBLE_MEDIA_TYPES.has(mediaType))
|
|
188
|
+
return true;
|
|
189
|
+
if (COMPRESSIBLE_MEDIA_TYPE_SUFFIXES.some((suffix) => mediaType.endsWith(suffix)))
|
|
190
|
+
return true;
|
|
191
|
+
if (ALREADY_COMPRESSED_MEDIA_TYPES.has(mediaType))
|
|
192
|
+
return false;
|
|
193
|
+
return !ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES.some((prefix) => mediaType.startsWith(prefix));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Reads an environment variable, on runtimes that have them.
|
|
197
|
+
*/
|
|
198
|
+
export function getEnv(name) {
|
|
199
|
+
return typeof process !== 'undefined' ? process.env?.[name] : undefined;
|
|
194
200
|
}
|
|
195
201
|
/**
|
|
196
|
-
*
|
|
202
|
+
* Returns the UTF-8 byte length of a string.
|
|
197
203
|
*/
|
|
198
|
-
export function
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
204
|
+
export function utf8ByteLength(value) {
|
|
205
|
+
return textEncoder.encode(value).byteLength;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Splits JSON-serialized items into consecutive batches of at most `maxCount` items, each of which fits into a JSON
|
|
209
|
+
* array body - the items joined by commas between brackets - of at most `maxByteLength` bytes. The `byteLength` of an
|
|
210
|
+
* item is the UTF-8 byte length of its serialization. An item too large for a body of its own still gets one, so a
|
|
211
|
+
* caller that cannot send such an item has to reject it beforehand.
|
|
212
|
+
*/
|
|
213
|
+
export function splitIntoJsonArrayBatches(items, { maxCount, maxByteLength }) {
|
|
214
|
+
const batches = [];
|
|
215
|
+
let batch = [];
|
|
216
|
+
// One byte for the opening bracket; each item then adds its own bytes plus one for the comma or the closing
|
|
217
|
+
// bracket that follows it.
|
|
218
|
+
let byteLength = 1;
|
|
219
|
+
for (const item of items) {
|
|
220
|
+
if (batch.length > 0 && (batch.length >= maxCount || byteLength + item.byteLength + 1 > maxByteLength)) {
|
|
221
|
+
batches.push(batch);
|
|
222
|
+
batch = [];
|
|
223
|
+
byteLength = 1;
|
|
211
224
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
byteLength += itemByteSize;
|
|
215
|
-
slicedArray.push(item);
|
|
225
|
+
batch.push(item);
|
|
226
|
+
byteLength += item.byteLength + 1;
|
|
216
227
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
if (typeof BROWSER_BUILD !== 'undefined')
|
|
221
|
-
return false;
|
|
222
|
-
return !!(typeof process !== 'undefined' && process.versions && process.versions.node);
|
|
228
|
+
if (batch.length > 0)
|
|
229
|
+
batches.push(batch);
|
|
230
|
+
return batches;
|
|
223
231
|
}
|
|
224
232
|
export function isBuffer(value) {
|
|
225
233
|
// Tag checks rather than `instanceof`, to also match buffers from another realm. `isView()`
|
|
@@ -228,43 +236,57 @@ export function isBuffer(value) {
|
|
|
228
236
|
return !isTagged(value, 'DataView');
|
|
229
237
|
return isTagged(value, 'ArrayBuffer');
|
|
230
238
|
}
|
|
239
|
+
/**
|
|
240
|
+
* Whether a value is a `Blob`, a `File` included. Unlike a stream, a blob can be read again for every attempt of a
|
|
241
|
+
* request, so a request with a blob body can be retried.
|
|
242
|
+
*/
|
|
243
|
+
export function isBlob(value) {
|
|
244
|
+
return isTagged(value, 'Blob') || isTagged(value, 'File');
|
|
245
|
+
}
|
|
231
246
|
function isTagged(value, tag) {
|
|
232
247
|
return Object.prototype.toString.call(value) === `[object ${tag}]`;
|
|
233
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response and may pass
|
|
251
|
+
* on as a request body.
|
|
252
|
+
*/
|
|
253
|
+
export function isWebStream(value) {
|
|
254
|
+
return isTagged(value, 'ReadableStream');
|
|
255
|
+
}
|
|
234
256
|
export function isStream(value) {
|
|
235
257
|
if (value === null || typeof value !== 'object')
|
|
236
258
|
return false;
|
|
237
259
|
const { on, pipe } = value;
|
|
238
260
|
return typeof on === 'function' && typeof pipe === 'function';
|
|
239
261
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
return
|
|
262
|
+
/**
|
|
263
|
+
* Whether a value is a stream of either kind, which a request can send only once.
|
|
264
|
+
*/
|
|
265
|
+
export function isAnyStream(value) {
|
|
266
|
+
return isStream(value) || isWebStream(value);
|
|
245
267
|
}
|
|
246
268
|
/**
|
|
247
269
|
* Helper class to create async iterators from paginated list endpoints.
|
|
248
270
|
*/
|
|
249
271
|
export class RequestQueuePaginationIterator {
|
|
250
|
-
maxPageLimit;
|
|
251
|
-
getPage;
|
|
252
|
-
limit;
|
|
253
|
-
cursor;
|
|
272
|
+
#maxPageLimit;
|
|
273
|
+
#getPage;
|
|
274
|
+
#limit;
|
|
275
|
+
#cursor;
|
|
254
276
|
constructor(options) {
|
|
255
|
-
this
|
|
256
|
-
this
|
|
257
|
-
this
|
|
258
|
-
this
|
|
277
|
+
this.#maxPageLimit = options.maxPageLimit;
|
|
278
|
+
this.#limit = options.limit;
|
|
279
|
+
this.#cursor = options.cursor;
|
|
280
|
+
this.#getPage = options.getPage;
|
|
259
281
|
}
|
|
260
282
|
async *[Symbol.asyncIterator]() {
|
|
261
|
-
let nextCursor = this
|
|
283
|
+
let nextCursor = this.#cursor;
|
|
262
284
|
let iterateItemCount = 0;
|
|
263
285
|
while (true) {
|
|
264
|
-
const pageLimit = this
|
|
265
|
-
? Math.min(this
|
|
266
|
-
: this
|
|
267
|
-
const page = await this
|
|
286
|
+
const pageLimit = this.#limit
|
|
287
|
+
? Math.min(this.#maxPageLimit, this.#limit - iterateItemCount)
|
|
288
|
+
: this.#maxPageLimit;
|
|
289
|
+
const page = await this.#getPage({
|
|
268
290
|
limit: pageLimit,
|
|
269
291
|
cursor: nextCursor,
|
|
270
292
|
});
|
|
@@ -274,12 +296,28 @@ export class RequestQueuePaginationIterator {
|
|
|
274
296
|
yield page;
|
|
275
297
|
iterateItemCount += page.items.length;
|
|
276
298
|
// Limit reached stopping to iterate
|
|
277
|
-
if ((this
|
|
299
|
+
if ((this.#limit && iterateItemCount >= this.#limit) || !page.nextCursor)
|
|
278
300
|
return;
|
|
279
301
|
nextCursor = page.nextCursor;
|
|
280
302
|
}
|
|
281
303
|
}
|
|
282
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* The smaller of two page limits, for the `limit` query parameter. The API treats a `limit` of 0 as unset, so 0 here
|
|
307
|
+
* means no limit and loses to any other value.
|
|
308
|
+
* @internal
|
|
309
|
+
*/
|
|
310
|
+
export function minForLimitParam(a, b) {
|
|
311
|
+
if (a === 0)
|
|
312
|
+
a = undefined;
|
|
313
|
+
if (b === 0)
|
|
314
|
+
b = undefined;
|
|
315
|
+
if (a === undefined)
|
|
316
|
+
return b;
|
|
317
|
+
if (b === undefined)
|
|
318
|
+
return a;
|
|
319
|
+
return Math.min(a, b);
|
|
320
|
+
}
|
|
283
321
|
/**
|
|
284
322
|
* Schema shape of {@link PaginationOptions}, to spread into every paginating client's list schema. One
|
|
285
323
|
* copy stops it drifting from the interface.
|
|
@@ -337,3 +375,24 @@ export function toPathSegment(value) {
|
|
|
337
375
|
export function toPath(path) {
|
|
338
376
|
return Array.isArray(path) ? path.map(toPathSegment).join('/') : path;
|
|
339
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* Resolves after `millis`, or right away once `signal` aborts.
|
|
380
|
+
* @internal
|
|
381
|
+
*/
|
|
382
|
+
export async function sleep(millis, signal) {
|
|
383
|
+
return new Promise((resolve) => {
|
|
384
|
+
if (signal?.aborted) {
|
|
385
|
+
resolve();
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const onAbort = () => {
|
|
389
|
+
clearTimeout(timer);
|
|
390
|
+
resolve();
|
|
391
|
+
};
|
|
392
|
+
const timer = setTimeout(() => {
|
|
393
|
+
signal?.removeEventListener('abort', onAbort);
|
|
394
|
+
resolve();
|
|
395
|
+
}, millis);
|
|
396
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
397
|
+
});
|
|
398
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Log } from '@apify/log';
|
|
2
|
+
/**
|
|
3
|
+
* Makes the `start` request, retrying it every {@link WAIT_FOR_RESOURCES_COOLDOWN_MILLIS} while it fails with one of
|
|
4
|
+
* {@link RESOURCE_LIMIT_ERROR_TYPES}. `true` retries until the request succeeds, a number of seconds bounds the
|
|
5
|
+
* retrying, after which the last error is thrown. Any other error is thrown right away.
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export declare function startWaitingForResources<T>(start: () => Promise<T>, waitForResources: boolean | number | undefined, logger: Log, signal?: AbortSignal): Promise<T>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ApifyApiError } from './apify_api_error.js';
|
|
2
|
+
import { sleep } from './utils.js';
|
|
3
|
+
/**
|
|
4
|
+
* Error types the API rejects a run start with while the account has no free memory or concurrent-run slot for it.
|
|
5
|
+
* Both clear as other runs or builds finish.
|
|
6
|
+
*/
|
|
7
|
+
const RESOURCE_LIMIT_ERROR_TYPES = new Set([
|
|
8
|
+
'actor-memory-limit-exceeded',
|
|
9
|
+
'concurrent-runs-limit-exceeded',
|
|
10
|
+
]);
|
|
11
|
+
/** Cooldown between two attempts to start a run that was rejected for lack of resources. */
|
|
12
|
+
const WAIT_FOR_RESOURCES_COOLDOWN_MILLIS = 10_000;
|
|
13
|
+
/**
|
|
14
|
+
* Makes the `start` request, retrying it every {@link WAIT_FOR_RESOURCES_COOLDOWN_MILLIS} while it fails with one of
|
|
15
|
+
* {@link RESOURCE_LIMIT_ERROR_TYPES}. `true` retries until the request succeeds, a number of seconds bounds the
|
|
16
|
+
* retrying, after which the last error is thrown. Any other error is thrown right away.
|
|
17
|
+
* @internal
|
|
18
|
+
*/
|
|
19
|
+
export async function startWaitingForResources(start, waitForResources, logger, signal) {
|
|
20
|
+
if (!waitForResources)
|
|
21
|
+
return start();
|
|
22
|
+
const deadline = waitForResources === true ? Infinity : Date.now() + waitForResources * 1000;
|
|
23
|
+
for (;;) {
|
|
24
|
+
try {
|
|
25
|
+
return await start();
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
if (!(err instanceof ApifyApiError) || !RESOURCE_LIMIT_ERROR_TYPES.has(err.type ?? ''))
|
|
29
|
+
throw err;
|
|
30
|
+
const remainingMillis = deadline - Date.now();
|
|
31
|
+
if (remainingMillis <= 0)
|
|
32
|
+
throw err;
|
|
33
|
+
const delayMillis = Math.min(WAIT_FOR_RESOURCES_COOLDOWN_MILLIS, remainingMillis);
|
|
34
|
+
logger.info(`Not enough resources to start the run, retrying in ${Number((delayMillis / 1000).toPrecision(3))}s: ${err.message}`);
|
|
35
|
+
await sleep(delayMillis, signal);
|
|
36
|
+
signal?.throwIfAborted();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|