apify-client 3.0.0-beta.1 → 3.0.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +21 -5
  2. package/dist/apify_api_error.d.ts +64 -22
  3. package/dist/apify_api_error.js +100 -30
  4. package/dist/apify_client.d.ts +150 -35
  5. package/dist/apify_client.js +198 -118
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/base/api_client.d.ts +9 -9
  9. package/dist/base/api_client.js +41 -45
  10. package/dist/base/resource_client.d.ts +24 -10
  11. package/dist/base/resource_client.js +78 -48
  12. package/dist/base/resource_collection_client.d.ts +15 -6
  13. package/dist/base/resource_collection_client.js +40 -21
  14. package/dist/body_parser.d.ts +3 -4
  15. package/dist/body_parser.js +20 -32
  16. package/dist/bundle.js +47 -52
  17. package/dist/bundle.js.map +1 -1
  18. package/dist/generated/api.d.ts +3363 -1185
  19. package/dist/generated/api.js +1 -2
  20. package/dist/generated/schemas.d.ts +8146 -0
  21. package/dist/generated/schemas.js +1866 -0
  22. package/dist/http_clients/axios.d.ts +61 -0
  23. package/dist/http_clients/axios.js +119 -0
  24. package/dist/http_clients/base.d.ts +391 -0
  25. package/dist/http_clients/base.js +650 -0
  26. package/dist/http_clients/index.d.ts +4 -0
  27. package/dist/http_clients/index.js +2 -0
  28. package/dist/http_compressors/base.d.ts +40 -0
  29. package/dist/http_compressors/base.js +9 -0
  30. package/dist/http_compressors/brotli.d.ts +33 -0
  31. package/dist/http_compressors/brotli.js +39 -0
  32. package/dist/http_compressors/gzip.d.ts +33 -0
  33. package/dist/http_compressors/gzip.js +39 -0
  34. package/dist/http_compressors/index.d.ts +8 -0
  35. package/dist/http_compressors/index.js +3 -0
  36. package/dist/http_compressors/resolve.d.ts +24 -0
  37. package/dist/http_compressors/resolve.js +30 -0
  38. package/dist/http_compressors/zstd.d.ts +34 -0
  39. package/dist/http_compressors/zstd.js +43 -0
  40. package/dist/index.d.ts +38 -32
  41. package/dist/index.js +36 -36
  42. package/dist/invalid_response_body_error.d.ts +14 -0
  43. package/dist/invalid_response_body_error.js +18 -0
  44. package/dist/lazy_schema.d.ts +8 -0
  45. package/dist/lazy_schema.js +11 -0
  46. package/dist/models.d.ts +196 -278
  47. package/dist/models.js +14 -15
  48. package/dist/resource_clients/actor.d.ts +115 -45
  49. package/dist/resource_clients/actor.js +187 -116
  50. package/dist/resource_clients/actor_collection.d.ts +21 -17
  51. package/dist/resource_clients/actor_collection.js +26 -21
  52. package/dist/resource_clients/actor_env_var.d.ts +13 -6
  53. package/dist/resource_clients/actor_env_var.js +21 -14
  54. package/dist/resource_clients/actor_env_var_collection.d.ts +18 -22
  55. package/dist/resource_clients/actor_env_var_collection.js +23 -20
  56. package/dist/resource_clients/actor_server.d.ts +149 -0
  57. package/dist/resource_clients/actor_server.js +199 -0
  58. package/dist/resource_clients/actor_version.d.ts +30 -10
  59. package/dist/resource_clients/actor_version.js +29 -23
  60. package/dist/resource_clients/actor_version_collection.d.ts +20 -21
  61. package/dist/resource_clients/actor_version_collection.js +25 -20
  62. package/dist/resource_clients/build.d.ts +24 -11
  63. package/dist/resource_clients/build.js +43 -26
  64. package/dist/resource_clients/build_collection.d.ts +10 -8
  65. package/dist/resource_clients/build_collection.js +13 -13
  66. package/dist/resource_clients/dataset.d.ts +87 -40
  67. package/dist/resource_clients/dataset.js +159 -175
  68. package/dist/resource_clients/dataset_collection.d.ts +13 -9
  69. package/dist/resource_clients/dataset_collection.js +29 -21
  70. package/dist/resource_clients/key_value_store.d.ts +110 -28
  71. package/dist/resource_clients/key_value_store.js +177 -99
  72. package/dist/resource_clients/key_value_store_collection.d.ts +13 -9
  73. package/dist/resource_clients/key_value_store_collection.js +29 -21
  74. package/dist/resource_clients/log.d.ts +42 -23
  75. package/dist/resource_clients/log.js +156 -85
  76. package/dist/resource_clients/request_queue.d.ts +77 -38
  77. package/dist/resource_clients/request_queue.js +251 -172
  78. package/dist/resource_clients/request_queue_collection.d.ts +12 -8
  79. package/dist/resource_clients/request_queue_collection.js +23 -20
  80. package/dist/resource_clients/run.d.ts +134 -34
  81. package/dist/resource_clients/run.js +225 -84
  82. package/dist/resource_clients/run_collection.d.ts +8 -6
  83. package/dist/resource_clients/run_collection.js +18 -18
  84. package/dist/resource_clients/schedule.d.ts +20 -11
  85. package/dist/resource_clients/schedule.js +36 -30
  86. package/dist/resource_clients/schedule_collection.d.ts +10 -6
  87. package/dist/resource_clients/schedule_collection.js +20 -17
  88. package/dist/resource_clients/store_collection.d.ts +9 -7
  89. package/dist/resource_clients/store_collection.js +18 -18
  90. package/dist/resource_clients/task.d.ts +44 -21
  91. package/dist/resource_clients/task.js +116 -86
  92. package/dist/resource_clients/task_collection.d.ts +13 -9
  93. package/dist/resource_clients/task_collection.js +19 -16
  94. package/dist/resource_clients/user.d.ts +22 -13
  95. package/dist/resource_clients/user.js +46 -47
  96. package/dist/resource_clients/webhook.d.ts +21 -12
  97. package/dist/resource_clients/webhook.js +35 -30
  98. package/dist/resource_clients/webhook_collection.d.ts +11 -7
  99. package/dist/resource_clients/webhook_collection.js +20 -17
  100. package/dist/resource_clients/webhook_dispatch.d.ts +9 -6
  101. package/dist/resource_clients/webhook_dispatch.js +11 -10
  102. package/dist/resource_clients/webhook_dispatch_collection.d.ts +7 -5
  103. package/dist/resource_clients/webhook_dispatch_collection.js +13 -13
  104. package/dist/response_validation_error.d.ts +27 -0
  105. package/dist/response_validation_error.js +38 -0
  106. package/dist/runtime/node.d.ts +6 -0
  107. package/dist/runtime/node.js +87 -0
  108. package/dist/runtime/types.d.ts +60 -0
  109. package/dist/runtime/types.js +1 -0
  110. package/dist/runtime/web.d.ts +5 -0
  111. package/dist/runtime/web.js +21 -0
  112. package/dist/schemas.d.ts +381 -0
  113. package/dist/schemas.js +37 -0
  114. package/dist/statistics.d.ts +1 -6
  115. package/dist/statistics.js +7 -11
  116. package/dist/timeouts.d.ts +84 -0
  117. package/dist/timeouts.js +37 -0
  118. package/dist/timezones.d.ts +1 -1
  119. package/dist/timezones.js +1 -2
  120. package/dist/utils.d.ts +99 -70
  121. package/dist/utils.js +251 -229
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +48 -47
  125. package/dist/argument_validation_error.d.ts +0 -17
  126. package/dist/argument_validation_error.js +0 -157
  127. package/dist/http_client.d.ts +0 -88
  128. package/dist/http_client.js +0 -260
  129. package/dist/index.mjs +0 -42
  130. package/dist/interceptors.d.ts +0 -19
  131. package/dist/interceptors.js +0 -110
