apify-client 3.0.0-rc.1 → 3.0.0-rc.2
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 +4 -2
- package/dist/apify_api_error.d.ts +2 -2
- package/dist/apify_client.d.ts +8 -8
- package/dist/apify_client.js +10 -10
- package/dist/axios.d.ts +2 -0
- package/dist/axios.js +1 -0
- package/dist/body_parser.d.ts +1 -1
- package/dist/bundle.js +31 -30
- package/dist/bundle.js.map +1 -1
- package/dist/generated/api.d.ts +124 -32
- package/dist/generated/schemas.d.ts +178 -58
- package/dist/generated/schemas.js +23 -6
- package/dist/http_clients/axios.d.ts +34 -15
- package/dist/http_clients/axios.js +79 -33
- package/dist/http_clients/base.d.ts +34 -23
- package/dist/http_clients/base.js +50 -20
- package/dist/http_clients/fetch.d.ts +53 -0
- package/dist/http_clients/fetch.js +219 -0
- package/dist/http_clients/index.d.ts +2 -2
- package/dist/http_clients/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/resource_clients/actor.d.ts +3 -2
- package/dist/resource_clients/actor.js +3 -3
- package/dist/resource_clients/actor_server.d.ts +11 -11
- package/dist/resource_clients/actor_server.js +0 -4
- package/dist/resource_clients/actor_version.d.ts +2 -1
- package/dist/resource_clients/actor_version.js +3 -2
- package/dist/resource_clients/actor_version_collection.d.ts +2 -1
- package/dist/resource_clients/actor_version_collection.js +3 -2
- package/dist/resource_clients/dataset.d.ts +14 -15
- package/dist/resource_clients/dataset.js +0 -4
- package/dist/resource_clients/key_value_store.d.ts +20 -19
- package/dist/resource_clients/key_value_store.js +10 -11
- package/dist/resource_clients/log.d.ts +10 -11
- package/dist/resource_clients/log.js +4 -3
- package/dist/resource_clients/run.d.ts +6 -2
- package/dist/resource_clients/run.js +6 -2
- package/dist/resource_clients/store_collection.d.ts +4 -0
- package/dist/resource_clients/task.js +3 -3
- package/dist/runtime/node.js +35 -11
- package/dist/runtime/types.d.ts +26 -4
- package/dist/runtime/web.js +39 -0
- package/dist/schemas.d.ts +4 -4
- package/dist/utils.d.ts +29 -1
- package/dist/utils.js +13 -0
- package/package.json +33 -21
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { runtime } from '#runtime';
|
|
2
|
+
import { ApifyClientError } from '../apify_client_error.js';
|
|
3
|
+
import { isAnyStream, isStream, isWebStream } from '../utils.js';
|
|
4
|
+
import { HttpClient } from './base.js';
|
|
5
|
+
/** Error codes of the timeouts that Node.js reports as the `cause` of a failed `fetch`. */
|
|
6
|
+
const TIMEOUT_ERROR_CODES = new Set([
|
|
7
|
+
'ETIMEDOUT',
|
|
8
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
9
|
+
'UND_ERR_HEADERS_TIMEOUT',
|
|
10
|
+
'UND_ERR_BODY_TIMEOUT',
|
|
11
|
+
]);
|
|
12
|
+
/** Error codes of a request that Node.js or Bun refused to send, so sending it again fails the same way. */
|
|
13
|
+
const INVALID_REQUEST_ERROR_CODES = new Set([
|
|
14
|
+
'ERR_INVALID_URL',
|
|
15
|
+
'ERR_INVALID_ARG_TYPE',
|
|
16
|
+
'ERR_INVALID_ARG_VALUE',
|
|
17
|
+
'UND_ERR_INVALID_ARG',
|
|
18
|
+
'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH',
|
|
19
|
+
]);
|
|
20
|
+
/**
|
|
21
|
+
* The default HTTP client of {@link ApifyClient}, built on the `fetch` of the runtime, so it works the same way in
|
|
22
|
+
* Node.js, browsers and edge runtimes and brings no dependency of its own.
|
|
23
|
+
*
|
|
24
|
+
* It inherits the request pipeline from {@link HttpClient} and adds the transport. Network errors are retried,
|
|
25
|
+
* timeouts included, and a stream body is sent without following redirects, since the part of it already sent could
|
|
26
|
+
* not be replayed. The timeout of a request runs until the response headers arrive and starts over with every chunk
|
|
27
|
+
* of the response body and of a stream body, so a large download or upload does not time out while it makes progress.
|
|
28
|
+
*
|
|
29
|
+
* In Node.js, `fetch` keeps connections alive on its own, and goes through a proxy only when Node.js is told to
|
|
30
|
+
* read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables: start it with `NODE_USE_ENV_PROXY=1`
|
|
31
|
+
* (Node.js 22.21 and 24.0) or `--use-env-proxy` (Node.js 22.21 and 24.5).
|
|
32
|
+
*/
|
|
33
|
+
export class FetchHttpClient extends HttpClient {
|
|
34
|
+
#fetch;
|
|
35
|
+
constructor(options = {}) {
|
|
36
|
+
super(options);
|
|
37
|
+
this.#fetch = options.fetch;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A timeout is the `TimeoutError` this client aborts a late request with, or a `fetch` failure caused by one of
|
|
41
|
+
* the connection, headers and body timeouts of Node.js.
|
|
42
|
+
*/
|
|
43
|
+
isTimeoutError(error) {
|
|
44
|
+
if (super.isTimeoutError(error))
|
|
45
|
+
return true;
|
|
46
|
+
const code = causeCode(error);
|
|
47
|
+
return code !== undefined && TIMEOUT_ERROR_CODES.has(code);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A network failure is the `TypeError` that `fetch` rejects with: a connection that could not be made, dropped
|
|
51
|
+
* mid-way or timed out. In Node.js it carries the failure as its `cause`, which tells it apart from a request
|
|
52
|
+
* that was never sent, such as one with an invalid URL. Bun rejects with an `Error` that has a `code` instead.
|
|
53
|
+
*/
|
|
54
|
+
isRetryableTransportError(error) {
|
|
55
|
+
if (this.isTimeoutError(error))
|
|
56
|
+
return true;
|
|
57
|
+
const code = causeCode(error) ?? errorCode(error);
|
|
58
|
+
if (code !== undefined && INVALID_REQUEST_ERROR_CODES.has(code))
|
|
59
|
+
return false;
|
|
60
|
+
if (runtime.fetchFailsWithCause)
|
|
61
|
+
return error instanceof TypeError && error.cause !== undefined;
|
|
62
|
+
// Browsers and Deno fail with a bare `TypeError` whatever the reason, and Bun with an error that has a `code`.
|
|
63
|
+
return error instanceof TypeError || code !== undefined;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Sends the request through `fetch` and hands the raw response back. A stream body is sent without following
|
|
67
|
+
* redirects, and so is a request with `followRedirects: false`. A browser hides such a redirect response from
|
|
68
|
+
* the page, so there it fails the request.
|
|
69
|
+
*/
|
|
70
|
+
async sendRequest(request) {
|
|
71
|
+
const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
|
|
72
|
+
// `AbortSignal.timeout()` could neither be restarted nor called off.
|
|
73
|
+
const timeout = new AbortController();
|
|
74
|
+
let timer;
|
|
75
|
+
let settled = false;
|
|
76
|
+
const restartTimeout = () => {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
// The transport may still read a stream body after the response arrived.
|
|
79
|
+
if (timeoutMillis === undefined || settled)
|
|
80
|
+
return;
|
|
81
|
+
timer = setTimeout(() => timeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError')), timeoutMillis);
|
|
82
|
+
};
|
|
83
|
+
restartTimeout();
|
|
84
|
+
let sentBody;
|
|
85
|
+
try {
|
|
86
|
+
// Browsers and Deno reject an invalid URL with the same bare `TypeError` as a network failure.
|
|
87
|
+
const baseUrl = globalThis.location?.href;
|
|
88
|
+
if (!runtime.fetchFailsWithCause && !URL.canParse(url, baseUrl)) {
|
|
89
|
+
throw Object.assign(new TypeError(`Invalid URL: ${url}`), { code: 'ERR_INVALID_URL' });
|
|
90
|
+
}
|
|
91
|
+
sentBody = trackProgress(body, restartTimeout);
|
|
92
|
+
const response = await (this.#fetch ?? globalThis.fetch)(url, {
|
|
93
|
+
method,
|
|
94
|
+
headers,
|
|
95
|
+
body: sentBody,
|
|
96
|
+
redirect: followRedirects && !isAnyStream(body) ? 'follow' : 'manual',
|
|
97
|
+
signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
|
|
98
|
+
// Required for a stream body, and ignored for any other.
|
|
99
|
+
...(isAnyStream(body) ? { duplex: 'half' } : {}),
|
|
100
|
+
});
|
|
101
|
+
// `redirect: 'manual'` resolves to an opaque response with status 0 in a browser.
|
|
102
|
+
if (response.type === 'opaqueredirect') {
|
|
103
|
+
throw new ApifyClientError(`${method} ${url} responded with a redirect, which the client does not follow.`);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
status: response.status,
|
|
107
|
+
headers: toResponseHeaders(response.headers),
|
|
108
|
+
// The timeout covers a streamed response only until its headers, and the caller's signal throughout.
|
|
109
|
+
body: stream ? (response.body ?? new Blob([]).stream()) : await readBody(response, restartTimeout),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
// A `fetch` that refused the request never took the body over, which keeps the caller's stream locked.
|
|
114
|
+
if (isWebStream(sentBody) && !sentBody.locked)
|
|
115
|
+
sentBody.cancel(error).catch(() => { });
|
|
116
|
+
if (!this.#fetch && this.isRetryableTransportError(error))
|
|
117
|
+
this.#warnAboutUnusedProxy();
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
settled = true;
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** A proxy the environment names and Node.js ignores is the likeliest reason for a connection to fail. */
|
|
126
|
+
#warnAboutUnusedProxy() {
|
|
127
|
+
const hint = runtime.unusedProxyHint();
|
|
128
|
+
if (hint)
|
|
129
|
+
this.logger.warningOnce(hint);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Bun reads a stream body ahead of sending it, so reading it there says nothing about the progress. */
|
|
133
|
+
const isBun = 'Bun' in globalThis;
|
|
134
|
+
/** A larger chunk of a stream body is passed on in pieces, since a `Blob` held in memory arrives as a single one. */
|
|
135
|
+
const MAX_BODY_CHUNK_BYTES = 64 * 1024;
|
|
136
|
+
/** Makes a stream body report every chunk that `fetch` reads from it, and leaves any other body as it is. */
|
|
137
|
+
function trackProgress(body, onChunk) {
|
|
138
|
+
if (isWebStream(body))
|
|
139
|
+
return withWebProgress(body, onChunk);
|
|
140
|
+
// Node.js reads an async iterable, which the DOM types do not know about.
|
|
141
|
+
if (isStream(body) && !isBun)
|
|
142
|
+
return withProgress(body, onChunk);
|
|
143
|
+
return body;
|
|
144
|
+
}
|
|
145
|
+
/** Passes a stream body on piece by piece, so that a large upload counts as alive for as long as it is being read. */
|
|
146
|
+
async function* withProgress(body, onChunk) {
|
|
147
|
+
for await (const chunk of body) {
|
|
148
|
+
// Deno refuses the string chunks of a stream with an encoding.
|
|
149
|
+
const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
|
|
150
|
+
if (!(bytes instanceof Uint8Array) || bytes.byteLength <= MAX_BODY_CHUNK_BYTES) {
|
|
151
|
+
onChunk();
|
|
152
|
+
yield bytes;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
for (let offset = 0; offset < bytes.byteLength; offset += MAX_BODY_CHUNK_BYTES) {
|
|
156
|
+
onChunk();
|
|
157
|
+
yield bytes.subarray(offset, offset + MAX_BODY_CHUNK_BYTES);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** Does for a web stream body what {@link withProgress} does for an async iterable. */
|
|
162
|
+
function withWebProgress(body, onChunk) {
|
|
163
|
+
const reader = body.getReader();
|
|
164
|
+
let rest;
|
|
165
|
+
return new ReadableStream({
|
|
166
|
+
async pull(controller) {
|
|
167
|
+
if (!rest?.byteLength) {
|
|
168
|
+
const { done, value } = await reader.read();
|
|
169
|
+
if (done)
|
|
170
|
+
return controller.close();
|
|
171
|
+
rest = value;
|
|
172
|
+
}
|
|
173
|
+
onChunk();
|
|
174
|
+
controller.enqueue(rest.subarray(0, MAX_BODY_CHUNK_BYTES));
|
|
175
|
+
rest = rest.subarray(MAX_BODY_CHUNK_BYTES);
|
|
176
|
+
},
|
|
177
|
+
async cancel(reason) {
|
|
178
|
+
await reader.cancel(reason);
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
// Reads a piece only once `fetch` asks for it.
|
|
182
|
+
{ highWaterMark: 0 });
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Reads the response body chunk by chunk, so that a large download counts as alive for as long as bytes arrive.
|
|
186
|
+
*/
|
|
187
|
+
async function readBody(response, onChunk) {
|
|
188
|
+
const chunks = [];
|
|
189
|
+
let length = 0;
|
|
190
|
+
const reader = response.body?.getReader();
|
|
191
|
+
for (let chunk = await reader?.read(); chunk && !chunk.done; chunk = await reader?.read()) {
|
|
192
|
+
onChunk();
|
|
193
|
+
chunks.push(chunk.value);
|
|
194
|
+
length += chunk.value.byteLength;
|
|
195
|
+
}
|
|
196
|
+
const bytes = new Uint8Array(length);
|
|
197
|
+
let offset = 0;
|
|
198
|
+
for (const chunk of chunks) {
|
|
199
|
+
bytes.set(chunk, offset);
|
|
200
|
+
offset += chunk.byteLength;
|
|
201
|
+
}
|
|
202
|
+
return bytes;
|
|
203
|
+
}
|
|
204
|
+
function toResponseHeaders(headers) {
|
|
205
|
+
const result = Object.fromEntries(headers);
|
|
206
|
+
// `fetch` joins repeated headers with a comma, which a cookie's `Expires` date makes ambiguous.
|
|
207
|
+
const cookies = headers.getSetCookie?.() ?? [];
|
|
208
|
+
if (cookies.length > 0)
|
|
209
|
+
result['set-cookie'] = cookies;
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
/** Reads the `code` of the error that caused a `fetch` failure, which is where Node.js puts the network error. */
|
|
213
|
+
function causeCode(error) {
|
|
214
|
+
return errorCode(error instanceof Error ? error.cause : undefined);
|
|
215
|
+
}
|
|
216
|
+
function errorCode(error) {
|
|
217
|
+
const code = error?.code;
|
|
218
|
+
return typeof code === 'string' ? code : undefined;
|
|
219
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { AxiosHttpClientOptions, RequestInterceptorFunction } from './axios.js';
|
|
2
|
-
export { AxiosHttpClient } from './axios.js';
|
|
3
1
|
export type { ApifyRequestConfig, ApifyResponse, ApifyResponseType, HttpClientOptions, HttpMethod, HttpRequest, HttpRequestBody, HttpResponse, HttpResponseBody, HttpResponseHeaders, } from './base.js';
|
|
4
2
|
export { HttpClient } from './base.js';
|
|
3
|
+
export type { FetchFunction, FetchHttpClientOptions } from './fetch.js';
|
|
4
|
+
export { FetchHttpClient } from './fetch.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -34,5 +34,5 @@ export * from './response_validation_error.js';
|
|
|
34
34
|
export * from './invalid_response_body_error.js';
|
|
35
35
|
export * from './http_clients/index.js';
|
|
36
36
|
export * from './http_compressors/index.js';
|
|
37
|
-
export type { PaginatedList, Dictionary } from './utils.js';
|
|
37
|
+
export type { AnyString, PaginatedList, Dictionary, JsonValue, TypedArray } from './utils.js';
|
|
38
38
|
export type { Timeout, TimeoutOptions, TimeoutTier } from './timeouts.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ValueOf } from '@apify/consts';
|
|
1
2
|
import { ACTOR_JOB_STATUSES, ACTOR_PERMISSION_LEVEL, META_ORIGINS } from '@apify/consts';
|
|
2
3
|
import { Log } from '@apify/log';
|
|
3
4
|
import type { ApiClientSubResourceOptions } from '../base/api_client.js';
|
|
@@ -15,7 +16,6 @@ import { RunClient } from './run.js';
|
|
|
15
16
|
import { RunCollectionClient } from './run_collection.js';
|
|
16
17
|
import type { WebhookUpdateData } from './webhook.js';
|
|
17
18
|
import { WebhookCollectionClient } from './webhook_collection.js';
|
|
18
|
-
import type { ValueOf } from 'type-fest';
|
|
19
19
|
export type { ActorResource, ActorChargeEvent, ActorChargeEvents, ActorDefinition, ActorRunPricingInfo, ActorRunStorageIds, ActorStandby, ActorStats, DefaultRunOptions, ExampleRunInput, FlatPricePerMonthActorPricingInfo, FreeActorPricingInfo, RunMetamorphEvent, PayPerEventActorPricingInfo, PricePerDatasetItemActorPricingInfo, Run, RunMeta, RunOptions, RunListItem, RunStats, RunUsage, TaggedBuildInfo, TaggedBuilds, TieredPricingPerDatasetItem, TieredPricingPerDatasetItemEntry, TieredPricingPerEvent, TieredPricingPerEventEntry, } from '../models.js';
|
|
20
20
|
/**
|
|
21
21
|
* Client for managing a specific Actor.
|
|
@@ -413,7 +413,8 @@ export interface ActorStartOptions extends TimeoutOptions {
|
|
|
413
413
|
* A run that requests more memory than the whole memory limit of the account is rejected with
|
|
414
414
|
* `actor-memory-limit-exceeded` as well and never starts, so `true` retries it forever.
|
|
415
415
|
*
|
|
416
|
-
* A `Readable`
|
|
416
|
+
* A stream input (`Readable` or web `ReadableStream`) can't be sent twice, so its start is never retried and the
|
|
417
|
+
* first rejection is thrown.
|
|
417
418
|
*/
|
|
418
419
|
waitForResources?: boolean | number;
|
|
419
420
|
}
|
|
@@ -4,7 +4,7 @@ import { Log } from '@apify/log';
|
|
|
4
4
|
import { ResourceClient } from '../base/resource_client.js';
|
|
5
5
|
import * as schemas from '../schemas.js';
|
|
6
6
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
7
|
-
import { anyObjectSchema,
|
|
7
|
+
import { anyObjectSchema, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
|
|
8
8
|
import { startWaitingForResources } from '../wait_for_resources.js';
|
|
9
9
|
import { ActorServerClient } from './actor_server.js';
|
|
10
10
|
import { ActorVersionClient } from './actor_version.js';
|
|
@@ -196,8 +196,8 @@ export class ActorClient extends ResourceClient {
|
|
|
196
196
|
'content-type': parsed.contentType,
|
|
197
197
|
};
|
|
198
198
|
}
|
|
199
|
-
// A
|
|
200
|
-
const response = await startWaitingForResources(async () => this.httpClient.call(request),
|
|
199
|
+
// A stream input is consumed by the first attempt, so a retry would start the run with an empty input.
|
|
200
|
+
const response = await startWaitingForResources(async () => this.httpClient.call(request), isAnyStream(input) ? false : waitForResources, this.httpClient.logger, signal);
|
|
201
201
|
return parseResponse(response, schemas.Run());
|
|
202
202
|
}
|
|
203
203
|
/**
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Readable } from 'node:stream';
|
|
2
1
|
import type { ApiClientSubResourceOptions } from '../base/api_client.js';
|
|
3
2
|
import { ResourceClient } from '../base/resource_client.js';
|
|
4
3
|
import type { ApifyResponse, ApifyResponseType, HttpMethod } from '../http_clients/index.js';
|
|
@@ -71,9 +70,10 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
71
70
|
* The method resolves to any response of the server, error statuses included. A rate-limit (429) or Service
|
|
72
71
|
* Unavailable (503) response is retried with the client's retry settings, and the last one is returned once the
|
|
73
72
|
* retries run out. The Actor's code can return these statuses too, and then it gets the request again. A redirect
|
|
74
|
-
* is returned as it is, since following it would send the token to a host the Actor's code picked.
|
|
75
|
-
*
|
|
76
|
-
* unless `compression` is set, since the Actor's server may not decode a
|
|
73
|
+
* is returned as it is, since following it would send the token to a host the Actor's code picked. In a
|
|
74
|
+
* browser the redirect response can't be read, so the request fails with an {@link ApifyClientError} instead.
|
|
75
|
+
* Request bodies are sent uncompressed unless `compression` is set, since the Actor's server may not decode a
|
|
76
|
+
* compressed body.
|
|
77
77
|
*
|
|
78
78
|
* @template T - Type of the parsed response body.
|
|
79
79
|
* @param path - The path on the Actor's server, for example `/search`. It is always resolved against the server
|
|
@@ -84,15 +84,15 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
84
84
|
* @param options.params - Query parameters of the request, converted the same way as for API calls.
|
|
85
85
|
* @param options.headers - Additional headers of the request.
|
|
86
86
|
* @param options.data - Request body, serialized the same way as for API calls: a plain object or array is sent
|
|
87
|
-
* as JSON, and a string
|
|
87
|
+
* as JSON, and a string, binary value or stream (`Readable`, web `ReadableStream`) as it is.
|
|
88
88
|
* @param options.parentRequestId - The `X-Actor-Request-ID` header of the request your Server Actor is handling,
|
|
89
89
|
* sent on as the same header so the called Actor charges at that request's pricing tier.
|
|
90
90
|
* @param options.compression - Compression algorithm for the request body, as a name or an {@link HttpCompressor}.
|
|
91
91
|
* The body is compressed under the same conditions as for API calls. Set it only if the Actor's server decodes
|
|
92
92
|
* the resulting `Content-Encoding`.
|
|
93
93
|
* @param options.responseType - How to return the response body: `'parsed'` by its content type, `'buffer'` as
|
|
94
|
-
* raw bytes, or `'stream'` as a
|
|
95
|
-
* you consume it to the end or
|
|
94
|
+
* raw bytes in a Uint8Array, or `'stream'` as a web ReadableStream with the body unread. A stream holds its
|
|
95
|
+
* connection open until you consume it to the end or cancel it. Default is `'parsed'`.
|
|
96
96
|
* @param options.timeoutSecs - Timeout for the HTTP request. Default is `'long'`. With `'stream'`, it bounds the
|
|
97
97
|
* wait for the server to start responding.
|
|
98
98
|
* @returns The response of the Actor's server, with the body in the form `responseType` asks for. An error
|
|
@@ -108,10 +108,10 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
108
108
|
}): Promise<ApifyResponse<T>>;
|
|
109
109
|
request(path: string, options: ActorServerRequestOptions & {
|
|
110
110
|
responseType: 'buffer';
|
|
111
|
-
}): Promise<ApifyResponse<
|
|
111
|
+
}): Promise<ApifyResponse<Uint8Array>>;
|
|
112
112
|
request(path: string, options: ActorServerRequestOptions & {
|
|
113
113
|
responseType: 'stream';
|
|
114
|
-
}): Promise<ApifyResponse<
|
|
114
|
+
}): Promise<ApifyResponse<ReadableStream<Uint8Array>>>;
|
|
115
115
|
request(path?: string, options?: ActorServerRequestOptions): Promise<ApifyResponse>;
|
|
116
116
|
}
|
|
117
117
|
/**
|
|
@@ -141,8 +141,8 @@ export interface ActorServerRequestOptions extends TimeoutOptions {
|
|
|
141
141
|
*/
|
|
142
142
|
compression?: HttpCompressionAlgorithm | HttpCompressor;
|
|
143
143
|
/**
|
|
144
|
-
* How to return the response body: `'parsed'` by its content type, `'buffer'` as raw bytes
|
|
145
|
-
*
|
|
144
|
+
* How to return the response body: `'parsed'` by its content type, `'buffer'` as raw bytes in a Uint8Array, or
|
|
145
|
+
* `'stream'` as a web ReadableStream with the body unread.
|
|
146
146
|
* @default 'parsed'
|
|
147
147
|
*/
|
|
148
148
|
responseType?: ApifyResponseType;
|
|
@@ -5,7 +5,6 @@ import { mergeHeaders } from '../http_clients/base.js';
|
|
|
5
5
|
import { compressionSchema, resolveCompressor } from '../http_compressors/resolve.js';
|
|
6
6
|
import * as schemas from '../schemas.js';
|
|
7
7
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
8
|
-
import { runtime } from '#runtime';
|
|
9
8
|
import { parseArgument, parseResponse } from '../utils.js';
|
|
10
9
|
import { BuildClient } from './build.js';
|
|
11
10
|
import { BuildCollectionClient } from './build_collection.js';
|
|
@@ -154,9 +153,6 @@ export class ActorServerClient extends ResourceClient {
|
|
|
154
153
|
async request(path = '/', options = {}) {
|
|
155
154
|
parseArgument(path, z.string());
|
|
156
155
|
const { method = 'GET', params, headers, data, parentRequestId, compression, responseType, timeoutSecs = 'long', signal, } = parseArgument(options, requestOptionsSchema, 'ActorServerRequestOptions');
|
|
157
|
-
if (responseType === 'stream' && !runtime.isNode) {
|
|
158
|
-
throw new Error("The 'stream' response type can only be used in Node.js environment.");
|
|
159
|
-
}
|
|
160
156
|
const serverUrl = await this.getUrl({ signal });
|
|
161
157
|
const serverPath = path.split('#')[0].replace(/^\/+/, '');
|
|
162
158
|
return this.httpClient.call({
|
|
@@ -46,7 +46,8 @@ export declare class ActorVersionClient extends ResourceClient {
|
|
|
46
46
|
*
|
|
47
47
|
* @param newFields - Fields to update.
|
|
48
48
|
* @param options - Request options
|
|
49
|
-
* @param options.timeoutSecs - Timeout for the API request. Default is `'
|
|
49
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
|
|
50
|
+
* its source files.
|
|
50
51
|
* @returns The updated Actor version object.
|
|
51
52
|
* @see https://docs.apify.com/api/v2/act-version-put
|
|
52
53
|
*/
|
|
@@ -55,13 +55,14 @@ export class ActorVersionClient extends ResourceClient {
|
|
|
55
55
|
*
|
|
56
56
|
* @param newFields - Fields to update.
|
|
57
57
|
* @param options - Request options
|
|
58
|
-
* @param options.timeoutSecs - Timeout for the API request. Default is `'
|
|
58
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
|
|
59
|
+
* its source files.
|
|
59
60
|
* @returns The updated Actor version object.
|
|
60
61
|
* @see https://docs.apify.com/api/v2/act-version-put
|
|
61
62
|
*/
|
|
62
63
|
async update(newFields, options = {}) {
|
|
63
64
|
parseArgument(newFields, anyObjectSchema);
|
|
64
|
-
const { timeoutSecs = '
|
|
65
|
+
const { timeoutSecs = 'long', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
|
|
65
66
|
return this.updateResource(schemas.Version(), newFields, timeoutSecs, signal);
|
|
66
67
|
}
|
|
67
68
|
/**
|
|
@@ -60,7 +60,8 @@ export declare class ActorVersionCollectionClient extends ResourceCollectionClie
|
|
|
60
60
|
*
|
|
61
61
|
* @param actorVersion - The Actor version data.
|
|
62
62
|
* @param options - Request options
|
|
63
|
-
* @param options.timeoutSecs - Timeout for the API request. Default is `'
|
|
63
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
|
|
64
|
+
* its source files.
|
|
64
65
|
* @returns The created Actor version object.
|
|
65
66
|
* @see https://docs.apify.com/api/v2/act-versions-post
|
|
66
67
|
*/
|
|
@@ -68,13 +68,14 @@ export class ActorVersionCollectionClient extends ResourceCollectionClient {
|
|
|
68
68
|
*
|
|
69
69
|
* @param actorVersion - The Actor version data.
|
|
70
70
|
* @param options - Request options
|
|
71
|
-
* @param options.timeoutSecs - Timeout for the API request. Default is `'
|
|
71
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
|
|
72
|
+
* its source files.
|
|
72
73
|
* @returns The created Actor version object.
|
|
73
74
|
* @see https://docs.apify.com/api/v2/act-versions-post
|
|
74
75
|
*/
|
|
75
76
|
async create(actorVersion, options = {}) {
|
|
76
77
|
parseArgument(actorVersion, actorVersionSchema);
|
|
77
|
-
const { timeoutSecs = '
|
|
78
|
+
const { timeoutSecs = 'long', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
|
|
78
79
|
return this.createResource(schemas.Version(), actorVersion, timeoutSecs, signal);
|
|
79
80
|
}
|
|
80
81
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Readable } from 'node:stream';
|
|
2
1
|
import type { STORAGE_GENERAL_ACCESS } from '@apify/consts';
|
|
3
2
|
import type { ApiClientSubResourceOptions } from '../base/api_client.js';
|
|
4
3
|
import { ResourceClient } from '../base/resource_client.js';
|
|
@@ -132,12 +131,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
132
131
|
*
|
|
133
132
|
* Unlike {@link listItems} which returns a {@link PaginatedList} with an array of individual
|
|
134
133
|
* dataset items, this method returns the items serialized to the provided format
|
|
135
|
-
* (JSON, CSV, Excel, etc.) as a
|
|
134
|
+
* (JSON, CSV, Excel, etc.) as a Uint8Array. Useful for exporting data for further processing.
|
|
136
135
|
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
136
|
+
* You can use the `stream` option to get a web ReadableStream, so a large export is processed in chunks without
|
|
137
|
+
* holding all of it in memory. The stream holds its connection open until you consume it to the end or cancel
|
|
138
|
+
* it. Iterating it with `for await` or piping it with `pipeTo()` does either one for you. In Node.js,
|
|
139
|
+
* `Readable.fromWeb()` turns it into a Readable.
|
|
141
140
|
*
|
|
142
141
|
* @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
|
|
143
142
|
* @param options - Download and formatting options (extends all options from {@link listItems})
|
|
@@ -149,12 +148,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
149
148
|
* @param options.xmlRow - Name of the XML element for each item. Default is `'item'`.
|
|
150
149
|
* @param options.fields - Array of field names to include in the export.
|
|
151
150
|
* @param options.omit - Array of field names to exclude from the export.
|
|
152
|
-
* @param options.stream - If `true`, the items are returned as a
|
|
151
|
+
* @param options.stream - If `true`, the items are returned as a web ReadableStream.
|
|
153
152
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`. With `stream`, it bounds the
|
|
154
|
-
* wait for the API to start responding
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
153
|
+
* wait for the API to start responding. To stop the download early or cap its total duration, cancel the stream
|
|
154
|
+
* or abort `signal`.
|
|
155
|
+
* @returns Uint8Array containing the serialized data in the specified format, or a web ReadableStream of it with
|
|
156
|
+
* `stream`
|
|
158
157
|
* @see https://docs.apify.com/api/v2/dataset-items-get
|
|
159
158
|
*
|
|
160
159
|
* @example
|
|
@@ -185,11 +184,11 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
185
184
|
*/
|
|
186
185
|
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions & {
|
|
187
186
|
stream?: false;
|
|
188
|
-
}): Promise<
|
|
187
|
+
}): Promise<Uint8Array>;
|
|
189
188
|
downloadItems(format: `${DownloadItemsFormat}`, options: DatasetClientDownloadItemsOptions & {
|
|
190
189
|
stream: true;
|
|
191
|
-
}): Promise<
|
|
192
|
-
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<
|
|
190
|
+
}): Promise<ReadableStream<Uint8Array>>;
|
|
191
|
+
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Uint8Array | ReadableStream<Uint8Array>>;
|
|
193
192
|
/**
|
|
194
193
|
* Stores one or more items into the dataset.
|
|
195
194
|
*
|
|
@@ -343,7 +342,7 @@ export interface DatasetClientDownloadItemsOptions extends Omit<DatasetClientLis
|
|
|
343
342
|
xmlRoot?: string;
|
|
344
343
|
xmlRow?: string;
|
|
345
344
|
/**
|
|
346
|
-
* If `true`, the items are returned as a
|
|
345
|
+
* If `true`, the items are returned as a web ReadableStream.
|
|
347
346
|
* @default false
|
|
348
347
|
*/
|
|
349
348
|
stream?: boolean;
|
|
@@ -3,7 +3,6 @@ import { createStorageContentSignatureAsync } from '@apify/utilities';
|
|
|
3
3
|
import { ResourceClient } from '../base/resource_client.js';
|
|
4
4
|
import * as schemas from '../schemas.js';
|
|
5
5
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
6
|
-
import { runtime } from '#runtime';
|
|
7
6
|
import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, } from '../utils.js';
|
|
8
7
|
/**
|
|
9
8
|
* Supported formats for downloading dataset items.
|
|
@@ -218,9 +217,6 @@ export class DatasetClient extends ResourceClient {
|
|
|
218
217
|
async downloadItems(format, options = {}) {
|
|
219
218
|
parseArgument(format, itemFormatSchema);
|
|
220
219
|
const { timeoutSecs = 'long', signal, stream, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
|
|
221
|
-
if (stream && !runtime.isNode) {
|
|
222
|
-
throw new Error('The stream option can only be used in Node.js environment.');
|
|
223
|
-
}
|
|
224
220
|
const { data } = await this.httpClient.call({
|
|
225
221
|
url: this.buildUrl('items'),
|
|
226
222
|
method: 'GET',
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { Readable } from 'node:stream';
|
|
2
|
-
import type { JsonValue, TypedArray } from 'type-fest';
|
|
3
2
|
import type { STORAGE_GENERAL_ACCESS } from '@apify/consts';
|
|
4
3
|
import type { ApiClientSubResourceOptions } from '../base/api_client.js';
|
|
5
4
|
import { ResourceClient } from '../base/resource_client.js';
|
|
6
5
|
import type { KeyValueStoreResource, KeyValueStoreKey, ListOfKeys } from '../models.js';
|
|
7
6
|
import type { TimeoutOptions } from '../timeouts.js';
|
|
7
|
+
import type { JsonValue, TypedArray } from '../utils.js';
|
|
8
8
|
export type { KeyValueStoreResource, KeyValueStoreKey, KeyValueStoreStats, ListOfKeys } from '../models.js';
|
|
9
9
|
/**
|
|
10
10
|
* Client for managing a specific key-value store.
|
|
@@ -178,22 +178,21 @@ export declare class KeyValueStoreClient extends ResourceClient {
|
|
|
178
178
|
recordExists(key: string, options?: TimeoutOptions): Promise<boolean>;
|
|
179
179
|
/**
|
|
180
180
|
* By default, the value is parsed by the record's content type: `application/json` is parsed into a value,
|
|
181
|
-
* `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a
|
|
182
|
-
*
|
|
181
|
+
* `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a Uint8Array.
|
|
182
|
+
* A record whose body does not parse as its content type claims, such as a non-JSON
|
|
183
183
|
* string stored under `application/json`, makes the call throw an {@link InvalidResponseBodyError}, which
|
|
184
184
|
* carries the raw body in `error.response`.
|
|
185
185
|
*
|
|
186
|
-
* You can use the `buffer` option to get the value
|
|
187
|
-
*
|
|
188
|
-
* use the `stream` option to get a Readable stream.
|
|
186
|
+
* You can use the `buffer` option to get the value as a Uint8Array, which skips the parsing. You can also
|
|
187
|
+
* use the `stream` option to get the value unread, as a web ReadableStream.
|
|
189
188
|
*
|
|
190
189
|
* When the record does not exist, the function resolves to `undefined`. It does
|
|
191
190
|
* NOT resolve to a `KeyValueStoreRecord` with an `undefined` value.
|
|
192
191
|
*
|
|
193
192
|
* @param key - The record key
|
|
194
193
|
* @param options - Retrieval options
|
|
195
|
-
* @param options.buffer - If `true`, the value is returned as a
|
|
196
|
-
* @param options.stream - If `true`, the value is returned as a
|
|
194
|
+
* @param options.buffer - If `true`, the value is returned as a Uint8Array.
|
|
195
|
+
* @param options.stream - If `true`, the value is returned as a web ReadableStream.
|
|
197
196
|
* @param options.signature - Signature of a public URL, for reading a record without a token.
|
|
198
197
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
|
|
199
198
|
* @see https://docs.apify.com/api/v2/key-value-store-record-get
|
|
@@ -210,15 +209,17 @@ export declare class KeyValueStoreClient extends ResourceClient {
|
|
|
210
209
|
* A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
|
|
211
210
|
* to be valid JSON already, or {@link getRecord} fails to parse it back.
|
|
212
211
|
*
|
|
213
|
-
* **Note about streams:** If the value is a stream
|
|
214
|
-
* the
|
|
215
|
-
* pass a `Blob` from `fs.openAsBlob()`
|
|
216
|
-
* in memory whole.
|
|
212
|
+
* **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
|
|
213
|
+
* such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
|
|
214
|
+
* on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
|
|
215
|
+
* instead: it is read again for every attempt and never held in memory whole. A browser sends a web
|
|
216
|
+
* `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
|
|
217
|
+
* where it doesn't, the call throws a `TypeError`.
|
|
217
218
|
*
|
|
218
219
|
* @param record - The record to store
|
|
219
220
|
* @param record.key - Record key (unique identifier)
|
|
220
|
-
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
221
|
-
* Readable)
|
|
221
|
+
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
|
|
222
|
+
* Readable, or web ReadableStream)
|
|
222
223
|
* @param record.contentType - Optional MIME type. Auto-detected if not provided:
|
|
223
224
|
* - Objects: `'application/json; charset=utf-8'`
|
|
224
225
|
* - Strings: `'text/plain; charset=utf-8'`
|
|
@@ -353,10 +354,10 @@ export interface KeyValueClientGetRecordOptions extends TimeoutOptions {
|
|
|
353
354
|
* A value that `setRecord` accepts.
|
|
354
355
|
*
|
|
355
356
|
* Anything JSON-serializable, or binary content the client uploads as bytes instead of JSON-encoding
|
|
356
|
-
* it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`,
|
|
357
|
-
* `Uint8Array`, so `TypedArray` covers it.
|
|
357
|
+
* it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, a Node.js `Readable`, or a web `ReadableStream`.
|
|
358
|
+
* `Buffer` is a `Uint8Array`, so `TypedArray` covers it.
|
|
358
359
|
*/
|
|
359
|
-
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable
|
|
360
|
+
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable | ReadableStream<Uint8Array>;
|
|
360
361
|
/**
|
|
361
362
|
* Represents a record (key-value pair) in a Key-Value Store.
|
|
362
363
|
*
|
|
@@ -387,8 +388,8 @@ export interface KeyValueStoreRecordOptions extends TimeoutOptions {
|
|
|
387
388
|
/**
|
|
388
389
|
* Helper type to determine the return type based on getRecord options.
|
|
389
390
|
*
|
|
390
|
-
* Returns
|
|
391
|
+
* Returns a web ReadableStream if stream option is true, Uint8Array if buffer option is true,
|
|
391
392
|
* otherwise returns JsonValue.
|
|
392
393
|
* @since Added in 2.0.6
|
|
393
394
|
*/
|
|
394
|
-
export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ?
|
|
395
|
+
export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? ReadableStream<Uint8Array> : Options['buffer'] extends true ? Uint8Array : JsonValue;
|