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.
- package/README.md +21 -5
- package/dist/apify_api_error.d.ts +64 -22
- package/dist/apify_api_error.js +100 -30
- package/dist/apify_client.d.ts +150 -35
- package/dist/apify_client.js +198 -118
- package/dist/apify_client_error.d.ts +10 -0
- package/dist/apify_client_error.js +10 -0
- package/dist/base/api_client.d.ts +9 -9
- package/dist/base/api_client.js +41 -45
- package/dist/base/resource_client.d.ts +24 -10
- package/dist/base/resource_client.js +78 -48
- package/dist/base/resource_collection_client.d.ts +15 -6
- package/dist/base/resource_collection_client.js +40 -21
- package/dist/body_parser.d.ts +3 -4
- package/dist/body_parser.js +20 -32
- package/dist/bundle.js +47 -52
- package/dist/bundle.js.map +1 -1
- package/dist/generated/api.d.ts +3363 -1185
- package/dist/generated/api.js +1 -2
- package/dist/generated/schemas.d.ts +8146 -0
- package/dist/generated/schemas.js +1866 -0
- package/dist/http_clients/axios.d.ts +61 -0
- package/dist/http_clients/axios.js +119 -0
- package/dist/http_clients/base.d.ts +391 -0
- package/dist/http_clients/base.js +650 -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 +38 -32
- package/dist/index.js +36 -36
- package/dist/invalid_response_body_error.d.ts +14 -0
- package/dist/invalid_response_body_error.js +18 -0
- package/dist/lazy_schema.d.ts +8 -0
- package/dist/lazy_schema.js +11 -0
- package/dist/models.d.ts +196 -278
- package/dist/models.js +14 -15
- package/dist/resource_clients/actor.d.ts +115 -45
- package/dist/resource_clients/actor.js +187 -116
- package/dist/resource_clients/actor_collection.d.ts +21 -17
- package/dist/resource_clients/actor_collection.js +26 -21
- package/dist/resource_clients/actor_env_var.d.ts +13 -6
- package/dist/resource_clients/actor_env_var.js +21 -14
- package/dist/resource_clients/actor_env_var_collection.d.ts +18 -22
- package/dist/resource_clients/actor_env_var_collection.js +23 -20
- package/dist/resource_clients/actor_server.d.ts +149 -0
- package/dist/resource_clients/actor_server.js +199 -0
- package/dist/resource_clients/actor_version.d.ts +30 -10
- package/dist/resource_clients/actor_version.js +29 -23
- package/dist/resource_clients/actor_version_collection.d.ts +20 -21
- package/dist/resource_clients/actor_version_collection.js +25 -20
- package/dist/resource_clients/build.d.ts +24 -11
- package/dist/resource_clients/build.js +43 -26
- package/dist/resource_clients/build_collection.d.ts +10 -8
- package/dist/resource_clients/build_collection.js +13 -13
- package/dist/resource_clients/dataset.d.ts +87 -40
- package/dist/resource_clients/dataset.js +159 -175
- package/dist/resource_clients/dataset_collection.d.ts +13 -9
- package/dist/resource_clients/dataset_collection.js +29 -21
- package/dist/resource_clients/key_value_store.d.ts +110 -28
- package/dist/resource_clients/key_value_store.js +177 -99
- package/dist/resource_clients/key_value_store_collection.d.ts +13 -9
- package/dist/resource_clients/key_value_store_collection.js +29 -21
- package/dist/resource_clients/log.d.ts +42 -23
- package/dist/resource_clients/log.js +156 -85
- package/dist/resource_clients/request_queue.d.ts +77 -38
- package/dist/resource_clients/request_queue.js +251 -172
- package/dist/resource_clients/request_queue_collection.d.ts +12 -8
- package/dist/resource_clients/request_queue_collection.js +23 -20
- package/dist/resource_clients/run.d.ts +134 -34
- package/dist/resource_clients/run.js +225 -84
- package/dist/resource_clients/run_collection.d.ts +8 -6
- package/dist/resource_clients/run_collection.js +18 -18
- package/dist/resource_clients/schedule.d.ts +20 -11
- package/dist/resource_clients/schedule.js +36 -30
- package/dist/resource_clients/schedule_collection.d.ts +10 -6
- package/dist/resource_clients/schedule_collection.js +20 -17
- package/dist/resource_clients/store_collection.d.ts +9 -7
- package/dist/resource_clients/store_collection.js +18 -18
- package/dist/resource_clients/task.d.ts +44 -21
- package/dist/resource_clients/task.js +116 -86
- package/dist/resource_clients/task_collection.d.ts +13 -9
- package/dist/resource_clients/task_collection.js +19 -16
- package/dist/resource_clients/user.d.ts +22 -13
- package/dist/resource_clients/user.js +46 -47
- package/dist/resource_clients/webhook.d.ts +21 -12
- package/dist/resource_clients/webhook.js +35 -30
- package/dist/resource_clients/webhook_collection.d.ts +11 -7
- package/dist/resource_clients/webhook_collection.js +20 -17
- package/dist/resource_clients/webhook_dispatch.d.ts +9 -6
- package/dist/resource_clients/webhook_dispatch.js +11 -10
- package/dist/resource_clients/webhook_dispatch_collection.d.ts +7 -5
- package/dist/resource_clients/webhook_dispatch_collection.js +13 -13
- package/dist/response_validation_error.d.ts +27 -0
- package/dist/response_validation_error.js +38 -0
- package/dist/runtime/node.d.ts +6 -0
- package/dist/runtime/node.js +87 -0
- package/dist/runtime/types.d.ts +60 -0
- package/dist/runtime/types.js +1 -0
- package/dist/runtime/web.d.ts +5 -0
- package/dist/runtime/web.js +21 -0
- package/dist/schemas.d.ts +381 -0
- package/dist/schemas.js +37 -0
- package/dist/statistics.d.ts +1 -6
- package/dist/statistics.js +7 -11
- package/dist/timeouts.d.ts +84 -0
- package/dist/timeouts.js +37 -0
- package/dist/timezones.d.ts +1 -1
- package/dist/timezones.js +1 -2
- package/dist/utils.d.ts +99 -70
- package/dist/utils.js +251 -229
- package/dist/wait_for_resources.d.ts +8 -0
- package/dist/wait_for_resources.js +39 -0
- package/package.json +48 -47
- package/dist/argument_validation_error.d.ts +0 -17
- package/dist/argument_validation_error.js +0 -157
- package/dist/http_client.d.ts +0 -88
- package/dist/http_client.js +0 -260
- package/dist/index.mjs +0 -42
- package/dist/interceptors.d.ts +0 -19
- package/dist/interceptors.js +0 -110
package/dist/utils.js
CHANGED
|
@@ -1,53 +1,70 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
exports.catchNotFoundOrThrow = catchNotFoundOrThrow;
|
|
8
|
-
exports.parseDateFields = parseDateFields;
|
|
9
|
-
exports.stringifyWebhooksToBase64 = stringifyWebhooksToBase64;
|
|
10
|
-
exports.maybeCompressValue = maybeCompressValue;
|
|
11
|
-
exports.sliceArrayByByteLength = sliceArrayByByteLength;
|
|
12
|
-
exports.isNode = isNode;
|
|
13
|
-
exports.isBuffer = isBuffer;
|
|
14
|
-
exports.isStream = isStream;
|
|
15
|
-
exports.getVersionData = getVersionData;
|
|
16
|
-
exports.cast = cast;
|
|
17
|
-
exports.asArray = asArray;
|
|
18
|
-
exports.applyQueryParamsToUrl = applyQueryParamsToUrl;
|
|
19
|
-
exports.toPathSegment = toPathSegment;
|
|
20
|
-
exports.toPath = toPath;
|
|
21
|
-
const zod_1 = require("zod");
|
|
22
|
-
const argument_validation_error_1 = require("./argument_validation_error");
|
|
23
|
-
const NOT_FOUND_STATUS_CODE = 404;
|
|
24
|
-
const RECORD_NOT_FOUND_TYPE = 'record-not-found';
|
|
25
|
-
const RECORD_OR_TOKEN_NOT_FOUND_TYPE = 'record-or-token-not-found';
|
|
26
|
-
const MIN_COMPRESS_BYTES = 1024;
|
|
27
|
-
// Zod installs its English locale as a module-level side effect but ships `"sideEffects": false`, so
|
|
28
|
-
// any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
|
|
29
|
-
// in per parse keeps them intact without reaching into the zod config the whole process shares.
|
|
30
|
-
const { localeError } = zod_1.z.locales.en();
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { NotFoundError } from './apify_api_error.js';
|
|
3
|
+
import { parseArgument } from '@apify/validations';
|
|
4
|
+
import { ResponseValidationError } from './response_validation_error.js';
|
|
5
|
+
// @ts-ignore if we enable `resolveJsonModule`, we end up with a `src` folder in `dist`
|
|
6
|
+
import packageJson from '../package.json' with { type: 'json' };
|
|
31
7
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* The optional `label` names the interface being validated and is appended to every error line
|
|
36
|
-
* (e.g. ``... at `memory` in `ActorStartOptions` ``).
|
|
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.
|
|
37
11
|
* @internal
|
|
38
12
|
*/
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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'];
|
|
62
|
+
export { parseArgument };
|
|
46
63
|
/**
|
|
47
64
|
* Accepts any non-null, non-array object as a predicate for `z.custom()`.
|
|
48
65
|
* @internal
|
|
49
66
|
*/
|
|
50
|
-
function isNonArrayObject(value) {
|
|
67
|
+
export function isNonArrayObject(value) {
|
|
51
68
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
52
69
|
}
|
|
53
70
|
/**
|
|
@@ -56,229 +73,209 @@ function isNonArrayObject(value) {
|
|
|
56
73
|
* the value itself instead of a copy.
|
|
57
74
|
* @internal
|
|
58
75
|
*/
|
|
59
|
-
|
|
76
|
+
export const anyObjectSchema = z.custom(isNonArrayObject, {
|
|
60
77
|
error: 'Invalid input: expected an object',
|
|
61
78
|
});
|
|
79
|
+
// Zod installs its English locale as a module-level side effect but ships `"sideEffects": false`, so
|
|
80
|
+
// any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
|
|
81
|
+
// in per parse keeps them intact without reaching into the zod config the whole process shares.
|
|
82
|
+
const { localeError } = z.locales.en();
|
|
83
|
+
const RESPONSE_ENVELOPE_SCHEMA = z.object({ data: z.unknown() });
|
|
62
84
|
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
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.
|
|
90
|
+
*
|
|
91
|
+
* Throws {@link ResponseValidationError} when the response does not match the specification.
|
|
92
|
+
* @internal
|
|
65
93
|
*/
|
|
66
|
-
function
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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;
|
|
101
|
+
const result = schema.safeParse(data, { error: localeError });
|
|
102
|
+
if (!result.success) {
|
|
103
|
+
throw new ResponseValidationError(result.error, data, { method, url });
|
|
70
104
|
}
|
|
71
|
-
|
|
105
|
+
return result.data;
|
|
72
106
|
}
|
|
73
107
|
/**
|
|
74
|
-
*
|
|
75
|
-
* Otherwise rethrows error.
|
|
108
|
+
* Swallows a 404 Not Found API error and rethrows anything else.
|
|
76
109
|
*/
|
|
77
|
-
function catchNotFoundOrThrow(err) {
|
|
78
|
-
|
|
79
|
-
const isNotFoundMessage = err.type === RECORD_NOT_FOUND_TYPE || err.type === RECORD_OR_TOKEN_NOT_FOUND_TYPE || err.httpMethod === 'head';
|
|
80
|
-
const isNotFoundError = isNotFoundStatus && isNotFoundMessage;
|
|
81
|
-
if (!isNotFoundError)
|
|
110
|
+
export function catchNotFoundOrThrow(err) {
|
|
111
|
+
if (!(err instanceof NotFoundError))
|
|
82
112
|
throw err;
|
|
83
113
|
}
|
|
84
114
|
/**
|
|
85
|
-
*
|
|
86
|
-
* "createdAt").
|
|
115
|
+
* Like `catchNotFoundOrThrow()`, but swallows the 404 only when the client names its resource by ID.
|
|
87
116
|
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* If the field cannot be converted to Date, it is left as is.
|
|
117
|
+
* A chained client without an ID, such as `run.dataset()` or `run.log()`, requests a path where a 404 can mean either
|
|
118
|
+
* the parent or the default sub-resource is missing. The response cannot tell the two apart, so the error propagates.
|
|
119
|
+
* @internal
|
|
93
120
|
*/
|
|
94
|
-
function
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
// array spend a level.
|
|
99
|
-
//
|
|
100
|
-
// In a list response it also reaches one level into caller-owned blobs the API stores verbatim, so a
|
|
101
|
-
// listed request's `userData.foo.somethingAt` comes back as a `Date` rather than the string it was
|
|
102
|
-
// written as.
|
|
103
|
-
// TODO: Consider removing this limitation. It might came across as an annoying surprise as it's not communicated.
|
|
104
|
-
if (depth > 4) {
|
|
105
|
-
return input;
|
|
106
|
-
}
|
|
107
|
-
if (Array.isArray(input))
|
|
108
|
-
return input.map((child) => parseDateFields(child, shouldParseField, depth + 1));
|
|
109
|
-
if (!input || typeof input !== 'object')
|
|
110
|
-
return input;
|
|
111
|
-
return Object.entries(input).reduce((output, [k, v]) => {
|
|
112
|
-
const isValObject = !!v && typeof v === 'object';
|
|
113
|
-
if (k.endsWith('At') || (shouldParseField && shouldParseField(k))) {
|
|
114
|
-
if (v) {
|
|
115
|
-
const d = new Date(v);
|
|
116
|
-
output[k] = Number.isNaN(d.getTime()) ? v : d;
|
|
117
|
-
}
|
|
118
|
-
else {
|
|
119
|
-
output[k] = v;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
else if (isValObject || Array.isArray(v)) {
|
|
123
|
-
output[k] = parseDateFields(v, shouldParseField, depth + 1);
|
|
124
|
-
}
|
|
125
|
-
else {
|
|
126
|
-
output[k] = v;
|
|
127
|
-
}
|
|
128
|
-
return output;
|
|
129
|
-
}, {});
|
|
121
|
+
export function catchNotFoundForResourceOrThrow(err, resourceId) {
|
|
122
|
+
if (!resourceId)
|
|
123
|
+
throw err;
|
|
124
|
+
catchNotFoundOrThrow(err);
|
|
130
125
|
}
|
|
131
126
|
/**
|
|
132
127
|
* Helper function that converts array of webhooks to base64 string
|
|
133
128
|
*/
|
|
134
|
-
function stringifyWebhooksToBase64(webhooks) {
|
|
129
|
+
export function stringifyWebhooksToBase64(webhooks) {
|
|
135
130
|
if (!webhooks)
|
|
136
131
|
return;
|
|
137
|
-
|
|
138
|
-
if (isNode()) {
|
|
139
|
-
return Buffer.from(webhooksJson, 'utf8').toString('base64');
|
|
140
|
-
}
|
|
141
|
-
const encoder = new TextEncoder();
|
|
142
|
-
const uint8Array = encoder.encode(webhooksJson);
|
|
143
|
-
return btoa(String.fromCharCode(...uint8Array));
|
|
132
|
+
return bytesToBase64(textEncoder.encode(JSON.stringify(webhooks)));
|
|
144
133
|
}
|
|
145
|
-
let brotliCompressPromisified;
|
|
146
134
|
/**
|
|
147
|
-
*
|
|
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.
|
|
148
138
|
*/
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const options = { params: { [constants.BROTLI_PARAM_QUALITY]: 6 } };
|
|
155
|
-
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));
|
|
156
144
|
}
|
|
157
|
-
return
|
|
145
|
+
return btoa(binary);
|
|
158
146
|
}
|
|
159
|
-
let gzipPromisified;
|
|
160
147
|
/**
|
|
161
|
-
*
|
|
148
|
+
* Concatenates byte chunks into one array.
|
|
162
149
|
*/
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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;
|
|
168
156
|
}
|
|
169
|
-
return
|
|
157
|
+
return result;
|
|
170
158
|
}
|
|
171
159
|
/**
|
|
172
|
-
*
|
|
173
|
-
*
|
|
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
|
|
174
163
|
*/
|
|
175
|
-
|
|
176
|
-
if (
|
|
177
|
-
return
|
|
178
|
-
|
|
179
|
-
// skip it instead of throwing for unsupported types.
|
|
180
|
-
if (typeof value !== 'string' && !Buffer.isBuffer(value))
|
|
181
|
-
return undefined;
|
|
182
|
-
const areDataLargeEnough = Buffer.byteLength(value) >= MIN_COMPRESS_BYTES;
|
|
183
|
-
if (!areDataLargeEnough)
|
|
184
|
-
return undefined;
|
|
185
|
-
try {
|
|
186
|
-
return { data: await brotliValue(value), encoding: 'br' };
|
|
187
|
-
}
|
|
188
|
-
catch {
|
|
189
|
-
// Runtimes that only provide a partial `node:zlib` (bundler polyfills, edge runtimes with
|
|
190
|
-
// Node compatibility shims) may not implement brotli, but usually do implement gzip.
|
|
191
|
-
}
|
|
192
|
-
try {
|
|
193
|
-
return { data: await gzipValue(value), encoding: 'gzip' };
|
|
194
|
-
}
|
|
195
|
-
catch {
|
|
196
|
-
// Same reasoning as above: compression is a best-effort optimization, so skip it instead
|
|
197
|
-
// of failing the request.
|
|
164
|
+
export function toBytes(value) {
|
|
165
|
+
if (typeof value === 'string')
|
|
166
|
+
return textEncoder.encode(value);
|
|
167
|
+
if (!isBuffer(value))
|
|
198
168
|
return undefined;
|
|
199
|
-
|
|
169
|
+
return ArrayBuffer.isView(value)
|
|
170
|
+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
|
|
171
|
+
: new Uint8Array(value);
|
|
200
172
|
}
|
|
201
173
|
/**
|
|
202
|
-
*
|
|
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;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Returns the UTF-8 byte length of a string.
|
|
203
|
+
*/
|
|
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.
|
|
203
212
|
*/
|
|
204
|
-
function
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
throw new Error(`RequestQueueClient.batchAddRequests: The size of the request with index: ${startIndex + i} ` +
|
|
216
|
-
`exceeds the maximum allowed size (${maxByteLength} bytes).`);
|
|
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;
|
|
217
224
|
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
byteLength += itemByteSize;
|
|
221
|
-
slicedArray.push(item);
|
|
225
|
+
batch.push(item);
|
|
226
|
+
byteLength += item.byteLength + 1;
|
|
222
227
|
}
|
|
223
|
-
|
|
228
|
+
if (batch.length > 0)
|
|
229
|
+
batches.push(batch);
|
|
230
|
+
return batches;
|
|
224
231
|
}
|
|
225
|
-
function
|
|
226
|
-
if (typeof BROWSER_BUILD !== 'undefined')
|
|
227
|
-
return false;
|
|
228
|
-
return !!(typeof process !== 'undefined' && process.versions && process.versions.node);
|
|
229
|
-
}
|
|
230
|
-
function isBuffer(value) {
|
|
232
|
+
export function isBuffer(value) {
|
|
231
233
|
// Tag checks rather than `instanceof`, to also match buffers from another realm. `isView()`
|
|
232
234
|
// additionally covers `DataView`, which is not raw binary content.
|
|
233
235
|
if (ArrayBuffer.isView(value))
|
|
234
236
|
return !isTagged(value, 'DataView');
|
|
235
237
|
return isTagged(value, 'ArrayBuffer');
|
|
236
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
|
+
}
|
|
237
246
|
function isTagged(value, tag) {
|
|
238
247
|
return Object.prototype.toString.call(value) === `[object ${tag}]`;
|
|
239
248
|
}
|
|
240
|
-
function isStream(value) {
|
|
249
|
+
export function isStream(value) {
|
|
241
250
|
if (value === null || typeof value !== 'object')
|
|
242
251
|
return false;
|
|
243
252
|
const { on, pipe } = value;
|
|
244
253
|
return typeof on === 'function' && typeof pipe === 'function';
|
|
245
254
|
}
|
|
246
|
-
function getVersionData() {
|
|
247
|
-
if (typeof BROWSER_BUILD !== 'undefined') {
|
|
248
|
-
return { version: VERSION };
|
|
249
|
-
}
|
|
250
|
-
// eslint-disable-next-line
|
|
251
|
-
return require('../package.json');
|
|
252
|
-
}
|
|
253
255
|
/**
|
|
254
|
-
* Helper class to create async iterators from paginated list endpoints
|
|
256
|
+
* Helper class to create async iterators from paginated list endpoints.
|
|
255
257
|
*/
|
|
256
|
-
class RequestQueuePaginationIterator {
|
|
257
|
-
maxPageLimit;
|
|
258
|
-
getPage;
|
|
259
|
-
limit;
|
|
260
|
-
|
|
261
|
-
cursor;
|
|
258
|
+
export class RequestQueuePaginationIterator {
|
|
259
|
+
#maxPageLimit;
|
|
260
|
+
#getPage;
|
|
261
|
+
#limit;
|
|
262
|
+
#cursor;
|
|
262
263
|
constructor(options) {
|
|
263
|
-
this
|
|
264
|
-
this
|
|
265
|
-
this
|
|
266
|
-
this
|
|
267
|
-
this.getPage = options.getPage;
|
|
264
|
+
this.#maxPageLimit = options.maxPageLimit;
|
|
265
|
+
this.#limit = options.limit;
|
|
266
|
+
this.#cursor = options.cursor;
|
|
267
|
+
this.#getPage = options.getPage;
|
|
268
268
|
}
|
|
269
269
|
async *[Symbol.asyncIterator]() {
|
|
270
|
-
let nextCursor = this
|
|
271
|
-
// allow using exclusiveStartId for the first page, but then we'll delete it to avoid using it for any later page
|
|
272
|
-
let nextExclusiveStartId = this.exclusiveStartId;
|
|
270
|
+
let nextCursor = this.#cursor;
|
|
273
271
|
let iterateItemCount = 0;
|
|
274
272
|
while (true) {
|
|
275
|
-
const pageLimit = this
|
|
276
|
-
? Math.min(this
|
|
277
|
-
: this
|
|
278
|
-
const page = await this
|
|
273
|
+
const pageLimit = this.#limit
|
|
274
|
+
? Math.min(this.#maxPageLimit, this.#limit - iterateItemCount)
|
|
275
|
+
: this.#maxPageLimit;
|
|
276
|
+
const page = await this.#getPage({
|
|
279
277
|
limit: pageLimit,
|
|
280
278
|
cursor: nextCursor,
|
|
281
|
-
exclusiveStartId: nextExclusiveStartId,
|
|
282
279
|
});
|
|
283
280
|
// There are no more pages to iterate
|
|
284
281
|
if (page.items.length === 0)
|
|
@@ -286,28 +283,42 @@ class RequestQueuePaginationIterator {
|
|
|
286
283
|
yield page;
|
|
287
284
|
iterateItemCount += page.items.length;
|
|
288
285
|
// Limit reached stopping to iterate
|
|
289
|
-
if ((this
|
|
286
|
+
if ((this.#limit && iterateItemCount >= this.#limit) || !page.nextCursor)
|
|
290
287
|
return;
|
|
291
288
|
nextCursor = page.nextCursor;
|
|
292
|
-
nextExclusiveStartId = undefined; // see comment above - delete it for any page after the first one, and paginate with cursor
|
|
293
289
|
}
|
|
294
290
|
}
|
|
295
291
|
}
|
|
296
|
-
|
|
292
|
+
/**
|
|
293
|
+
* The smaller of two page limits, for the `limit` query parameter. The API treats a `limit` of 0 as unset, so 0 here
|
|
294
|
+
* means no limit and loses to any other value.
|
|
295
|
+
* @internal
|
|
296
|
+
*/
|
|
297
|
+
export function minForLimitParam(a, b) {
|
|
298
|
+
if (a === 0)
|
|
299
|
+
a = undefined;
|
|
300
|
+
if (b === 0)
|
|
301
|
+
b = undefined;
|
|
302
|
+
if (a === undefined)
|
|
303
|
+
return b;
|
|
304
|
+
if (b === undefined)
|
|
305
|
+
return a;
|
|
306
|
+
return Math.min(a, b);
|
|
307
|
+
}
|
|
297
308
|
/**
|
|
298
309
|
* Schema shape of {@link PaginationOptions}, to spread into every paginating client's list schema. One
|
|
299
310
|
* copy stops it drifting from the interface.
|
|
300
311
|
* @internal
|
|
301
312
|
*/
|
|
302
|
-
|
|
303
|
-
limit:
|
|
304
|
-
offset:
|
|
305
|
-
chunkSize:
|
|
313
|
+
export const paginationOptionsShape = {
|
|
314
|
+
limit: z.number().min(0).optional(),
|
|
315
|
+
offset: z.number().min(0).optional(),
|
|
316
|
+
chunkSize: z.number().positive().optional(),
|
|
306
317
|
};
|
|
307
|
-
function cast(input) {
|
|
318
|
+
export function cast(input) {
|
|
308
319
|
return input;
|
|
309
320
|
}
|
|
310
|
-
function asArray(value) {
|
|
321
|
+
export function asArray(value) {
|
|
311
322
|
if (Array.isArray(value)) {
|
|
312
323
|
return value;
|
|
313
324
|
}
|
|
@@ -316,7 +327,7 @@ function asArray(value) {
|
|
|
316
327
|
/**
|
|
317
328
|
* Adds query parameters to a given URL based on the provided options object.
|
|
318
329
|
*/
|
|
319
|
-
function applyQueryParamsToUrl(url, options) {
|
|
330
|
+
export function applyQueryParamsToUrl(url, options) {
|
|
320
331
|
for (const [key, value] of Object.entries(options ?? {})) {
|
|
321
332
|
// skip undefined values
|
|
322
333
|
if (value === undefined)
|
|
@@ -330,17 +341,7 @@ function applyQueryParamsToUrl(url, options) {
|
|
|
330
341
|
}
|
|
331
342
|
return url;
|
|
332
343
|
}
|
|
333
|
-
|
|
334
|
-
* Builds a `[check, message]` pair to spread into `.refine()`, asserting that at most one of `keys`
|
|
335
|
-
* is present. Pass the options interface as `T`, so that a misspelled key is a type error.
|
|
336
|
-
* @internal
|
|
337
|
-
*/
|
|
338
|
-
const mutuallyExclusive = (...keys) => [
|
|
339
|
-
(value) => keys.filter((key) => typeof value[key] !== 'undefined').length <= 1,
|
|
340
|
-
`At most one of the following fields is allowed: ${keys.join(', ')}`,
|
|
341
|
-
];
|
|
342
|
-
exports.mutuallyExclusive = mutuallyExclusive;
|
|
343
|
-
const pathSegmentSchema = zod_1.z
|
|
344
|
+
const pathSegmentSchema = z
|
|
344
345
|
.string()
|
|
345
346
|
.nonempty()
|
|
346
347
|
.refine((v) => v !== '.' && v !== '..', { error: 'URL path must not contain dot segments' });
|
|
@@ -350,7 +351,7 @@ const pathSegmentSchema = zod_1.z
|
|
|
350
351
|
* Empty strings and dot segments are rejected instead of encoded, because URL parsers resolve
|
|
351
352
|
* dot segments after decoding - `records/%2E%2E` collapses to the parent endpoint just like `records/..`.
|
|
352
353
|
*/
|
|
353
|
-
function toPathSegment(value) {
|
|
354
|
+
export function toPathSegment(value) {
|
|
354
355
|
const valueParsed = parseArgument(value, pathSegmentSchema);
|
|
355
356
|
return encodeURIComponent(valueParsed);
|
|
356
357
|
}
|
|
@@ -358,6 +359,27 @@ function toPathSegment(value) {
|
|
|
358
359
|
* Builds a URL path from segments. A plain string is used as-is, so literal paths such as
|
|
359
360
|
* `requests/batch` keep their separators; an array has each of its segments encoded individually.
|
|
360
361
|
*/
|
|
361
|
-
function toPath(path) {
|
|
362
|
+
export function toPath(path) {
|
|
362
363
|
return Array.isArray(path) ? path.map(toPathSegment).join('/') : path;
|
|
363
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* Resolves after `millis`, or right away once `signal` aborts.
|
|
367
|
+
* @internal
|
|
368
|
+
*/
|
|
369
|
+
export async function sleep(millis, signal) {
|
|
370
|
+
return new Promise((resolve) => {
|
|
371
|
+
if (signal?.aborted) {
|
|
372
|
+
resolve();
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const onAbort = () => {
|
|
376
|
+
clearTimeout(timer);
|
|
377
|
+
resolve();
|
|
378
|
+
};
|
|
379
|
+
const timer = setTimeout(() => {
|
|
380
|
+
signal?.removeEventListener('abort', onAbort);
|
|
381
|
+
resolve();
|
|
382
|
+
}, millis);
|
|
383
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
384
|
+
});
|
|
385
|
+
}
|
|
@@ -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
|
+
}
|