@@ -1,9 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApiClient = void 0;
4
- const utils_1 = require("../utils");
1
+ import { minForLimitParam, toPath, toPathSegment } from '../utils.js';
5
2
  /** @private */
6
- class ApiClient {
3
+ export class ApiClient {
7
4
  id;
8
5
  safeId;
9
6
  baseUrl;
@@ -19,81 +16,81 @@ class ApiClient {
19
16
  constructor(options) {
20
17
  const { baseUrl, publicBaseUrl, apifyClient, httpClient, resourcePath, id, params = {} } = options;
21
18
  this.id = id;
22
- this.safeId = id && this._toSafeId(id);
19
+ this.safeId = id && this.toSafeId(id);
23
20
  this.baseUrl = baseUrl;
24
21
  this.publicBaseUrl = publicBaseUrl;
25
22
  this.resourcePath = resourcePath;
26
- this.url = id ? `${baseUrl}/${resourcePath}/${(0, utils_1.toPathSegment)(this.safeId)}` : `${baseUrl}/${resourcePath}`;
23
+ this.url = id ? `${baseUrl}/${resourcePath}/${toPathSegment(this.safeId)}` : `${baseUrl}/${resourcePath}`;
27
24
  this.apifyClient = apifyClient;
28
25
  this.httpClient = httpClient;
29
26
  this.params = params;
30
27
  }
31
- _subResourceOptions(moreOptions) {
28
+ subResourceOptions(moreOptions) {
32
29
  const baseOptions = {
33
- baseUrl: this._url(),
30
+ baseUrl: this.buildUrl(),
34
31
  publicBaseUrl: this.publicBaseUrl,
35
32
  apifyClient: this.apifyClient,
36
33
  httpClient: this.httpClient,
37
- params: this._params(),
34
+ params: this.buildParams(),
38
35
  };
39
36
  return { ...baseOptions, ...moreOptions };
40
37
  }
41
- _url(path) {
42
- return path ? `${this.url}/${(0, utils_1.toPath)(path)}` : this.url;
38
+ buildUrl(path) {
39
+ return path ? `${this.url}/${toPath(path)}` : this.url;
43
40
  }
44
- _publicUrl(path) {
41
+ buildPublicUrl(path) {
45
42
  const url = this.id
46
- ? `${this.publicBaseUrl}/${this.resourcePath}/${(0, utils_1.toPathSegment)(this.safeId)}`
43
+ ? `${this.publicBaseUrl}/${this.resourcePath}/${toPathSegment(this.safeId)}`
47
44
  : `${this.publicBaseUrl}/${this.resourcePath}`;
48
- return path ? `${url}/${(0, utils_1.toPath)(path)}` : url;
45
+ return path ? `${url}/${toPath(path)}` : url;
49
46
  }
50
- _params(endpointParams) {
47
+ buildParams(endpointParams) {
51
48
  return { ...this.params, ...endpointParams };
52
49
  }
53
- _toSafeId(id) {
50
+ toSafeId(id) {
54
51
  return id.replaceAll('/', '~');
55
52
  }
56
53
  /**
57
54
  * Returns async iterator to iterate through all items and Promise that can be awaited to get first page of results.
58
55
  */
59
- _listPaginatedFromCallback(getPaginatedList, options = {}) {
60
- const minForLimitParam = (a, b) => {
61
- // API treats 0 as undefined for limit parameter
62
- if (a === 0)
63
- a = undefined;
64
- if (b === 0)
65
- b = undefined;
66
- if (a === undefined)
67
- return b;
68
- if (b === undefined)
69
- return a;
70
- return Math.min(a, b);
71
- };
56
+ listPaginatedFromCallback(getPaginatedList, options = {}) {
72
57
  // `chunkSize` only sizes this loop's requests; it is not an API parameter, so it must not reach
73
- // `_params()` and the query string.
58
+ // `buildParams()` and the query string. The same goes for `timeoutSecs` and `signal`, which callers take out
59
+ // before calling this, since they also apply to every page request.
74
60
  const { chunkSize, ...listOptions } = options;
75
- const paginatedListPromise = getPaginatedList({
76
- ...listOptions,
77
- limit: minForLimitParam(options.limit, chunkSize),
78
- });
61
+ const firstPageLimit = minForLimitParam(options.limit, chunkSize);
62
+ const paginatedListPromise = getPaginatedList({ ...listOptions, limit: firstPageLimit });
63
+ // A page of dataset items can return more or fewer items than the rows it scanned (see `PaginatedList.count`).
64
+ // The next offset and the stop condition follow the scanned rows: advancing by `items.length` would re-scan
65
+ // rows after a filter dropped some and skip rows after `unwind` multiplied them, and stopping at an empty page
66
+ // would end the iteration in front of rows a filter hid. The step is the larger of `count` and `items.length`,
67
+ // capped at the rows the request asked for, which keeps an unwound page from advancing past rows the next
68
+ // request would then never read.
69
+ const scannedRows = (page, requestedLimit) => {
70
+ const scanned = Math.max(page.count ?? 0, page.items.length);
71
+ return requestedLimit ? Math.min(scanned, requestedLimit) : scanned;
72
+ };
73
+ // `total` is not consulted, as it changes when the listed resource grows during the iteration.
79
74
  async function* asyncGenerator() {
80
75
  let currentPage = await paginatedListPromise;
81
76
  yield* currentPage.items;
82
- const offset = options.offset ?? 0;
83
- const limit = Math.min(options.limit || currentPage.total, currentPage.total);
84
- let currentOffset = offset + currentPage.items.length;
85
- let remainingItems = Math.min(currentPage.total - offset, limit) - currentPage.items.length;
86
- while (currentPage.items.length > 0 && // Continue only if at least some items were returned in the last page.
87
- remainingItems > 0) {
77
+ let pageScanned = scannedRows(currentPage, firstPageLimit);
78
+ let currentOffset = (options.offset ?? 0) + pageScanned;
79
+ let remainingItems = options.limit ? options.limit - pageScanned : undefined;
80
+ while (pageScanned > 0 && // Continue only if the last page scanned some rows.
81
+ (remainingItems === undefined || remainingItems > 0)) {
82
+ const requestedLimit = minForLimitParam(remainingItems, chunkSize);
88
83
  const newOptions = {
89
84
  ...listOptions,
90
- limit: minForLimitParam(remainingItems, chunkSize),
85
+ limit: requestedLimit,
91
86
  offset: currentOffset,
92
87
  };
93
88
  currentPage = await getPaginatedList(newOptions);
94
89
  yield* currentPage.items;
95
- currentOffset += currentPage.items.length;
96
- remainingItems -= currentPage.items.length;
90
+ pageScanned = scannedRows(currentPage, requestedLimit);
91
+ currentOffset += pageScanned;
92
+ if (remainingItems !== undefined)
93
+ remainingItems -= pageScanned;
97
94
  }
98
95
  }
99
96
  return Object.defineProperty(paginatedListPromise, Symbol.asyncIterator, {
@@ -101,4 +98,3 @@ class ApiClient {
101
98
  });
102
99
  }
103
100
  }
104
- exports.ApiClient = ApiClient;
@@ -1,24 +1,38 @@
1
1
  import type { ACT_JOB_STATUSES } from '@apify/consts';
2
- import { ApiClient } from './api_client';
3
- export declare const SMALL_TIMEOUT_MILLIS: number;
4
- export declare const MEDIUM_TIMEOUT_MILLIS: number;
5
- export declare const DEFAULT_TIMEOUT_MILLIS: number;
2
+ import type { z } from 'zod';
3
+ import type { Timeout, TimeoutOptions, TimeoutTier } from '../timeouts.js';
4
+ import { ApiClient } from './api_client.js';
6
5
  /**
7
6
  * Resource client.
8
7
  * @private
9
8
  */
10
9
  export declare class ResourceClient extends ApiClient {
11
- protected _get<T, R>(options?: T, timeoutMillis?: number): Promise<R | undefined>;
12
- protected _update<T, R>(newFields: T, timeoutMillis?: number): Promise<R>;
13
- protected _delete(timeoutMillis?: number): Promise<void>;
10
+ /**
11
+ * Picks the timeout of a request that asks the API to hold its response with `waitForFinish`. The request
12
+ * gets the hold the caller asked for plus the round trip its tier allows, so the client does not abort a
13
+ * request while the API is still holding it - which for `start()` and `build()` would retry a call that
14
+ * creates a resource. An explicit per-call `timeoutSecs` is used as given.
15
+ */
16
+ protected timeoutForWaitForFinish(timeoutSecs: Timeout | undefined, tier: TimeoutTier, waitForFinishSecs: number | undefined): Timeout;
17
+ /**
18
+ * A 404 resolves to `undefined` only when the client names its resource by ID. A chained client without one, such
19
+ * as `run.dataset()`, throws it instead (see `catchNotFoundForResourceOrThrow()`).
20
+ */
21
+ protected getResource<T, R>(schema: z.ZodType, options: T, timeoutSecs: Timeout, signal?: AbortSignal): Promise<R | undefined>;
22
+ protected updateResource<T, R>(schema: z.ZodType, newFields: T, timeoutSecs: Timeout, signal?: AbortSignal): Promise<R>;
23
+ /**
24
+ * A 404 is swallowed, keeping the DELETE idempotent, only when the client names its resource by ID. A chained client
25
+ * without one throws it instead (see `catchNotFoundForResourceOrThrow()`).
26
+ */
27
+ protected deleteResource(timeoutSecs: Timeout, signal?: AbortSignal): Promise<void>;
14
28
  /**
15
29
  * This function is used in Build and Run endpoints so it's kept
16
30
  * here to stay DRY.
17
31
  */
18
- protected _waitForFinish<R extends {
32
+ protected waitForJobFinish<R extends {
19
33
  status: (typeof ACT_JOB_STATUSES)[keyof typeof ACT_JOB_STATUSES];
20
- }>(options?: WaitForFinishOptions): Promise<R>;
34
+ }>(schema: z.ZodType, options?: WaitForFinishOptions): Promise<R>;
21
35
  }
22
- export interface WaitForFinishOptions {
36
+ export interface WaitForFinishOptions extends TimeoutOptions {
23
37
  waitSecs?: number;
24
38
  }
@@ -1,108 +1,138 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ResourceClient = exports.DEFAULT_TIMEOUT_MILLIS = exports.MEDIUM_TIMEOUT_MILLIS = exports.SMALL_TIMEOUT_MILLIS = void 0;
4
- const consts_1 = require("@apify/consts");
5
- const utils_1 = require("../utils");
6
- const api_client_1 = require("./api_client");
1
+ import { ACT_JOB_TERMINAL_STATUSES } from '@apify/consts';
2
+ import { catchNotFoundForResourceOrThrow, catchNotFoundOrThrow, parseResponse, sleep } from '../utils.js';
3
+ import { ApiClient } from './api_client.js';
7
4
  /**
8
5
  * We need to supply some number for the API,
9
6
  * because it would not accept "Infinity".
10
7
  * 999999 seconds is more than 10 days.
11
8
  */
12
9
  const MAX_WAIT_FOR_FINISH = 999999;
13
- exports.SMALL_TIMEOUT_MILLIS = 5 * 1000; // For fast and common actions. Suitable for idempotent actions.
14
- exports.MEDIUM_TIMEOUT_MILLIS = 30 * 1000; // For actions that may take longer.
15
- exports.DEFAULT_TIMEOUT_MILLIS = 360 * 1000; // 6 minutes
10
+ /** The API holds a `waitForFinish` response for at most a minute, however long the parameter asks for. */
11
+ const MAX_WAIT_FOR_FINISH_HOLD_SECS = 60;
12
+ /** How long `waitForFinish()` keeps polling a job that returns 404, to ride out replica lag, before it gives up. */
13
+ const MAX_WAIT_WHEN_JOB_NOT_EXIST_MILLIS = 3000;
16
14
  /**
17
15
  * Resource client.
18
16
  * @private
19
17
  */
20
- class ResourceClient extends api_client_1.ApiClient {
21
- async _get(options = {}, timeoutMillis) {
18
+ export class ResourceClient extends ApiClient {
19
+ /**
20
+ * Picks the timeout of a request that asks the API to hold its response with `waitForFinish`. The request
21
+ * gets the hold the caller asked for plus the round trip its tier allows, so the client does not abort a
22
+ * request while the API is still holding it - which for `start()` and `build()` would retry a call that
23
+ * creates a resource. An explicit per-call `timeoutSecs` is used as given.
24
+ */
25
+ timeoutForWaitForFinish(timeoutSecs, tier, waitForFinishSecs) {
26
+ if (timeoutSecs !== undefined)
27
+ return timeoutSecs;
28
+ if (waitForFinishSecs === undefined)
29
+ return tier;
30
+ const holdSecs = Math.min(waitForFinishSecs, MAX_WAIT_FOR_FINISH_HOLD_SECS);
31
+ if (holdSecs <= 0)
32
+ return tier;
33
+ return holdSecs + this.httpClient.timeoutMillis[tier] / 1000;
34
+ }
35
+ /**
36
+ * A 404 resolves to `undefined` only when the client names its resource by ID. A chained client without one, such
37
+ * as `run.dataset()`, throws it instead (see `catchNotFoundForResourceOrThrow()`).
38
+ */
39
+ async getResource(schema, options, timeoutSecs, signal) {
22
40
  const requestOpts = {
23
- url: this._url(),
41
+ url: this.buildUrl(),
24
42
  method: 'GET',
25
- params: this._params(options),
26
- timeout: timeoutMillis,
43
+ params: this.buildParams(options),
44
+ timeoutSecs,
45
+ signal,
27
46
  };
28
47
  try {
29
48
  const response = await this.httpClient.call(requestOpts);
30
- return (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
49
+ return parseResponse(response, schema);
31
50
  }
32
51
  catch (err) {
33
- (0, utils_1.catchNotFoundOrThrow)(err);
52
+ catchNotFoundForResourceOrThrow(err, this.id);
34
53
  }
35
54
  return undefined;
36
55
  }
37
- async _update(newFields, timeoutMillis) {
56
+ async updateResource(schema, newFields, timeoutSecs, signal) {
38
57
  const response = await this.httpClient.call({
39
- url: this._url(),
58
+ url: this.buildUrl(),
40
59
  method: 'PUT',
41
- params: this._params(),
60
+ params: this.buildParams(),
42
61
  data: newFields,
43
- timeout: timeoutMillis,
62
+ timeoutSecs,
63
+ signal,
44
64
  });
45
- return (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
65
+ return parseResponse(response, schema);
46
66
  }
47
- async _delete(timeoutMillis) {
67
+ /**
68
+ * A 404 is swallowed, keeping the DELETE idempotent, only when the client names its resource by ID. A chained client
69
+ * without one throws it instead (see `catchNotFoundForResourceOrThrow()`).
70
+ */
71
+ async deleteResource(timeoutSecs, signal) {
48
72
  try {
49
73
  await this.httpClient.call({
50
- url: this._url(),
74
+ url: this.buildUrl(),
51
75
  method: 'DELETE',
52
- params: this._params(),
53
- timeout: timeoutMillis,
76
+ params: this.buildParams(),
77
+ timeoutSecs,
78
+ signal,
54
79
  });
55
80
  }
56
81
  catch (err) {
57
- (0, utils_1.catchNotFoundOrThrow)(err);
82
+ catchNotFoundForResourceOrThrow(err, this.id);
58
83
  }
59
84
  }
60
85
  /**
61
86
  * This function is used in Build and Run endpoints so it's kept
62
87
  * here to stay DRY.
63
88
  */
64
- async _waitForFinish(options = {}) {
65
- const { waitSecs = MAX_WAIT_FOR_FINISH } = options;
89
+ async waitForJobFinish(schema, options = {}) {
90
+ const { waitSecs = MAX_WAIT_FOR_FINISH, timeoutSecs = 'noTimeout', signal } = options;
66
91
  const waitMillis = waitSecs * 1000;
67
92
  let job;
93
+ let notFoundSince;
94
+ let notFoundError;
68
95
  const startedAt = Date.now();
69
96
  const shouldRepeat = () => {
70
- const millisSinceStart = Date.now() - startedAt;
71
- if (millisSinceStart >= waitMillis)
97
+ const now = Date.now();
98
+ if (now - startedAt >= waitMillis)
99
+ return false;
100
+ if (notFoundSince !== undefined && now - notFoundSince >= MAX_WAIT_WHEN_JOB_NOT_EXIST_MILLIS)
72
101
  return false;
73
- const hasJobEnded = job && consts_1.ACT_JOB_TERMINAL_STATUSES.includes(job.status);
102
+ const hasJobEnded = job && ACT_JOB_TERMINAL_STATUSES.includes(job.status);
74
103
  return !hasJobEnded;
75
104
  };
76
- do {
105
+ while (true) {
77
106
  const millisSinceStart = Date.now() - startedAt;
78
107
  const remainingWaitSeconds = Math.round((waitMillis - millisSinceStart) / 1000);
79
108
  const waitForFinish = Math.max(0, remainingWaitSeconds);
80
109
  const requestOpts = {
81
- url: this._url(),
110
+ url: this.buildUrl(),
82
111
  method: 'GET',
83
- params: this._params({ waitForFinish }),
112
+ params: this.buildParams({ waitForFinish }),
113
+ timeoutSecs,
114
+ signal,
84
115
  };
85
116
  try {
86
117
  const response = await this.httpClient.call(requestOpts);
87
- job = (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
118
+ job = parseResponse(response, schema);
119
+ notFoundSince = undefined;
88
120
  }
89
121
  catch (err) {
90
- (0, utils_1.catchNotFoundOrThrow)(err);
122
+ catchNotFoundOrThrow(err);
91
123
  job = undefined;
124
+ notFoundSince ??= Date.now();
125
+ notFoundError = err;
92
126
  }
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 (!job) {
101
- const constructorName = this.constructor.name;
102
- const jobName = constructorName.match(/(\w+)Client/)[1].toLowerCase();
103
- throw new Error(`Waiting for ${jobName} to finish failed. Cannot fetch actor ${jobName} details from the server.`);
127
+ if (!shouldRepeat())
128
+ break;
129
+ // The API answers right away when the remaining wait rounds to 0 seconds, and database replicas may not see
130
+ // a new job for a short while, so pause before the next poll.
131
+ await sleep(250, signal);
132
+ signal?.throwIfAborted();
104
133
  }
134
+ if (!job)
135
+ throw notFoundError;
105
136
  return job;
106
137
  }
107
138
  }
108
- exports.ResourceClient = ResourceClient;
@@ -1,5 +1,7 @@
1
- import type { PaginatedResponse, PaginationOptions } from '../utils';
2
- import { ApiClient } from './api_client';
1
+ import type { z } from 'zod';
2
+ import type { Timeout, TimeoutOptions } from '../timeouts.js';
3
+ import type { PaginatedResponse, PaginationOptions } from '../utils.js';
4
+ import { ApiClient } from './api_client.js';
3
5
  /**
4
6
  * Resource collection client.
5
7
  * @private
@@ -8,11 +10,18 @@ export declare class ResourceCollectionClient extends ApiClient {
8
10
  /**
9
11
  * @private
10
12
  */
11
- protected _list<T, R>(options?: T): Promise<R>;
13
+ protected listResources<T, R>(schema: z.ZodType, options: T | undefined, timeoutSecs: Timeout, signal?: AbortSignal): Promise<R>;
14
+ /**
15
+ * Lists an endpoint that returns every item in one response and ignores `offset` and `limit`. The result can be
16
+ * awaited as that response or iterated over its items, with a single request either way.
17
+ */
18
+ protected listUnpaginatedResources<Data, R extends PaginatedResponse<Data>>(schema: z.ZodType, timeoutSecs: Timeout, signal?: AbortSignal): AsyncIterable<Data> & Promise<R>;
12
19
  /**
13
20
  * Returns async iterator to iterate through all items and Promise that can be awaited to get first page of results.
21
+ * `defaultTimeoutSecs` applies to every page request unless `options.timeoutSecs` overrides it, and
22
+ * `options.signal` goes to every page request.
14
23
  */
15
- protected _listPaginated<T extends PaginationOptions, Data, R extends PaginatedResponse<Data>>(options?: T): AsyncIterable<Data> & Promise<R>;
16
- protected _create<D, R>(resource: D): Promise<R>;
17
- protected _getOrCreate<D, R>(name?: string, resource?: D): Promise<R>;
24
+ protected listResourcesPaginated<T extends PaginationOptions & TimeoutOptions, Data, R extends PaginatedResponse<Data>>(schema: z.ZodType, options: T, defaultTimeoutSecs: Timeout): AsyncIterable<Data> & Promise<R>;
25
+ protected createResource<D, R>(schema: z.ZodType, resource: D, timeoutSecs: Timeout, signal?: AbortSignal): Promise<R>;
26
+ protected getOrCreateResource<D, R>(schema: z.ZodType, name: string | undefined, resource: D | undefined, timeoutSecs: Timeout, signal?: AbortSignal): Promise<R>;
18
27
  }
@@ -1,47 +1,66 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ResourceCollectionClient = void 0;
4
- const utils_1 = require("../utils");
5
- const api_client_1 = require("./api_client");
1
+ import { parseResponse } from '../utils.js';
2
+ import { ApiClient } from './api_client.js';
6
3
  /**
7
4
  * Resource collection client.
8
5
  * @private
9
6
  */
10
- class ResourceCollectionClient extends api_client_1.ApiClient {
7
+ export class ResourceCollectionClient extends ApiClient {
11
8
  /**
12
9
  * @private
13
10
  */
14
- async _list(options = {}) {
11
+ async listResources(schema, options, timeoutSecs, signal) {
15
12
  const response = await this.httpClient.call({
16
- url: this._url(),
13
+ url: this.buildUrl(),
17
14
  method: 'GET',
18
- params: this._params(options),
15
+ params: this.buildParams(options),
16
+ timeoutSecs,
17
+ signal,
18
+ });
19
+ return parseResponse(response, schema);
20
+ }
21
+ /**
22
+ * Lists an endpoint that returns every item in one response and ignores `offset` and `limit`. The result can be
23
+ * awaited as that response or iterated over its items, with a single request either way.
24
+ */
25
+ listUnpaginatedResources(schema, timeoutSecs, signal) {
26
+ const listPromise = this.listResources(schema, undefined, timeoutSecs, signal);
27
+ return Object.defineProperty(listPromise, Symbol.asyncIterator, {
28
+ async *value() {
29
+ yield* (await listPromise).items;
30
+ },
19
31
  });
20
- return (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
21
32
  }
22
33
  /**
23
34
  * Returns async iterator to iterate through all items and Promise that can be awaited to get first page of results.
35
+ * `defaultTimeoutSecs` applies to every page request unless `options.timeoutSecs` overrides it, and
36
+ * `options.signal` goes to every page request.
24
37
  */
25
- _listPaginated(options = {}) {
26
- return this._listPaginatedFromCallback((this._list.bind(this)), options);
38
+ listResourcesPaginated(schema, options, defaultTimeoutSecs) {
39
+ // `timeoutSecs` and `signal` only apply to the page requests; they are not API parameters, so they must not
40
+ // reach the query string.
41
+ const { timeoutSecs = defaultTimeoutSecs, signal, ...listOptions } = options;
42
+ return this.listPaginatedFromCallback(async (pageOptions) => this.listResources(schema, pageOptions, timeoutSecs, signal), listOptions);
27
43
  }
28
- async _create(resource) {
44
+ async createResource(schema, resource, timeoutSecs, signal) {
29
45
  const response = await this.httpClient.call({
30
- url: this._url(),
46
+ url: this.buildUrl(),
31
47
  method: 'POST',
32
- params: this._params(),
48
+ params: this.buildParams(),
33
49
  data: resource,
50
+ timeoutSecs,
51
+ signal,
34
52
  });
35
- return (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
53
+ return parseResponse(response, schema);
36
54
  }
37
- async _getOrCreate(name, resource) {
55
+ async getOrCreateResource(schema, name, resource, timeoutSecs, signal) {
38
56
  const response = await this.httpClient.call({
39
- url: this._url(),
57
+ url: this.buildUrl(),
40
58
  method: 'POST',
41
- params: this._params({ name }),
59
+ params: this.buildParams({ name }),
42
60
  data: resource,
61
+ timeoutSecs,
62
+ signal,
43
63
  });
44
- return (0, utils_1.parseDateFields)((0, utils_1.pluckData)(response.data));
64
+ return parseResponse(response, schema);
45
65
  }
46
66
  }
47
- exports.ResourceCollectionClient = ResourceCollectionClient;
@@ -1,13 +1,12 @@
1
1
  import type { JsonArray, JsonObject } from 'type-fest';
2
2
  /**
3
- * Parses a Buffer or ArrayBuffer using the provided content type header.
3
+ * Parses a binary response body using the provided content type header.
4
4
  *
5
5
  * - application/json is returned as a parsed object.
6
6
  * - application/*xml and text/* are returned as strings.
7
7
  * - everything else is returned as original body.
8
8
  *
9
9
  * If the header includes a charset, the body will be stringified only
10
- * if the charset represents a known encoding to Node.js or Browser.
10
+ * if the charset is an encoding `TextDecoder` knows.
11
11
  */
12
- export declare function maybeParseBody(body: Buffer | ArrayBuffer, contentTypeHeader: string): string | Buffer | ArrayBuffer | JsonObject | JsonArray;
13
- export declare function isomorphicBufferToString(buffer: Buffer | ArrayBuffer, encoding: BufferEncoding): string;
12
+ export declare function maybeParseBody(body: ArrayBuffer | ArrayBufferView, contentTypeHeader: string): string | ArrayBuffer | ArrayBufferView | JsonObject | JsonArray;
@@ -1,27 +1,21 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.maybeParseBody = maybeParseBody;
4
- exports.isomorphicBufferToString = isomorphicBufferToString;
5
- const tslib_1 = require("tslib");
6
- const content_type_1 = tslib_1.__importDefault(require("content-type"));
7
- const utils_1 = require("./utils");
1
+ import { parse as parseContentType } from 'content-type';
8
2
  const CONTENT_TYPE_JSON = 'application/json';
9
3
  const STRINGIFIABLE_CONTENT_TYPE_RXS = [new RegExp(`^${CONTENT_TYPE_JSON}`, 'i'), /^application\/.*xml$/i, /^text\//i];
10
4
  /**
11
- * Parses a Buffer or ArrayBuffer using the provided content type header.
5
+ * Parses a binary response body using the provided content type header.
12
6
  *
13
7
  * - application/json is returned as a parsed object.
14
8
  * - application/*xml and text/* are returned as strings.
15
9
  * - everything else is returned as original body.
16
10
  *
17
11
  * If the header includes a charset, the body will be stringified only
18
- * if the charset represents a known encoding to Node.js or Browser.
12
+ * if the charset is an encoding `TextDecoder` knows.
19
13
  */
20
- function maybeParseBody(body, contentTypeHeader) {
14
+ export function maybeParseBody(body, contentTypeHeader) {
21
15
  let contentType;
22
16
  let charset;
23
17
  try {
24
- const result = content_type_1.default.parse(contentTypeHeader);
18
+ const result = parseContentType(contentTypeHeader);
25
19
  contentType = result.type;
26
20
  charset = result.parameters.charset;
27
21
  }
@@ -29,35 +23,29 @@ function maybeParseBody(body, contentTypeHeader) {
29
23
  // can't parse, keep original body
30
24
  return body;
31
25
  }
32
- // If we can't successfully parse it, we return
26
+ if (!isContentTypeStringifiable(contentType))
27
+ return body;
28
+ // If we can't successfully decode it, we return
33
29
  // the original buffer rather than a mangled string.
34
- if (!areDataStringifiable(contentType, charset))
30
+ const decoder = createDecoder(charset);
31
+ if (!decoder)
35
32
  return body;
36
- const dataString = isomorphicBufferToString(body, charset);
33
+ const dataString = decoder.decode(body);
37
34
  return contentType === CONTENT_TYPE_JSON ? JSON.parse(dataString) : dataString;
38
35
  }
39
- function isomorphicBufferToString(buffer, encoding) {
40
- if (buffer.constructor.name !== ArrayBuffer.name) {
41
- return buffer.toString(encoding);
36
+ function createDecoder(charset) {
37
+ try {
38
+ // No charset defaults to utf-8. A leading BOM is kept, so a BOM-prefixed CSV stored in a key-value store
39
+ // round-trips through `getRecord()` unchanged.
40
+ return new TextDecoder(charset, { ignoreBOM: true });
41
+ }
42
+ catch {
43
+ // `TextDecoder` throws a `RangeError` for a label it does not know.
44
+ return undefined;
42
45
  }
43
- // Browser decoding only works with UTF-8.
44
- const utf8decoder = new TextDecoder();
45
- return utf8decoder.decode(new Uint8Array(buffer));
46
- }
47
- function isCharsetStringifiable(charset) {
48
- if (!charset)
49
- return true; // hope that it's utf-8
50
- if ((0, utils_1.isNode)())
51
- return Buffer.isEncoding(charset);
52
- const normalizedCharset = charset.toLowerCase().replace('-', '');
53
- // Browsers only support decoding utf-8 buffers.
54
- return normalizedCharset === 'utf8';
55
46
  }
56
47
  function isContentTypeStringifiable(contentType) {
57
48
  if (!contentType)
58
49
  return false; // keep buffer
59
50
  return STRINGIFIABLE_CONTENT_TYPE_RXS.some((rx) => rx.test(contentType));
60
51
  }
61
- function areDataStringifiable(contentType, charset) {
62
- return isContentTypeStringifiable(contentType) && isCharsetStringifiable(charset);
63
- }