apify-client 3.0.0-beta.12 → 3.0.0-beta.121

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 (128) hide show
  1. package/README.md +23 -2
  2. package/dist/apify_api_error.d.ts +14 -28
  3. package/dist/apify_api_error.js +33 -23
  4. package/dist/apify_client.d.ts +125 -10
  5. package/dist/apify_client.js +133 -48
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/axios.d.ts +2 -0
  9. package/dist/axios.js +1 -0
  10. package/dist/base/api_client.d.ts +7 -7
  11. package/dist/base/api_client.js +36 -36
  12. package/dist/base/resource_client.d.ts +13 -8
  13. package/dist/base/resource_client.js +60 -34
  14. package/dist/base/resource_collection_client.d.ts +12 -4
  15. package/dist/base/resource_collection_client.js +34 -11
  16. package/dist/body_parser.d.ts +4 -5
  17. package/dist/body_parser.js +19 -26
  18. package/dist/bundle.js +41 -35
  19. package/dist/bundle.js.map +1 -1
  20. package/dist/generated/api.d.ts +3266 -1103
  21. package/dist/generated/schemas.d.ts +2608 -1079
  22. package/dist/generated/schemas.js +600 -239
  23. package/dist/http_clients/axios.d.ts +80 -0
  24. package/dist/http_clients/axios.js +165 -0
  25. package/dist/http_clients/base.d.ts +402 -0
  26. package/dist/http_clients/base.js +680 -0
  27. package/dist/http_clients/fetch.d.ts +53 -0
  28. package/dist/http_clients/fetch.js +219 -0
  29. package/dist/http_clients/index.d.ts +4 -0
  30. package/dist/http_clients/index.js +2 -0
  31. package/dist/http_compressors/base.d.ts +40 -0
  32. package/dist/http_compressors/base.js +9 -0
  33. package/dist/http_compressors/brotli.d.ts +33 -0
  34. package/dist/http_compressors/brotli.js +39 -0
  35. package/dist/http_compressors/gzip.d.ts +33 -0
  36. package/dist/http_compressors/gzip.js +39 -0
  37. package/dist/http_compressors/index.d.ts +8 -0
  38. package/dist/http_compressors/index.js +3 -0
  39. package/dist/http_compressors/resolve.d.ts +24 -0
  40. package/dist/http_compressors/resolve.js +30 -0
  41. package/dist/http_compressors/zstd.d.ts +34 -0
  42. package/dist/http_compressors/zstd.js +43 -0
  43. package/dist/index.d.ts +7 -2
  44. package/dist/index.js +5 -1
  45. package/dist/invalid_response_body_error.d.ts +14 -0
  46. package/dist/invalid_response_body_error.js +18 -0
  47. package/dist/models.d.ts +177 -240
  48. package/dist/models.js +6 -4
  49. package/dist/resource_clients/actor.d.ts +94 -23
  50. package/dist/resource_clients/actor.js +129 -43
  51. package/dist/resource_clients/actor_collection.d.ts +15 -11
  52. package/dist/resource_clients/actor_collection.js +9 -3
  53. package/dist/resource_clients/actor_env_var.d.ts +11 -4
  54. package/dist/resource_clients/actor_env_var.js +16 -6
  55. package/dist/resource_clients/actor_env_var_collection.d.ts +9 -4
  56. package/dist/resource_clients/actor_env_var_collection.js +11 -4
  57. package/dist/resource_clients/actor_server.d.ts +149 -0
  58. package/dist/resource_clients/actor_server.js +195 -0
  59. package/dist/resource_clients/actor_version.d.ts +19 -6
  60. package/dist/resource_clients/actor_version.js +19 -8
  61. package/dist/resource_clients/actor_version_collection.d.ts +10 -4
  62. package/dist/resource_clients/actor_version_collection.js +12 -4
  63. package/dist/resource_clients/build.d.ts +18 -7
  64. package/dist/resource_clients/build.js +33 -15
  65. package/dist/resource_clients/build_collection.d.ts +7 -5
  66. package/dist/resource_clients/build_collection.js +4 -1
  67. package/dist/resource_clients/dataset.d.ts +83 -37
  68. package/dist/resource_clients/dataset.js +99 -109
  69. package/dist/resource_clients/dataset_collection.d.ts +10 -6
  70. package/dist/resource_clients/dataset_collection.js +13 -2
  71. package/dist/resource_clients/key_value_store.d.ts +108 -33
  72. package/dist/resource_clients/key_value_store.js +134 -53
  73. package/dist/resource_clients/key_value_store_collection.d.ts +10 -6
  74. package/dist/resource_clients/key_value_store_collection.js +13 -2
  75. package/dist/resource_clients/log.d.ts +41 -25
  76. package/dist/resource_clients/log.js +142 -65
  77. package/dist/resource_clients/request_queue.d.ts +77 -31
  78. package/dist/resource_clients/request_queue.js +178 -93
  79. package/dist/resource_clients/request_queue_collection.d.ts +9 -5
  80. package/dist/resource_clients/request_queue_collection.js +9 -3
  81. package/dist/resource_clients/run.d.ts +119 -29
  82. package/dist/resource_clients/run.js +188 -49
  83. package/dist/resource_clients/run_collection.d.ts +5 -3
  84. package/dist/resource_clients/run_collection.js +4 -1
  85. package/dist/resource_clients/schedule.d.ts +15 -6
  86. package/dist/resource_clients/schedule.js +25 -10
  87. package/dist/resource_clients/schedule_collection.d.ts +6 -2
  88. package/dist/resource_clients/schedule_collection.js +9 -3
  89. package/dist/resource_clients/store_collection.d.ts +10 -4
  90. package/dist/resource_clients/store_collection.js +4 -1
  91. package/dist/resource_clients/task.d.ts +35 -12
  92. package/dist/resource_clients/task.js +75 -35
  93. package/dist/resource_clients/task_collection.d.ts +9 -5
  94. package/dist/resource_clients/task_collection.js +9 -3
  95. package/dist/resource_clients/user.d.ts +16 -7
  96. package/dist/resource_clients/user.js +34 -16
  97. package/dist/resource_clients/webhook.d.ts +16 -7
  98. package/dist/resource_clients/webhook.js +25 -10
  99. package/dist/resource_clients/webhook_collection.d.ts +8 -4
  100. package/dist/resource_clients/webhook_collection.js +9 -3
  101. package/dist/resource_clients/webhook_dispatch.d.ts +4 -1
  102. package/dist/resource_clients/webhook_dispatch.js +7 -2
  103. package/dist/resource_clients/webhook_dispatch_collection.d.ts +3 -1
  104. package/dist/resource_clients/webhook_dispatch_collection.js +4 -1
  105. package/dist/response_validation_error.d.ts +2 -1
  106. package/dist/response_validation_error.js +2 -1
  107. package/dist/runtime/node.d.ts +6 -0
  108. package/dist/runtime/node.js +111 -0
  109. package/dist/runtime/types.d.ts +82 -0
  110. package/dist/runtime/types.js +1 -0
  111. package/dist/runtime/web.d.ts +5 -0
  112. package/dist/runtime/web.js +60 -0
  113. package/dist/schemas.d.ts +372 -4
  114. package/dist/schemas.js +26 -4
  115. package/dist/statistics.d.ts +1 -6
  116. package/dist/statistics.js +2 -2
  117. package/dist/timeouts.d.ts +84 -0
  118. package/dist/timeouts.js +37 -0
  119. package/dist/timezones.d.ts +1 -1
  120. package/dist/utils.d.ts +115 -61
  121. package/dist/utils.js +220 -161
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +53 -38
  125. package/dist/http_client.d.ts +0 -88
  126. package/dist/http_client.js +0 -255
  127. package/dist/interceptors.d.ts +0 -19
  128. package/dist/interceptors.js +0 -105
