apify-client 3.0.0-beta.16 → 3.0.0-beta.17

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.
@@ -6,6 +6,7 @@ import type { RequestInterceptorFunction } from './interceptors.js';
6
6
  import type { Statistics } from './statistics.js';
7
7
  import type { Timeout, TimeoutTier } from './timeouts.js';
8
8
  export declare class HttpClient {
9
+ #private;
9
10
  stats: Statistics;
10
11
  maxRetries: number;
11
12
  minDelayBetweenRetriesMillis: number;
@@ -19,63 +20,8 @@ export declare class HttpClient {
19
20
  httpsAgent?: https.Agent;
20
21
  axios: AxiosInstance;
21
22
  workflowKey?: string;
22
- private nodeInitPromise?;
23
- private userAgentSuffix?;
24
23
  constructor(options: HttpClientOptions);
25
- private ensureNodeInit;
26
- private initNode;
27
24
  call<T = any>(config: ApifyRequestConfig): Promise<ApifyResponse<T>>;
28
- private informAboutStreamNoRetry;
29
- /**
30
- * Successful responses are returned, errors and unsuccessful
31
- * status codes are retried. See the following functions for the
32
- * retrying logic.
33
- */
34
- private createRequestHandler;
35
- private isStatusOk;
36
- /**
37
- * Resolves `timeoutSecs` to the number of milliseconds the given attempt gets. A tier name resolves to
38
- * its configured duration, a number is taken as seconds, and `'noTimeout'` becomes `0`, which axios reads
39
- * as no timeout. The result doubles with each attempt and is capped at `timeoutMaxMillis`. A requested
40
- * value above the cap is capped too, which warns once, since it does not take effect in full.
41
- */
42
- private computeTimeoutMillis;
43
- /**
44
- * Handles all unexpected errors that can happen, but are not
45
- * Apify API typed errors. E.g. network errors, timeouts and so on.
46
- */
47
- private handleRequestError;
48
- /**
49
- * Axios calls req.abort() on timeouts so timeout errors will
50
- * have a code ECONNABORTED.
51
- */
52
- private isTimeoutError;
53
- /**
54
- * We don't want to retry every exception thrown from Axios.
55
- * The common denominator for retryable errors are network issues.
56
- * @param {Error} err
57
- * @private
58
- */
59
- private isRetryableError;
60
- /**
61
- * When a network connection to our API is interrupted in the middle of streaming
62
- * a response, the request often does not fail, but simply contains
63
- * an incomplete response. This can often be fixed by retrying.
64
- */
65
- private isResponseBodyInvalid;
66
- /**
67
- * When a network request is attempted by axios and fails,
68
- * it throws an AxiosError, which will have the request
69
- * and config (and other) properties.
70
- */
71
- private isNetworkError;
72
- /**
73
- * We retry 429 (rate limit) and 500+.
74
- * For status codes 300-499 (except 429) we do not retry the request,
75
- * because it's probably caused by invalid url (redirect 3xx) or invalid user input (4xx).
76
- */
77
- private isStatusCodeRetryable;
78
- private onRequestRetry;
79
25
  }
80
26
  export interface ApifyRequestConfig extends Omit<AxiosRequestConfig, 'timeout'> {
81
27
  stringifyFunctions?: boolean;
@@ -20,8 +20,8 @@ export class HttpClient {
20
20
  httpsAgent;
21
21
  axios;
22
22
  workflowKey;
23
- nodeInitPromise;
24
- userAgentSuffix;
23
+ #nodeInitPromise;
24
+ #userAgentSuffix;
25
25
  constructor(options) {
26
26
  const { token } = options;
27
27
  this.stats = options.apifyClientStats;
@@ -36,8 +36,7 @@ export class HttpClient {
36
36
  this.timeoutMaxMillis = options.timeoutMaxSecs * 1000;
37
37
  this.logger = options.logger;
38
38
  this.workflowKey = options.workflowKey || process.env[APIFY_ENV_VARS.WORKFLOW_KEY];
39
- this.userAgentSuffix = options.userAgentSuffix;
40
- this.onRequestRetry = this.onRequestRetry.bind(this);
39
+ this.#userAgentSuffix = options.userAgentSuffix;
41
40
  this.axios = axios.create({
42
41
  // Disable axios's built-in proxy handling since we're using custom agents
43
42
  proxy: false,
@@ -82,13 +81,13 @@ export class HttpClient {
82
81
  this.userProvidedRequestInterceptors.forEach((i) => this.axios.interceptors.request.use(i));
83
82
  responseInterceptors.forEach((i) => this.axios.interceptors.response.use(i));
84
83
  }
85
- async ensureNodeInit() {
84
+ async #ensureNodeInit() {
86
85
  if (!isNode())
87
86
  return;
88
- this.nodeInitPromise ??= this.initNode();
89
- return this.nodeInitPromise;
87
+ this.#nodeInitPromise ??= this.#initNode();
88
+ return this.#nodeInitPromise;
90
89
  }
91
- async initNode() {
90
+ async #initNode() {
92
91
  if (!isNode())
93
92
  return;
94
93
  const [{ ProxyAgent }, os] = await Promise.all([import('proxy-agent'), import('node:os')]);
@@ -129,22 +128,22 @@ export class HttpClient {
129
128
  // Works only in Node. Cannot be set in browser
130
129
  const isAtHome = !!process.env[APIFY_ENV_VARS.IS_AT_HOME];
131
130
  let userAgent = `ApifyClient/${version} (${os.platform()}; Node/${process.version}); isAtHome/${isAtHome}`;
132
- if (this.userAgentSuffix) {
133
- userAgent += `; ${asArray(this.userAgentSuffix).join('; ')}`;
131
+ if (this.#userAgentSuffix) {
132
+ userAgent += `; ${asArray(this.#userAgentSuffix).join('; ')}`;
134
133
  }
135
134
  this.axios.defaults.headers['User-Agent'] = userAgent;
136
135
  }
137
136
  async call(config) {
138
- await this.ensureNodeInit();
137
+ await this.#ensureNodeInit();
139
138
  this.stats.calls++;
140
- const makeRequest = this.createRequestHandler(config);
139
+ const makeRequest = this.#createRequestHandler(config);
141
140
  return retry(makeRequest, {
142
141
  retries: this.maxRetries,
143
142
  minTimeout: this.minDelayBetweenRetriesMillis,
144
- onRetry: this.onRequestRetry,
143
+ onRetry: (error, attempt) => this.#onRequestRetry(error, attempt),
145
144
  });
146
145
  }
147
- informAboutStreamNoRetry() {
146
+ #informAboutStreamNoRetry() {
148
147
  this.logger.warningOnce('Request body was a stream - retrying will not work, as part of it was already consumed.');
149
148
  this.logger.warningOnce('If you want Apify client to handle retries for you, collect the stream into a buffer before sending it.');
150
149
  }
@@ -153,7 +152,7 @@ export class HttpClient {
153
152
  * status codes are retried. See the following functions for the
154
153
  * retrying logic.
155
154
  */
156
- createRequestHandler(config) {
155
+ #createRequestHandler(config) {
157
156
  const { timeoutSecs = 'medium', ...axiosConfig } = config;
158
157
  const makeRequest = async (stopTrying, attempt) => {
159
158
  this.stats.requests++;
@@ -168,21 +167,21 @@ export class HttpClient {
168
167
  }
169
168
  response = await this.axios.request({
170
169
  ...axiosConfig,
171
- timeout: this.computeTimeoutMillis(timeoutSecs, attempt),
170
+ timeout: this.#computeTimeoutMillis(timeoutSecs, attempt),
172
171
  });
173
- if (this.isStatusOk(response.status))
172
+ if (this.#isStatusOk(response.status))
174
173
  return response;
175
174
  }
176
175
  catch (err) {
177
- return cast(this.handleRequestError(err, config, stopTrying));
176
+ return cast(this.#handleRequestError(err, config, stopTrying));
178
177
  }
179
178
  if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE) {
180
179
  this.stats.addRateLimitError(attempt);
181
180
  }
182
181
  const apiError = ApifyApiError.fromResponse(response, attempt);
183
- if (this.isStatusCodeRetryable(response.status)) {
182
+ if (this.#isStatusCodeRetryable(response.status)) {
184
183
  if (requestIsStream) {
185
- this.informAboutStreamNoRetry();
184
+ this.#informAboutStreamNoRetry();
186
185
  }
187
186
  else {
188
187
  // allow a retry
@@ -194,7 +193,7 @@ export class HttpClient {
194
193
  };
195
194
  return makeRequest;
196
195
  }
197
- isStatusOk(statusCode) {
196
+ #isStatusOk(statusCode) {
198
197
  return statusCode < 300;
199
198
  }
200
199
  /**
@@ -203,7 +202,7 @@ export class HttpClient {
203
202
  * as no timeout. The result doubles with each attempt and is capped at `timeoutMaxMillis`. A requested
204
203
  * value above the cap is capped too, which warns once, since it does not take effect in full.
205
204
  */
206
- computeTimeoutMillis(timeoutSecs, attempt) {
205
+ #computeTimeoutMillis(timeoutSecs, attempt) {
207
206
  if (timeoutSecs === 'noTimeout')
208
207
  return 0;
209
208
  const requestedMillis = typeof timeoutSecs === 'number' ? timeoutSecs * 1000 : this.timeoutMillis[timeoutSecs];
@@ -219,13 +218,13 @@ export class HttpClient {
219
218
  * Handles all unexpected errors that can happen, but are not
220
219
  * Apify API typed errors. E.g. network errors, timeouts and so on.
221
220
  */
222
- handleRequestError(err, config, stopTrying) {
223
- if (this.isTimeoutError(err) && config.doNotRetryTimeouts) {
221
+ #handleRequestError(err, config, stopTrying) {
222
+ if (this.#isTimeoutError(err) && config.doNotRetryTimeouts) {
224
223
  return stopTrying(err);
225
224
  }
226
- if (this.isRetryableError(err)) {
225
+ if (this.#isRetryableError(err)) {
227
226
  if (isStream(config.data)) {
228
- this.informAboutStreamNoRetry();
227
+ this.#informAboutStreamNoRetry();
229
228
  }
230
229
  else {
231
230
  throw err;
@@ -237,7 +236,7 @@ export class HttpClient {
237
236
  * Axios calls req.abort() on timeouts so timeout errors will
238
237
  * have a code ECONNABORTED.
239
238
  */
240
- isTimeoutError(err) {
239
+ #isTimeoutError(err) {
241
240
  return err.code === 'ECONNABORTED';
242
241
  }
243
242
  /**
@@ -246,15 +245,15 @@ export class HttpClient {
246
245
  * @param {Error} err
247
246
  * @private
248
247
  */
249
- isRetryableError(err) {
250
- return this.isNetworkError(err) || this.isResponseBodyInvalid(err);
248
+ #isRetryableError(err) {
249
+ return this.#isNetworkError(err) || this.#isResponseBodyInvalid(err);
251
250
  }
252
251
  /**
253
252
  * When a network connection to our API is interrupted in the middle of streaming
254
253
  * a response, the request often does not fail, but simply contains
255
254
  * an incomplete response. This can often be fixed by retrying.
256
255
  */
257
- isResponseBodyInvalid(err) {
256
+ #isResponseBodyInvalid(err) {
258
257
  return err instanceof InvalidResponseBodyError;
259
258
  }
260
259
  /**
@@ -262,7 +261,7 @@ export class HttpClient {
262
261
  * it throws an AxiosError, which will have the request
263
262
  * and config (and other) properties.
264
263
  */
265
- isNetworkError(err) {
264
+ #isNetworkError(err) {
266
265
  const hasRequest = err.request && typeof err.request === 'object';
267
266
  const hasConfig = err.config && typeof err.config === 'object';
268
267
  return hasRequest && hasConfig;
@@ -272,12 +271,12 @@ export class HttpClient {
272
271
  * For status codes 300-499 (except 429) we do not retry the request,
273
272
  * because it's probably caused by invalid url (redirect 3xx) or invalid user input (4xx).
274
273
  */
275
- isStatusCodeRetryable(statusCode) {
274
+ #isStatusCodeRetryable(statusCode) {
276
275
  const isRateLimitError = statusCode === RATE_LIMIT_EXCEEDED_STATUS_CODE;
277
276
  const isInternalError = statusCode >= 500;
278
277
  return isRateLimitError || isInternalError;
279
278
  }
280
- onRequestRetry(error, attempt) {
279
+ #onRequestRetry(error, attempt) {
281
280
  if (attempt === Math.round(this.maxRetries / 2)) {
282
281
  this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${error.stack}`);
283
282
  }
@@ -35,6 +35,7 @@ export type { Dataset, DatasetStatistics, DatasetStats, FieldStatistics } from '
35
35
  * @see https://docs.apify.com/platform/storage/dataset
36
36
  */
37
37
  export declare class DatasetClient<Data extends Record<string | number, any> = Record<string | number, unknown>> extends ResourceClient {
38
+ #private;
38
39
  /**
39
40
  * @hidden
40
41
  */
@@ -236,7 +237,6 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
236
237
  * @since Added in 2.13.0
237
238
  */
238
239
  createItemsPublicUrl(options?: DatasetClientCreateItemsUrlOptions): Promise<string>;
239
- private createPaginationList;
240
240
  }
241
241
  /**
242
242
  * Options for updating a dataset.
@@ -192,7 +192,7 @@ export class DatasetClient extends ResourceClient {
192
192
  params: this.buildParams(datasetListOptions),
193
193
  timeoutSecs,
194
194
  });
195
- return this.createPaginationList(response, datasetListOptions.desc ?? false);
195
+ return this.#createPaginationList(response, datasetListOptions.desc ?? false);
196
196
  };
197
197
  return this.listPaginatedFromCallback(fetchItems, listOptions);
198
198
  }
@@ -371,7 +371,7 @@ export class DatasetClient extends ResourceClient {
371
371
  createdItemsPublicUrl = applyQueryParamsToUrl(createdItemsPublicUrl, queryOptions);
372
372
  return createdItemsPublicUrl.toString();
373
373
  }
374
- createPaginationList(response, userProvidedDesc) {
374
+ #createPaginationList(response, userProvidedDesc) {
375
375
  const page = {
376
376
  items: response.data,
377
377
  total: Number(response.headers['x-apify-pagination-total']),
@@ -74,13 +74,7 @@ export declare class LoggerActorRedirect extends Logger {
74
74
  * @since Added in 2.20.0
75
75
  */
76
76
  export declare class StreamedLog {
77
- private destinationLog;
78
- private streamBuffer;
79
- private splitMarker;
80
- private relevancyTimeLimit;
81
- private logClient;
82
- private streamingTask;
83
- private stopLogging;
77
+ #private;
84
78
  constructor(options: StreamedLogOptions);
85
79
  /**
86
80
  * Start log redirection.
@@ -90,15 +84,6 @@ export declare class StreamedLog {
90
84
  * Stop log redirection.
91
85
  */
92
86
  stop(): Promise<void>;
93
- /**
94
- * Get log stream from response and redirect it to another log.
95
- */
96
- private streamLog;
97
- private logStreamChunks;
98
- /**
99
- * Parse the buffer and log complete messages.
100
- */
101
- private logBufferContent;
102
87
  }
103
88
  /**
104
89
  * @since Added in 2.20.0
@@ -130,39 +130,39 @@ export class LoggerActorRedirect extends Logger {
130
130
  * @since Added in 2.20.0
131
131
  */
132
132
  export class StreamedLog {
133
- destinationLog;
134
- streamBuffer = [];
135
- splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
136
- relevancyTimeLimit;
137
- logClient;
138
- streamingTask = null;
139
- stopLogging = false;
133
+ #destinationLog;
134
+ #streamBuffer = [];
135
+ #splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
136
+ #relevancyTimeLimit;
137
+ #logClient;
138
+ #streamingTask = null;
139
+ #stopLogging = false;
140
140
  constructor(options) {
141
141
  const { toLog, logClient, fromStart = true } = options;
142
- this.destinationLog = toLog;
143
- this.logClient = logClient;
144
- this.relevancyTimeLimit = fromStart ? null : new Date();
142
+ this.#destinationLog = toLog;
143
+ this.#logClient = logClient;
144
+ this.#relevancyTimeLimit = fromStart ? null : new Date();
145
145
  }
146
146
  /**
147
147
  * Start log redirection.
148
148
  */
149
149
  start() {
150
- if (this.streamingTask) {
150
+ if (this.#streamingTask) {
151
151
  throw new Error('Streaming task already active');
152
152
  }
153
- this.stopLogging = false;
154
- this.streamingTask = this.streamLog();
153
+ this.#stopLogging = false;
154
+ this.#streamingTask = this.#streamLog();
155
155
  }
156
156
  /**
157
157
  * Stop log redirection.
158
158
  */
159
159
  async stop() {
160
- if (!this.streamingTask) {
160
+ if (!this.#streamingTask) {
161
161
  throw new Error('Streaming task is not active');
162
162
  }
163
- this.stopLogging = true;
163
+ this.#stopLogging = true;
164
164
  try {
165
- await this.streamingTask;
165
+ await this.#streamingTask;
166
166
  }
167
167
  catch (err) {
168
168
  if (!(err instanceof Error && err.name === 'AbortError')) {
@@ -170,30 +170,30 @@ export class StreamedLog {
170
170
  }
171
171
  }
172
172
  finally {
173
- this.streamingTask = null;
173
+ this.#streamingTask = null;
174
174
  }
175
175
  }
176
176
  /**
177
177
  * Get log stream from response and redirect it to another log.
178
178
  */
179
- async streamLog() {
179
+ async #streamLog() {
180
180
  try {
181
- const logStream = await this.logClient.stream({ raw: true });
181
+ const logStream = await this.#logClient.stream({ raw: true });
182
182
  if (!logStream) {
183
183
  return;
184
184
  }
185
- const lastChunkRemainder = await this.logStreamChunks(logStream);
185
+ const lastChunkRemainder = await this.#logStreamChunks(logStream);
186
186
  // Process whatever is left when exiting. Maybe it is incomplete, maybe it is last log without EOL.
187
187
  const lastMessage = Buffer.from(lastChunkRemainder).toString().trim();
188
188
  if (lastMessage.length) {
189
- this.destinationLog.info(lastMessage);
189
+ this.#destinationLog.info(lastMessage);
190
190
  }
191
191
  }
192
192
  catch (err) {
193
193
  log.warning(`Log redirection stopped due to error`, err);
194
194
  }
195
195
  }
196
- async logStreamChunks(logStream) {
196
+ async #logStreamChunks(logStream) {
197
197
  // Chunk may be incomplete. Keep remainder for next chunk.
198
198
  let previousChunkRemainder = new Uint8Array();
199
199
  for await (const chunk of logStream) {
@@ -205,10 +205,10 @@ export class StreamedLog {
205
205
  const lastCompleteMessageIndex = chunkWithPreviousRemainder.lastIndexOf(0x0a);
206
206
  previousChunkRemainder = chunkWithPreviousRemainder.slice(lastCompleteMessageIndex);
207
207
  // Push complete part of the chunk to the buffer
208
- this.streamBuffer.push(Buffer.from(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex)));
209
- this.logBufferContent();
208
+ this.#streamBuffer.push(Buffer.from(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex)));
209
+ this.#logBufferContent();
210
210
  // Keep processing the new data until stopped
211
- if (this.stopLogging) {
211
+ if (this.#stopLogging) {
212
212
  break;
213
213
  }
214
214
  }
@@ -217,26 +217,26 @@ export class StreamedLog {
217
217
  /**
218
218
  * Parse the buffer and log complete messages.
219
219
  */
220
- logBufferContent() {
221
- const allParts = Buffer.concat(this.streamBuffer).toString().split(this.splitMarker).slice(1);
220
+ #logBufferContent() {
221
+ const allParts = Buffer.concat(this.#streamBuffer).toString().split(this.#splitMarker).slice(1);
222
222
  // Parse the buffer parts into complete messages
223
223
  const messageMarkers = allParts.filter((_, i) => i % 2 === 0);
224
224
  const messageContents = allParts.filter((_, i) => i % 2 !== 0);
225
- this.streamBuffer = [];
225
+ this.#streamBuffer = [];
226
226
  messageMarkers.forEach((marker, index) => {
227
227
  const decodedMarker = marker;
228
228
  const decodedContent = messageContents[index];
229
- if (this.relevancyTimeLimit) {
229
+ if (this.#relevancyTimeLimit) {
230
230
  // Log only relevant messages. Ignore too old log messages.
231
231
  const logTime = new Date(decodedMarker);
232
- if (logTime < this.relevancyTimeLimit) {
232
+ if (logTime < this.#relevancyTimeLimit) {
233
233
  return;
234
234
  }
235
235
  }
236
236
  const message = decodedMarker + decodedContent;
237
237
  // Original log level information is not available. Log all on info level. Log level could be guessed for
238
238
  // some logs, but for any multiline logs such guess would be probably correct only for the first line.
239
- this.destinationLog.info(message.trim());
239
+ this.#destinationLog.info(message.trim());
240
240
  });
241
241
  }
242
242
  }
@@ -35,17 +35,11 @@ export type { AllowedHttpMethods, RequestQueue, RequestQueueClientAddRequestResu
35
35
  * @see https://docs.apify.com/platform/storage/request-queue
36
36
  */
37
37
  export declare class RequestQueueClient extends ResourceClient {
38
- private clientKey?;
39
- private timeoutSecs?;
38
+ #private;
40
39
  /**
41
40
  * @hidden
42
41
  */
43
42
  constructor(options: ApiClientSubResourceOptions, userOptions?: RequestQueueUserOptions);
44
- /**
45
- * Picks the timeout of a request: an explicit per-call `timeoutSecs` as is, otherwise the method's default
46
- * tier, capped at the queue-wide `timeoutSecs` when one was given.
47
- */
48
- private resolveTimeout;
49
43
  /**
50
44
  * Gets the Request queue object from the Apify API.
51
45
  *