apify-client 2.25.1-beta.8 → 2.26.0

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.
@@ -64,14 +64,16 @@ class ApifyApiError extends Error {
64
64
  let type;
65
65
  let responseData = response.data;
66
66
  let errorData;
67
- // Some methods (e.g. downloadItems) set up forceBuffer on request response. If this request failed
68
- // the body buffer needs to parse to get the correct error.
67
+ // A `forceBuffer` request (e.g. `downloadItems()`) and a failed streaming request, whose body `HttpClient`
68
+ // has read into a buffer, both arrive unparsed. Parse the body here to get at the error.
69
69
  if ((0, utils_1.isBuffer)(responseData)) {
70
+ const body = (0, body_parser_1.isomorphicBufferToString)(response.data, 'utf-8');
70
71
  try {
71
- responseData = JSON.parse((0, body_parser_1.isomorphicBufferToString)(response.data, 'utf-8'));
72
+ responseData = JSON.parse(body);
72
73
  }
73
74
  catch {
74
- // This can happen. The data in the response body are malformed.
75
+ // A body that is not JSON at all, such as an HTML error page from a proxy, is kept as text.
76
+ responseData = body;
75
77
  }
76
78
  }
77
79
  if (responseData && responseData.error) {
@@ -1,6 +1,20 @@
1
1
  import type { ApifyClient } from '../apify_client';
2
2
  import type { HttpClient } from '../http_client';
3
3
  import type { PaginatedResponse, PaginationOptions } from '../utils';
4
+ /**
5
+ * Percent-encodes a caller-supplied URL path segment so it cannot restructure the request path.
6
+ *
7
+ * Empty strings and dot segments are rejected instead of encoded, because URL parsers resolve
8
+ * dot segments after decoding - `records/%2E%2E` collapses to the parent endpoint just like `records/..`.
9
+ * @private
10
+ */
11
+ export declare function toPathSegment(value: string): string;
12
+ /**
13
+ * Builds a URL path from segments. A plain string is used as-is, so literal paths such as
14
+ * `requests/batch` keep their separators; an array has each of its segments encoded individually.
15
+ * @private
16
+ */
17
+ export declare function toPath(path: string | string[]): string;
4
18
  /** @private */
5
19
  export interface ApiClientOptions {
6
20
  baseUrl: string;
@@ -31,8 +45,8 @@ export declare abstract class ApiClient {
31
45
  params?: Record<string, unknown>;
32
46
  constructor(options: ApiClientOptions);
33
47
  protected _subResourceOptions<T>(moreOptions?: T): BaseOptions & T;
34
- protected _url(path?: string): string;
35
- protected _publicUrl(path?: string): string;
48
+ protected _url(path?: string | string[]): string;
49
+ protected _publicUrl(path?: string | string[]): string;
36
50
  protected _params<T>(endpointParams?: T): Record<string, unknown>;
37
51
  protected _toSafeId(id: string): string;
38
52
  /**
@@ -1,6 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ApiClient = void 0;
4
+ exports.toPathSegment = toPathSegment;
5
+ exports.toPath = toPath;
6
+ const tslib_1 = require("tslib");
7
+ const ow_1 = tslib_1.__importDefault(require("ow"));
8
+ /**
9
+ * Percent-encodes a caller-supplied URL path segment so it cannot restructure the request path.
10
+ *
11
+ * Empty strings and dot segments are rejected instead of encoded, because URL parsers resolve
12
+ * dot segments after decoding - `records/%2E%2E` collapses to the parent endpoint just like `records/..`.
13
+ * @private
14
+ */
15
+ function toPathSegment(value) {
16
+ (0, ow_1.default)(value, ow_1.default.string.nonEmpty.validate((v) => ({
17
+ validator: v !== '.' && v !== '..',
18
+ message: 'URL path must not contain dot segments',
19
+ })));
20
+ return encodeURIComponent(value);
21
+ }
22
+ /**
23
+ * Builds a URL path from segments. A plain string is used as-is, so literal paths such as
24
+ * `requests/batch` keep their separators; an array has each of its segments encoded individually.
25
+ * @private
26
+ */
27
+ function toPath(path) {
28
+ return Array.isArray(path) ? path.map(toPathSegment).join('/') : path;
29
+ }
4
30
  /** @private */
5
31
  class ApiClient {
6
32
  id;
@@ -22,7 +48,7 @@ class ApiClient {
22
48
  this.baseUrl = baseUrl;
23
49
  this.publicBaseUrl = publicBaseUrl;
24
50
  this.resourcePath = resourcePath;
25
- this.url = id ? `${baseUrl}/${resourcePath}/${this.safeId}` : `${baseUrl}/${resourcePath}`;
51
+ this.url = id ? `${baseUrl}/${resourcePath}/${toPathSegment(this.safeId)}` : `${baseUrl}/${resourcePath}`;
26
52
  this.apifyClient = apifyClient;
27
53
  this.httpClient = httpClient;
28
54
  this.params = params;
@@ -38,20 +64,19 @@ class ApiClient {
38
64
  return { ...baseOptions, ...moreOptions };
39
65
  }
40
66
  _url(path) {
41
- return path ? `${this.url}/${path}` : this.url;
67
+ return path ? `${this.url}/${toPath(path)}` : this.url;
42
68
  }
43
69
  _publicUrl(path) {
44
70
  const url = this.id
45
- ? `${this.publicBaseUrl}/${this.resourcePath}/${this.safeId}`
71
+ ? `${this.publicBaseUrl}/${this.resourcePath}/${toPathSegment(this.safeId)}`
46
72
  : `${this.publicBaseUrl}/${this.resourcePath}`;
47
- return path ? `${url}/${path}` : url;
73
+ return path ? `${url}/${toPath(path)}` : url;
48
74
  }
49
75
  _params(endpointParams) {
50
76
  return { ...this.params, ...endpointParams };
51
77
  }
52
78
  _toSafeId(id) {
53
- // The id has the format `username/actor-name`, so we only need to replace the first `/`.
54
- return id.replace('/', '~');
79
+ return id.replaceAll('/', '~');
55
80
  }
56
81
  /**
57
82
  * Returns async iterator to iterate through all items and Promise that can be awaited to get first page of results.
@@ -10,6 +10,8 @@ const api_client_1 = require("./api_client");
10
10
  * 999999 seconds is more than 10 days.
11
11
  */
12
12
  const MAX_WAIT_FOR_FINISH = 999999;
13
+ /** How long `waitForFinish()` keeps polling a job that returns 404, to ride out replica lag, before it gives up. */
14
+ const MAX_WAIT_WHEN_JOB_NOT_EXIST_MILLIS = 3000;
13
15
  exports.SMALL_TIMEOUT_MILLIS = 5 * 1000; // For fast and common actions. Suitable for idempotent actions.
14
16
  exports.MEDIUM_TIMEOUT_MILLIS = 30 * 1000; // For actions that may take longer.
15
17
  exports.DEFAULT_TIMEOUT_MILLIS = 360 * 1000; // 6 minutes
@@ -65,15 +67,18 @@ class ResourceClient extends api_client_1.ApiClient {
65
67
  const { waitSecs = MAX_WAIT_FOR_FINISH } = options;
66
68
  const waitMillis = waitSecs * 1000;
67
69
  let job;
70
+ let notFoundSince;
68
71
  const startedAt = Date.now();
69
72
  const shouldRepeat = () => {
70
- const millisSinceStart = Date.now() - startedAt;
71
- if (millisSinceStart >= waitMillis)
73
+ const now = Date.now();
74
+ if (now - startedAt >= waitMillis)
75
+ return false;
76
+ if (notFoundSince !== undefined && now - notFoundSince >= MAX_WAIT_WHEN_JOB_NOT_EXIST_MILLIS)
72
77
  return false;
73
78
  const hasJobEnded = job && consts_1.ACT_JOB_TERMINAL_STATUSES.includes(job.status);
74
79
  return !hasJobEnded;
75
80
  };
76
- do {
81
+ while (true) {
77
82
  const millisSinceStart = Date.now() - startedAt;
78
83
  const remainingWaitSeconds = Math.round((waitMillis - millisSinceStart) / 1000);
79
84
  const waitForFinish = Math.max(0, remainingWaitSeconds);
@@ -85,18 +90,21 @@ class ResourceClient extends api_client_1.ApiClient {
85
90
  try {
86
91
  const response = await this.httpClient.call(requestOpts);
87
92
  job = (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
93
+ notFoundSince = undefined;
88
94
  }
89
95
  catch (err) {
90
96
  (0, utils_1.catchNotFoundOrThrow)(err);
91
97
  job = undefined;
98
+ notFoundSince ??= Date.now();
92
99
  }
93
- // It might take some time for database replicas to get up-to-date,
94
- // so getRun() might return null. Wait a little bit and try it again.
95
- if (!job)
96
- await new Promise((resolve) => {
97
- setTimeout(resolve, 250);
98
- });
99
- } while (shouldRepeat());
100
+ if (!shouldRepeat())
101
+ break;
102
+ // The API answers right away when the remaining wait rounds to 0 seconds, and database replicas may not see
103
+ // a new job for a short while, so pause before the next poll.
104
+ await new Promise((resolve) => {
105
+ setTimeout(resolve, 250);
106
+ });
107
+ }
100
108
  if (!job) {
101
109
  const constructorName = this.constructor.name;
102
110
  const jobName = constructorName.match(/(\w+)Client/)[1].toLowerCase();