@@ -1,7 +1,21 @@
1
1
  import c from 'ansi-colors';
2
+ import { z } from 'zod';
2
3
  import log, { Logger, LogLevel } from '@apify/log';
3
4
  import { ResourceClient } from '../base/resource_client.js';
4
- import { cast, catchNotFoundForResourceOrThrow } from '../utils.js';
5
+ import { timeoutOptionsShape } from '../timeouts.js';
6
+ import { cast, catchNotFoundForResourceOrThrow, concatBytes, parseArgument, sleep } from '../utils.js';
7
+ /**
8
+ * Pause before the first reopen of a log stream that ended before the run logged anything. Each further reopen doubles
9
+ * the pause up to `EMPTY_LOG_STREAM_MAX_RETRY_MILLIS`, which bounds the request rate while a run waits long to start,
10
+ * for example for free memory.
11
+ */
12
+ const EMPTY_LOG_STREAM_RETRY_MILLIS = 500;
13
+ /** Upper bound on the pause between reopens of an empty log stream. */
14
+ const EMPTY_LOG_STREAM_MAX_RETRY_MILLIS = 5_000;
15
+ const logOptionsSchema = z.strictObject({ raw: z.boolean().optional(), ...timeoutOptionsShape });
16
+ const logGetOptionsSchema = logOptionsSchema.extend({ buffer: z.boolean().optional() });
17
+ /** How long `StreamedLog.stop()` waits for lines already in flight before aborting the log stream request. */
18
+ const STOP_GRACE_MILLIS = 1000;
5
19
  /**
6
20
  * Client for accessing Actor run or build logs.
7
21
  *
@@ -17,6 +31,9 @@ import { cast, catchNotFoundForResourceOrThrow } from '../utils.js';
17
31
  * const log = await runClient.log().get();
18
32
  * console.log(log);
19
33
  *
34
+ * // Get the log content as raw bytes
35
+ * const logBuffer = await runClient.log().get({ buffer: true });
36
+ *
20
37
  * // Stream the log in real-time
21
38
  * const stream = await runClient.log().stream();
22
39
  * stream.on('line', (line) => console.log(line));
@@ -34,21 +51,17 @@ export class LogClient extends ResourceClient {
34
51
  ...options,
35
52
  });
36
53
  }
37
- /**
38
- * Retrieves the log as a string.
39
- *
40
- * @param options - Log retrieval options.
41
- * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
42
- * @returns The log content as a string, or `undefined` if it does not exist. A chained client such as
43
- * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
44
- * @see https://docs.apify.com/api/v2/log-get
45
- */
46
54
  async get(options = {}) {
55
+ const { timeoutSecs = 'long', signal, buffer, ...params } = parseArgument(options, logGetOptionsSchema, 'LogGetOptions');
47
56
  const requestOpts = {
48
- url: this._url(),
57
+ url: this.buildUrl(),
49
58
  method: 'GET',
50
- params: this._params(options),
59
+ params: this.buildParams(params),
60
+ timeoutSecs,
61
+ signal,
51
62
  };
63
+ if (buffer)
64
+ requestOpts.responseType = 'buffer';
52
65
  try {
53
66
  const response = await this.httpClient.call(requestOpts);
54
67
  return cast(response.data);
@@ -59,24 +72,28 @@ export class LogClient extends ResourceClient {
59
72
  return undefined;
60
73
  }
61
74
  /**
62
- * Retrieves the log as a Readable stream. Only works in Node.js.
75
+ * Retrieves the log as a web ReadableStream of Uint8Array chunks.
63
76
  *
64
77
  * @param options - Log retrieval options.
65
78
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
66
- * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
79
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
80
+ * @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
67
81
  * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
68
82
  * @see https://docs.apify.com/api/v2/log-get
69
83
  */
70
84
  async stream(options = {}) {
85
+ const { timeoutSecs = 'long', signal, raw } = parseArgument(options, logOptionsSchema, 'LogOptions');
71
86
  const params = {
72
87
  stream: true,
73
- raw: options.raw,
88
+ raw,
74
89
  };
75
90
  const requestOpts = {
76
- url: this._url(),
91
+ url: this.buildUrl(),
77
92
  method: 'GET',
78
- params: this._params(params),
93
+ params: this.buildParams(params),
79
94
  responseType: 'stream',
95
+ timeoutSecs,
96
+ signal,
80
97
  };
81
98
  try {
82
99
  const response = await this.httpClient.call(requestOpts);
@@ -121,39 +138,50 @@ export class LoggerActorRedirect extends Logger {
121
138
  * @since Added in 2.20.0
122
139
  */
123
140
  export class StreamedLog {
124
- destinationLog;
125
- streamBuffer = [];
126
- splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
127
- relevancyTimeLimit;
128
- logClient;
129
- streamingTask = null;
130
- stopLogging = false;
141
+ #destinationLog;
142
+ #streamBuffer = [];
143
+ #decoder = new TextDecoder();
144
+ #splitMarker = /(?:\n|^)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)/g;
145
+ #relevancyTimeLimit;
146
+ #logClient;
147
+ #signal;
148
+ #streamingTask = null;
149
+ #stopLogging = false;
150
+ #stopController = new AbortController();
151
+ #wakeController = new AbortController();
131
152
  constructor(options) {
132
- const { toLog, logClient, fromStart = true } = options;
133
- this.destinationLog = toLog;
134
- this.logClient = logClient;
135
- this.relevancyTimeLimit = fromStart ? null : new Date();
153
+ const { toLog, logClient, fromStart = true, signal } = options;
154
+ this.#destinationLog = toLog;
155
+ this.#logClient = logClient;
156
+ this.#signal = signal;
157
+ this.#relevancyTimeLimit = fromStart ? null : new Date();
136
158
  }
137
159
  /**
138
160
  * Start log redirection.
139
161
  */
140
162
  start() {
141
- if (this.streamingTask) {
163
+ if (this.#streamingTask) {
142
164
  throw new Error('Streaming task already active');
143
165
  }
144
- this.stopLogging = false;
145
- this.streamingTask = this.streamLog();
166
+ this.#stopLogging = false;
167
+ this.#stopController = new AbortController();
168
+ this.#wakeController = new AbortController();
169
+ this.#streamingTask = this.#streamLog();
146
170
  }
147
171
  /**
148
- * Stop log redirection.
172
+ * Stop log redirection. Waits up to one second for lines already in flight, then aborts the log stream request. If
173
+ * no stream has delivered anything yet, reads the whole log in one request instead.
149
174
  */
150
175
  async stop() {
151
- if (!this.streamingTask) {
176
+ if (!this.#streamingTask) {
152
177
  throw new Error('Streaming task is not active');
153
178
  }
154
- this.stopLogging = true;
179
+ this.#stopLogging = true;
180
+ this.#wakeController.abort();
181
+ const stopController = this.#stopController;
182
+ const abortTimeout = setTimeout(() => stopController.abort(), STOP_GRACE_MILLIS);
155
183
  try {
156
- await this.streamingTask;
184
+ await this.#streamingTask;
157
185
  }
158
186
  catch (err) {
159
187
  if (!(err instanceof Error && err.name === 'AbortError')) {
@@ -161,73 +189,122 @@ export class StreamedLog {
161
189
  }
162
190
  }
163
191
  finally {
164
- this.streamingTask = null;
192
+ clearTimeout(abortTimeout);
193
+ this.#streamingTask = null;
165
194
  }
166
195
  }
167
196
  /**
168
197
  * Get log stream from response and redirect it to another log.
169
198
  */
170
- async streamLog() {
199
+ async #streamLog() {
200
+ const signal = this.#signal
201
+ ? AbortSignal.any([this.#signal, this.#stopController.signal])
202
+ : this.#stopController.signal;
171
203
  try {
172
- const logStream = await this.logClient.stream({ raw: true });
173
- if (!logStream) {
174
- return;
204
+ let lastChunkRemainder;
205
+ let retryMillis = EMPTY_LOG_STREAM_RETRY_MILLIS;
206
+ // The API serves the log of a run that has not logged anything yet as an empty stream that ends at once,
207
+ // so reopen it until the first bytes arrive. If stopped before any bytes arrive, fetch it in one request.
208
+ while (!lastChunkRemainder) {
209
+ if (this.#stopLogging) {
210
+ // `signal` is aborted once the stop grace period ends, which would cut this read short.
211
+ const logContent = await this.#logClient.get({ raw: true, signal: this.#signal });
212
+ lastChunkRemainder = await this.#logStreamChunks([new TextEncoder().encode(logContent ?? '')], signal);
213
+ break;
214
+ }
215
+ let logStream;
216
+ try {
217
+ logStream = await this.#logClient.stream({ raw: true, signal });
218
+ }
219
+ catch (err) {
220
+ // The stop grace period ended while the stream was connecting, so read the log in one request.
221
+ if (this.#stopLogging && !this.#signal?.aborted)
222
+ continue;
223
+ throw err;
224
+ }
225
+ if (!logStream) {
226
+ return;
227
+ }
228
+ // A stream opened during stop() would be cut after its first chunk, so read the log in one request.
229
+ if (this.#stopLogging) {
230
+ // Cancelling a stream that has already failed rejects with its error.
231
+ await logStream.cancel().catch(() => { });
232
+ continue;
233
+ }
234
+ lastChunkRemainder = await this.#logStreamChunks(logStream, signal);
235
+ if (!lastChunkRemainder) {
236
+ await sleep(retryMillis, AbortSignal.any([signal, this.#wakeController.signal]));
237
+ retryMillis = Math.min(retryMillis * 2, EMPTY_LOG_STREAM_MAX_RETRY_MILLIS);
238
+ }
175
239
  }
176
- const lastChunkRemainder = await this.logStreamChunks(logStream);
177
240
  // Process whatever is left when exiting. Maybe it is incomplete, maybe it is last log without EOL.
178
- const lastMessage = Buffer.from(lastChunkRemainder).toString().trim();
241
+ const lastMessage = this.#decoder.decode(lastChunkRemainder).trim();
179
242
  if (lastMessage.length) {
180
- this.destinationLog.info(lastMessage);
243
+ this.#destinationLog.info(lastMessage);
181
244
  }
182
245
  }
183
246
  catch (err) {
247
+ if (signal.aborted)
248
+ return;
184
249
  log.warning(`Log redirection stopped due to error`, err);
185
250
  }
186
251
  }
187
- async logStreamChunks(logStream) {
252
+ /**
253
+ * Redirect every complete message in the chunks and return the incomplete rest, or `undefined` when there were no
254
+ * chunks at all.
255
+ */
256
+ async #logStreamChunks(logStream, signal) {
188
257
  // Chunk may be incomplete. Keep remainder for next chunk.
189
- let previousChunkRemainder = new Uint8Array();
190
- for await (const chunk of logStream) {
191
- // Handle possible leftover incomplete line from previous chunk.
192
- // Everything before last end of line is complete.
193
- const chunkWithPreviousRemainder = new Uint8Array(previousChunkRemainder.length + chunk.length);
194
- chunkWithPreviousRemainder.set(previousChunkRemainder, 0);
195
- chunkWithPreviousRemainder.set(chunk, previousChunkRemainder.length);
196
- const lastCompleteMessageIndex = chunkWithPreviousRemainder.lastIndexOf(0x0a);
197
- previousChunkRemainder = chunkWithPreviousRemainder.slice(lastCompleteMessageIndex);
198
- // Push complete part of the chunk to the buffer
199
- this.streamBuffer.push(Buffer.from(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex)));
200
- this.logBufferContent();
201
- // Keep processing the new data until stopped
202
- if (this.stopLogging) {
203
- break;
258
+ let previousChunkRemainder;
259
+ try {
260
+ for await (const chunk of logStream) {
261
+ // Handle possible leftover incomplete line from previous chunk.
262
+ // Everything before last end of line is complete.
263
+ previousChunkRemainder ??= new Uint8Array();
264
+ const chunkWithPreviousRemainder = new Uint8Array(previousChunkRemainder.length + chunk.length);
265
+ chunkWithPreviousRemainder.set(previousChunkRemainder, 0);
266
+ chunkWithPreviousRemainder.set(chunk, previousChunkRemainder.length);
267
+ const lastCompleteMessageIndex = chunkWithPreviousRemainder.lastIndexOf(0x0a);
268
+ previousChunkRemainder = chunkWithPreviousRemainder.slice(lastCompleteMessageIndex);
269
+ // Push complete part of the chunk to the buffer
270
+ this.#streamBuffer.push(chunkWithPreviousRemainder.slice(0, lastCompleteMessageIndex));
271
+ this.#logBufferContent();
272
+ // Keep processing the new data until stopped
273
+ if (this.#stopLogging) {
274
+ break;
275
+ }
204
276
  }
205
277
  }
278
+ catch (err) {
279
+ // An aborted stream still hands back its unterminated last line, so the caller can flush it.
280
+ if (!signal.aborted)
281
+ throw err;
282
+ }
206
283
  return previousChunkRemainder;
207
284
  }
208
285
  /**
209
286
  * Parse the buffer and log complete messages.
210
287
  */
211
- logBufferContent() {
212
- const allParts = Buffer.concat(this.streamBuffer).toString().split(this.splitMarker).slice(1);
288
+ #logBufferContent() {
289
+ const allParts = this.#decoder.decode(concatBytes(this.#streamBuffer)).split(this.#splitMarker).slice(1);
213
290
  // Parse the buffer parts into complete messages
214
291
  const messageMarkers = allParts.filter((_, i) => i % 2 === 0);
215
292
  const messageContents = allParts.filter((_, i) => i % 2 !== 0);
216
- this.streamBuffer = [];
293
+ this.#streamBuffer = [];
217
294
  messageMarkers.forEach((marker, index) => {
218
295
  const decodedMarker = marker;
219
296
  const decodedContent = messageContents[index];
220
- if (this.relevancyTimeLimit) {
297
+ if (this.#relevancyTimeLimit) {
221
298
  // Log only relevant messages. Ignore too old log messages.
222
299
  const logTime = new Date(decodedMarker);
223
- if (logTime < this.relevancyTimeLimit) {
300
+ if (logTime < this.#relevancyTimeLimit) {
224
301
  return;
225
302
  }
226
303
  }
227
304
  const message = decodedMarker + decodedContent;
228
305
  // Original log level information is not available. Log all on info level. Log level could be guessed for
229
306
  // some logs, but for any multiline logs such guess would be probably correct only for the first line.
230
- this.destinationLog.info(message.trim());
307
+ this.#destinationLog.info(message.trim());
231
308
  });
232
309
  }
233
310
  }