apify-client 3.0.0-beta.114 → 3.0.0-beta.115
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 +1 -1
- package/dist/bundle.js +8 -8
- package/dist/bundle.js.map +1 -1
- package/dist/http_clients/axios.d.ts +7 -4
- package/dist/http_clients/axios.js +29 -10
- package/dist/http_clients/base.d.ts +11 -9
- package/dist/http_clients/base.js +17 -6
- package/dist/http_clients/fetch.js +2 -2
- package/dist/resource_clients/actor_server.d.ts +6 -7
- package/dist/resource_clients/actor_server.js +0 -4
- 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 +8 -9
- package/dist/resource_clients/key_value_store.js +6 -4
- package/dist/resource_clients/log.d.ts +10 -11
- package/dist/resource_clients/log.js +4 -3
- package/dist/runtime/node.js +2 -4
- package/dist/runtime/types.d.ts +4 -4
- package/dist/runtime/web.js +2 -2
- package/dist/utils.d.ts +4 -0
- package/dist/utils.js +6 -0
- package/package.json +1 -1
|
@@ -29,7 +29,8 @@ export interface AxiosHttpClientOptions extends HttpClientOptions {
|
|
|
29
29
|
* next to the client.
|
|
30
30
|
*
|
|
31
31
|
* It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
|
|
32
|
-
* in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects
|
|
32
|
+
* in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
|
|
33
|
+
* that asks for a streamed response.
|
|
33
34
|
* Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
|
|
34
35
|
* part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
|
|
35
36
|
* in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
|
|
@@ -58,8 +59,8 @@ export declare class AxiosHttpClient extends HttpClient {
|
|
|
58
59
|
isTimeoutError(error: unknown): boolean;
|
|
59
60
|
/**
|
|
60
61
|
* A network failure is an axios error that carries the request it was sending: a connection that could not be
|
|
61
|
-
* made, dropped mid-way or timed out
|
|
62
|
-
* retried.
|
|
62
|
+
* made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
|
|
63
|
+
* Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
|
|
63
64
|
*/
|
|
64
65
|
isRetryableTransportError(error: unknown): boolean;
|
|
65
66
|
/**
|
|
@@ -71,7 +72,9 @@ export declare class AxiosHttpClient extends HttpClient {
|
|
|
71
72
|
* Sends the request through axios and hands the raw response back. A stream body is sent without following
|
|
72
73
|
* redirects, since the part of it already sent could not be replayed, and so is a request with
|
|
73
74
|
* `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
|
|
74
|
-
* redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page.
|
|
75
|
+
* redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
|
|
76
|
+
* request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
|
|
77
|
+
* timeout covers the wait for the headers only.
|
|
75
78
|
*/
|
|
76
79
|
sendRequest(request: HttpRequest): Promise<HttpResponse>;
|
|
77
80
|
}
|
|
@@ -9,7 +9,8 @@ import { HttpClient } from './base.js';
|
|
|
9
9
|
* next to the client.
|
|
10
10
|
*
|
|
11
11
|
* It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
|
|
12
|
-
* in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects
|
|
12
|
+
* in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
|
|
13
|
+
* that asks for a streamed response.
|
|
13
14
|
* Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
|
|
14
15
|
* part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
|
|
15
16
|
* in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
|
|
@@ -71,10 +72,12 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
71
72
|
}
|
|
72
73
|
/**
|
|
73
74
|
* A network failure is an axios error that carries the request it was sending: a connection that could not be
|
|
74
|
-
* made, dropped mid-way or timed out
|
|
75
|
-
* retried.
|
|
75
|
+
* made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
|
|
76
|
+
* Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
|
|
76
77
|
*/
|
|
77
78
|
isRetryableTransportError(error) {
|
|
79
|
+
if (super.isTimeoutError(error))
|
|
80
|
+
return true;
|
|
78
81
|
if (!axios.isAxiosError(error))
|
|
79
82
|
return false;
|
|
80
83
|
return typeof error.request === 'object' && error.request !== null && error.config != null;
|
|
@@ -93,27 +96,42 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
93
96
|
* Sends the request through axios and hands the raw response back. A stream body is sent without following
|
|
94
97
|
* redirects, since the part of it already sent could not be replayed, and so is a request with
|
|
95
98
|
* `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
|
|
96
|
-
* redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page.
|
|
99
|
+
* redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
|
|
100
|
+
* request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
|
|
101
|
+
* timeout covers the wait for the headers only.
|
|
97
102
|
*/
|
|
98
103
|
async sendRequest(request) {
|
|
99
104
|
await this.#ensureHttpAgents();
|
|
100
105
|
const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
|
|
101
|
-
const useFetch = !followRedirects && !runtime.isNode;
|
|
102
|
-
|
|
106
|
+
const useFetch = (!followRedirects || stream) && !runtime.isNode;
|
|
107
|
+
// The fetch adapter keeps the axios timeout running until a streamed response is read to its end.
|
|
108
|
+
const headersTimeout = useFetch && stream && timeoutMillis !== undefined ? new AbortController() : undefined;
|
|
109
|
+
const headersTimer = headersTimeout &&
|
|
110
|
+
setTimeout(() => {
|
|
111
|
+
headersTimeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError'));
|
|
112
|
+
}, timeoutMillis);
|
|
113
|
+
const signals = [signal, headersTimeout?.signal].filter((item) => item !== undefined);
|
|
114
|
+
const response = await this.axios
|
|
115
|
+
.request({
|
|
103
116
|
method,
|
|
104
117
|
url,
|
|
105
118
|
// The fetch adapter adds a `User-Agent` of its own otherwise, which a browser lists in the CORS preflight.
|
|
106
119
|
headers: useFetch ? { 'User-Agent': null, ...headers } : headers,
|
|
107
120
|
data: body,
|
|
108
121
|
// Axios reads 0 as no timeout.
|
|
109
|
-
timeout: timeoutMillis ?? 0,
|
|
110
|
-
signal,
|
|
122
|
+
timeout: headersTimeout ? 0 : (timeoutMillis ?? 0),
|
|
123
|
+
signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0],
|
|
111
124
|
responseType: stream ? 'stream' : 'arraybuffer',
|
|
112
125
|
// See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The fetch
|
|
113
126
|
// adapter turns this into `redirect: 'manual'`.
|
|
114
127
|
...(isStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
|
|
115
128
|
...(useFetch ? { adapter: 'fetch' } : {}),
|
|
116
|
-
})
|
|
129
|
+
})
|
|
130
|
+
.catch((error) => {
|
|
131
|
+
// Axios reports any abort as a cancellation.
|
|
132
|
+
throw headersTimeout?.signal.aborted ? headersTimeout.signal.reason : error;
|
|
133
|
+
})
|
|
134
|
+
.finally(() => clearTimeout(headersTimer));
|
|
117
135
|
// `redirect: 'manual'` resolves to an opaque response with status 0 instead of the redirect.
|
|
118
136
|
if (useFetch && response.status === 0) {
|
|
119
137
|
throw new ApifyClientError(`${method} ${url} responded with a redirect, which the client does not follow.`);
|
|
@@ -121,7 +139,8 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
121
139
|
return {
|
|
122
140
|
status: response.status,
|
|
123
141
|
headers: AxiosHeaders.from(response.headers).toJSON(),
|
|
124
|
-
body
|
|
142
|
+
// `fetch` has no body stream for a response without a body, such as a 204.
|
|
143
|
+
body: (response.data ?? (stream ? new Blob([]).stream() : undefined)),
|
|
125
144
|
};
|
|
126
145
|
}
|
|
127
146
|
async #ensureHttpAgents() {
|
|
@@ -32,17 +32,19 @@ export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
|
|
|
32
32
|
*/
|
|
33
33
|
export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | Blob;
|
|
34
34
|
/**
|
|
35
|
-
* A response body as the transport hands it back: the raw bytes, a `Readable` when the
|
|
36
|
-
* response, or `undefined` when the response carried no body.
|
|
35
|
+
* A response body as the transport hands it back: the raw bytes, a web `ReadableStream` or a `Readable` when the
|
|
36
|
+
* request asked for a streamed response, or `undefined` when the response carried no body. The pipeline hands the bytes
|
|
37
|
+
* on as a `Uint8Array` (a `Buffer` in Node.js) and the stream as a web `ReadableStream`, whichever of the
|
|
38
|
+
* types they arrive in.
|
|
37
39
|
*/
|
|
38
|
-
export type HttpResponseBody =
|
|
40
|
+
export type HttpResponseBody = Uint8Array | ArrayBuffer | Readable | ReadableStream<Uint8Array> | undefined;
|
|
39
41
|
/**
|
|
40
42
|
* How {@link HttpClient.call} hands back the response body.
|
|
41
43
|
*
|
|
42
44
|
* - `parsed` (the default) decodes it by content type: JSON becomes an object, text and XML become a string, anything
|
|
43
|
-
* else stays a `
|
|
44
|
-
* - `buffer` skips the decoding and hands back the raw bytes
|
|
45
|
-
* - `stream` hands back a `
|
|
45
|
+
* else stays a `Uint8Array`.
|
|
46
|
+
* - `buffer` skips the decoding and hands back the raw bytes as a `Uint8Array`.
|
|
47
|
+
* - `stream` hands back the body unread, as a web `ReadableStream` of `Uint8Array` chunks.
|
|
46
48
|
*/
|
|
47
49
|
export type ApifyResponseType = 'parsed' | 'buffer' | 'stream';
|
|
48
50
|
/**
|
|
@@ -157,7 +159,7 @@ export interface HttpRequest {
|
|
|
157
159
|
* `timeoutSecs: 'noTimeout'` asks for.
|
|
158
160
|
*/
|
|
159
161
|
timeoutMillis?: number;
|
|
160
|
-
/** Whether to hand the body back unread as a
|
|
162
|
+
/** Whether to hand the body back unread as a stream. The caller always gets a web `ReadableStream`. */
|
|
161
163
|
stream: boolean;
|
|
162
164
|
/**
|
|
163
165
|
* Whether to follow redirects. With `false`, return a redirect response as it is: the request carries a token
|
|
@@ -178,7 +180,7 @@ export interface HttpResponse {
|
|
|
178
180
|
status: number;
|
|
179
181
|
/** Response headers keyed by lowercase header name. */
|
|
180
182
|
headers: HttpResponseHeaders;
|
|
181
|
-
/** The body as raw bytes, or unread as a `Readable`
|
|
183
|
+
/** The body as raw bytes, or unread as a stream: a web `ReadableStream`, or a `Readable` the pipeline converts. */
|
|
182
184
|
body: HttpResponseBody;
|
|
183
185
|
}
|
|
184
186
|
/**
|
|
@@ -257,7 +259,7 @@ export interface HttpClientOptions {
|
|
|
257
259
|
* return {
|
|
258
260
|
* status: response.status,
|
|
259
261
|
* headers: Object.fromEntries(response.headers),
|
|
260
|
-
* body:
|
|
262
|
+
* body: await response.arrayBuffer(),
|
|
261
263
|
* };
|
|
262
264
|
* }
|
|
263
265
|
*
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { APIFY_ENV_VARS } from '@apify/consts';
|
|
3
3
|
import log from '@apify/log';
|
|
4
|
-
import { concatStreamToBuffer } from '@apify/utilities';
|
|
5
4
|
import { ApifyApiError } from '../apify_api_error.js';
|
|
6
5
|
import { maybeParseBody } from '../body_parser.js';
|
|
7
6
|
import { resolveCompressor } from '../http_compressors/resolve.js';
|
|
@@ -9,7 +8,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
|
|
|
9
8
|
import { Statistics } from '../statistics.js';
|
|
10
9
|
import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
|
|
11
10
|
import { runtime } from '#runtime';
|
|
12
|
-
import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
|
|
11
|
+
import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, isWebStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
|
|
13
12
|
export const DEFAULT_MAX_RETRIES = 8;
|
|
14
13
|
export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
|
|
15
14
|
const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
|
|
@@ -68,7 +67,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
|
|
|
68
67
|
* return {
|
|
69
68
|
* status: response.status,
|
|
70
69
|
* headers: Object.fromEntries(response.headers),
|
|
71
|
-
* body:
|
|
70
|
+
* body: await response.arrayBuffer(),
|
|
72
71
|
* };
|
|
73
72
|
* }
|
|
74
73
|
*
|
|
@@ -371,12 +370,17 @@ export class HttpClient {
|
|
|
371
370
|
const shouldReturnError = isError &&
|
|
372
371
|
config.throwOnErrorStatus === false &&
|
|
373
372
|
(!isRetryable || requestIsStream || attempt > this.maxRetries);
|
|
373
|
+
// Transports return whichever stream and binary type their HTTP library has, and callers get the web ones.
|
|
374
|
+
if (isStream(response.body))
|
|
375
|
+
response.body = runtime.streamToWeb(response.body);
|
|
374
376
|
// A failed streaming request carries the API error body in the stream, so read it and let
|
|
375
377
|
// `ApifyApiError` parse it like any other error body. A body that cannot be read leaves the error
|
|
376
378
|
// without a message, which beats losing the status code to a stream error.
|
|
377
|
-
if (isError && !shouldReturnError &&
|
|
378
|
-
response.body = await
|
|
379
|
+
if (isError && !shouldReturnError && isWebStream(response.body)) {
|
|
380
|
+
response.body = await new Response(response.body).arrayBuffer().catch(() => undefined);
|
|
379
381
|
}
|
|
382
|
+
if (isBuffer(response.body))
|
|
383
|
+
response.body = toResponseBytes(response.body);
|
|
380
384
|
let data;
|
|
381
385
|
try {
|
|
382
386
|
data = this.#parseResponseBody(response, config);
|
|
@@ -425,7 +429,7 @@ export class HttpClient {
|
|
|
425
429
|
const { body } = response;
|
|
426
430
|
if (config.responseType === 'stream' || config.responseType === 'buffer')
|
|
427
431
|
return body;
|
|
428
|
-
if (body === undefined ||
|
|
432
|
+
if (body === undefined || !isBuffer(body))
|
|
429
433
|
return body;
|
|
430
434
|
if (body.byteLength === 0)
|
|
431
435
|
return undefined;
|
|
@@ -554,6 +558,13 @@ function withCause(error, cause) {
|
|
|
554
558
|
error.cause = cause;
|
|
555
559
|
return error;
|
|
556
560
|
}
|
|
561
|
+
/** Views response bytes as a `Uint8Array` without copying them: a `Buffer` in Node.js, which v2 callers rely on. */
|
|
562
|
+
function toResponseBytes(body) {
|
|
563
|
+
if (runtime.isNode && Buffer.isBuffer(body))
|
|
564
|
+
return body;
|
|
565
|
+
const bytes = toBytes(body);
|
|
566
|
+
return runtime.isNode ? Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) : bytes;
|
|
567
|
+
}
|
|
557
568
|
function headerValue(value) {
|
|
558
569
|
return Array.isArray(value) ? value[0] : value;
|
|
559
570
|
}
|
|
@@ -105,7 +105,7 @@ export class FetchHttpClient extends HttpClient {
|
|
|
105
105
|
status: response.status,
|
|
106
106
|
headers: toResponseHeaders(response.headers),
|
|
107
107
|
// The timeout covers a streamed response only until its headers, and the caller's signal throughout.
|
|
108
|
-
body: stream ?
|
|
108
|
+
body: stream ? (response.body ?? new Blob([]).stream()) : await readBody(response, restartTimeout),
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
111
|
catch (error) {
|
|
@@ -163,7 +163,7 @@ async function readBody(response, onChunk) {
|
|
|
163
163
|
bytes.set(chunk, offset);
|
|
164
164
|
offset += chunk.byteLength;
|
|
165
165
|
}
|
|
166
|
-
return
|
|
166
|
+
return bytes;
|
|
167
167
|
}
|
|
168
168
|
function toResponseHeaders(headers) {
|
|
169
169
|
const result = Object.fromEntries(headers);
|
|
@@ -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';
|
|
@@ -92,8 +91,8 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
92
91
|
* The body is compressed under the same conditions as for API calls. Set it only if the Actor's server decodes
|
|
93
92
|
* the resulting `Content-Encoding`.
|
|
94
93
|
* @param options.responseType - How to return the response body: `'parsed'` by its content type, `'buffer'` as
|
|
95
|
-
* raw bytes, or `'stream'` as a
|
|
96
|
-
* 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'`.
|
|
97
96
|
* @param options.timeoutSecs - Timeout for the HTTP request. Default is `'long'`. With `'stream'`, it bounds the
|
|
98
97
|
* wait for the server to start responding.
|
|
99
98
|
* @returns The response of the Actor's server, with the body in the form `responseType` asks for. An error
|
|
@@ -109,10 +108,10 @@ export declare class ActorServerClient extends ResourceClient {
|
|
|
109
108
|
}): Promise<ApifyResponse<T>>;
|
|
110
109
|
request(path: string, options: ActorServerRequestOptions & {
|
|
111
110
|
responseType: 'buffer';
|
|
112
|
-
}): Promise<ApifyResponse<
|
|
111
|
+
}): Promise<ApifyResponse<Uint8Array>>;
|
|
113
112
|
request(path: string, options: ActorServerRequestOptions & {
|
|
114
113
|
responseType: 'stream';
|
|
115
|
-
}): Promise<ApifyResponse<
|
|
114
|
+
}): Promise<ApifyResponse<ReadableStream<Uint8Array>>>;
|
|
116
115
|
request(path?: string, options?: ActorServerRequestOptions): Promise<ApifyResponse>;
|
|
117
116
|
}
|
|
118
117
|
/**
|
|
@@ -142,8 +141,8 @@ export interface ActorServerRequestOptions extends TimeoutOptions {
|
|
|
142
141
|
*/
|
|
143
142
|
compression?: HttpCompressionAlgorithm | HttpCompressor;
|
|
144
143
|
/**
|
|
145
|
-
* How to return the response body: `'parsed'` by its content type, `'buffer'` as raw bytes
|
|
146
|
-
*
|
|
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.
|
|
147
146
|
* @default 'parsed'
|
|
148
147
|
*/
|
|
149
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({
|
|
@@ -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',
|
|
@@ -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
|
|
@@ -387,8 +386,8 @@ export interface KeyValueStoreRecordOptions extends TimeoutOptions {
|
|
|
387
386
|
/**
|
|
388
387
|
* Helper type to determine the return type based on getRecord options.
|
|
389
388
|
*
|
|
390
|
-
* Returns
|
|
389
|
+
* Returns a web ReadableStream if stream option is true, Uint8Array if buffer option is true,
|
|
391
390
|
* otherwise returns JsonValue.
|
|
392
391
|
* @since Added in 2.0.6
|
|
393
392
|
*/
|
|
394
|
-
export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ?
|
|
393
|
+
export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? ReadableStream<Uint8Array> : Options['buffer'] extends true ? Uint8Array : JsonValue;
|
|
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
|
|
|
5
5
|
import * as schemas from '../schemas.js';
|
|
6
6
|
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
7
7
|
import { runtime } from '#runtime';
|
|
8
|
-
import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBlob, isBuffer, isStream, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
|
|
8
|
+
import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBlob, isBuffer, isStream, isWebStream, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
|
|
9
9
|
const listKeysOptionsSchema = z.strictObject({
|
|
10
10
|
limit: z.number().min(0).optional(),
|
|
11
11
|
chunkSize: z.number().positive().optional(),
|
|
@@ -320,9 +320,6 @@ export class KeyValueStoreClient extends ResourceClient {
|
|
|
320
320
|
async getRecord(key, options = {}) {
|
|
321
321
|
parseArgument(key, keySchema);
|
|
322
322
|
const parsed = parseArgument(options, getRecordOptionsSchema, 'KeyValueClientGetRecordOptions');
|
|
323
|
-
if (parsed.stream && !runtime.isNode) {
|
|
324
|
-
throw new Error('The stream option can only be used in Node.js environment.');
|
|
325
|
-
}
|
|
326
323
|
if ('disableRedirect' in parsed) {
|
|
327
324
|
log.deprecated('The disableRedirect option for getRecord() is deprecated. ' +
|
|
328
325
|
'It has no effect and will be removed in the following major release.');
|
|
@@ -439,6 +436,11 @@ export class KeyValueStoreClient extends ResourceClient {
|
|
|
439
436
|
if (contentEncoding !== undefined && !runtime.isNode) {
|
|
440
437
|
throw new Error('The contentEncoding option can only be used in Node.js environment.');
|
|
441
438
|
}
|
|
439
|
+
// A web stream is no request body the transports take, and it would serialize to JSON as `{}`.
|
|
440
|
+
if (isWebStream(value)) {
|
|
441
|
+
throw new TypeError('A web ReadableStream cannot be stored as a record value. ' +
|
|
442
|
+
'Convert it with Readable.fromWeb() in Node.js, or read it into bytes first.');
|
|
443
|
+
}
|
|
442
444
|
const isBinaryValue = isStream(value) || isBuffer(value) || isBlob(value);
|
|
443
445
|
// The client forwards the header without inspecting the body, so a string or a value serialized to JSON, which
|
|
444
446
|
// cannot hold compressed bytes, would be stored under an encoding that misdescribes it.
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { Readable } from 'node:stream';
|
|
2
1
|
import type { Log } from '@apify/log';
|
|
3
2
|
import { Logger, LogLevel } from '@apify/log';
|
|
4
3
|
import type { ApiClientSubResourceOptions } from '../base/api_client.js';
|
|
@@ -37,13 +36,13 @@ export declare class LogClient extends ResourceClient {
|
|
|
37
36
|
/**
|
|
38
37
|
* Retrieves the log as a string.
|
|
39
38
|
*
|
|
40
|
-
* The `buffer` option only selects the return type: the bytes come back as a
|
|
41
|
-
*
|
|
42
|
-
*
|
|
39
|
+
* The `buffer` option only selects the return type: the bytes come back as a Uint8Array, not decoded to a
|
|
40
|
+
* string. Either way the whole log is downloaded in one response; to read it incrementally, use
|
|
41
|
+
* {@link LogClient.stream}.
|
|
43
42
|
*
|
|
44
43
|
* @param options - Log retrieval options.
|
|
45
44
|
* @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
|
|
46
|
-
* @param options.buffer - If `true`, the log is returned as a
|
|
45
|
+
* @param options.buffer - If `true`, the log is returned as a Uint8Array instead of a
|
|
47
46
|
* string. It does not change how the log is fetched.
|
|
48
47
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
|
|
49
48
|
* @returns The log content, or `undefined` if it does not exist. A chained client such as `run.log()` throws an
|
|
@@ -55,19 +54,19 @@ export declare class LogClient extends ResourceClient {
|
|
|
55
54
|
}): Promise<string | undefined>;
|
|
56
55
|
get(options: LogGetOptions & {
|
|
57
56
|
buffer: true;
|
|
58
|
-
}): Promise<
|
|
59
|
-
get(options?: LogGetOptions): Promise<string |
|
|
57
|
+
}): Promise<Uint8Array | undefined>;
|
|
58
|
+
get(options?: LogGetOptions): Promise<string | Uint8Array | undefined>;
|
|
60
59
|
/**
|
|
61
|
-
* Retrieves the log as a
|
|
60
|
+
* Retrieves the log as a web ReadableStream of Uint8Array chunks.
|
|
62
61
|
*
|
|
63
62
|
* @param options - Log retrieval options.
|
|
64
63
|
* @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
|
|
65
64
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
|
|
66
|
-
* @returns The log content as a
|
|
65
|
+
* @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
|
|
67
66
|
* `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
|
|
68
67
|
* @see https://docs.apify.com/api/v2/log-get
|
|
69
68
|
*/
|
|
70
|
-
stream(options?: LogOptions): Promise<
|
|
69
|
+
stream(options?: LogOptions): Promise<ReadableStream<Uint8Array> | undefined>;
|
|
71
70
|
}
|
|
72
71
|
/**
|
|
73
72
|
* @since Added in 2.20.0
|
|
@@ -81,7 +80,7 @@ export interface LogOptions extends TimeoutOptions {
|
|
|
81
80
|
*/
|
|
82
81
|
export interface LogGetOptions extends LogOptions {
|
|
83
82
|
/**
|
|
84
|
-
* If `true`, the log is returned as a
|
|
83
|
+
* If `true`, the log is returned as a Uint8Array instead of a string. It only selects
|
|
85
84
|
* the return type; to read the log incrementally, use {@link LogClient.stream}.
|
|
86
85
|
* @default false
|
|
87
86
|
*/
|
|
@@ -72,12 +72,12 @@ export class LogClient extends ResourceClient {
|
|
|
72
72
|
return undefined;
|
|
73
73
|
}
|
|
74
74
|
/**
|
|
75
|
-
* Retrieves the log as a
|
|
75
|
+
* Retrieves the log as a web ReadableStream of Uint8Array chunks.
|
|
76
76
|
*
|
|
77
77
|
* @param options - Log retrieval options.
|
|
78
78
|
* @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
|
|
79
79
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
|
|
80
|
-
* @returns The log content as a
|
|
80
|
+
* @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
|
|
81
81
|
* `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
|
|
82
82
|
* @see https://docs.apify.com/api/v2/log-get
|
|
83
83
|
*/
|
|
@@ -227,7 +227,8 @@ export class StreamedLog {
|
|
|
227
227
|
}
|
|
228
228
|
// A stream opened during stop() would be cut after its first chunk, so read the log in one request.
|
|
229
229
|
if (this.#stopLogging) {
|
|
230
|
-
|
|
230
|
+
// Cancelling a stream that has already failed rejects with its error.
|
|
231
|
+
await logStream.cancel().catch(() => { });
|
|
231
232
|
continue;
|
|
232
233
|
}
|
|
233
234
|
lastChunkRemainder = await this.#logStreamChunks(logStream, signal);
|
package/dist/runtime/node.js
CHANGED
|
@@ -50,10 +50,8 @@ export const runtime = {
|
|
|
50
50
|
};
|
|
51
51
|
return { httpAgent: new http.Agent(agentOptions), httpsAgent: new https.Agent(agentOptions) };
|
|
52
52
|
},
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
return Readable.from([]);
|
|
56
|
-
return Readable.fromWeb(body);
|
|
53
|
+
streamToWeb(stream) {
|
|
54
|
+
return Readable.toWeb(stream);
|
|
57
55
|
},
|
|
58
56
|
unusedProxyHint() {
|
|
59
57
|
const names = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'].filter((name) => process.env[name]);
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -29,7 +29,7 @@ export interface Runtime {
|
|
|
29
29
|
/**
|
|
30
30
|
* Whether the Node.js implementation was selected, which the `node` condition settles when `#runtime` is
|
|
31
31
|
* resolved - so a Node.js application bundled for a browser or a neutral target reports `false`. Log
|
|
32
|
-
*
|
|
32
|
+
* redirection and request body compression are gated on it.
|
|
33
33
|
*/
|
|
34
34
|
isNode: boolean;
|
|
35
35
|
/**
|
|
@@ -56,10 +56,10 @@ export interface Runtime {
|
|
|
56
56
|
timeoutMillis: number;
|
|
57
57
|
}): Promise<HttpAgents | undefined>;
|
|
58
58
|
/**
|
|
59
|
-
*
|
|
60
|
-
* where the runtime has no `Readable`, since
|
|
59
|
+
* Turns the `Readable` a transport returned for a streamed response into the web stream the callers get.
|
|
60
|
+
* Throws where the runtime has no `Readable`, since no transport can return one there.
|
|
61
61
|
*/
|
|
62
|
-
|
|
62
|
+
streamToWeb(stream: Readable): ReadableStream<Uint8Array>;
|
|
63
63
|
/**
|
|
64
64
|
* Explains how to make `fetch` use the proxy named in the environment variables, or returns `undefined` when
|
|
65
65
|
* none is set, the runtime already honors them, or it has no environment to read.
|
package/dist/runtime/web.js
CHANGED
|
@@ -16,8 +16,8 @@ export const runtime = {
|
|
|
16
16
|
async createHttpAgents() {
|
|
17
17
|
return undefined;
|
|
18
18
|
},
|
|
19
|
-
|
|
20
|
-
throw new Error('
|
|
19
|
+
streamToWeb() {
|
|
20
|
+
throw new Error('A Readable stream is only available in Node.js.');
|
|
21
21
|
},
|
|
22
22
|
// A browser applies the proxy settings of the system on its own.
|
|
23
23
|
unusedProxyHint() {
|
package/dist/utils.d.ts
CHANGED
|
@@ -105,6 +105,10 @@ export declare function isBuffer(value: unknown): value is Buffer | ArrayBuffer
|
|
|
105
105
|
* request, so a request with a blob body can be retried.
|
|
106
106
|
*/
|
|
107
107
|
export declare function isBlob(value: unknown): value is Blob;
|
|
108
|
+
/**
|
|
109
|
+
* Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response.
|
|
110
|
+
*/
|
|
111
|
+
export declare function isWebStream(value: unknown): value is ReadableStream<Uint8Array>;
|
|
108
112
|
export declare function isStream(value: unknown): value is Readable;
|
|
109
113
|
/**
|
|
110
114
|
* Helper class to create async iterators from paginated list endpoints.
|