@crawlee/core 4.0.0-beta.99 → 4.0.0-rc.1

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 (133) hide show
  1. package/README.md +1 -1
  2. package/configuration.d.ts +16 -47
  3. package/configuration.js +13 -25
  4. package/debug.js +4 -4
  5. package/errors.d.ts +28 -38
  6. package/errors.js +33 -47
  7. package/events/event_manager.d.ts +2 -2
  8. package/events/event_manager.js +7 -6
  9. package/events/index.d.ts +1 -0
  10. package/events/local_event_manager.d.ts +1 -8
  11. package/events/local_event_manager.js +13 -13
  12. package/events/system_info.d.ts +38 -0
  13. package/index.d.ts +2 -8
  14. package/index.js +4 -8
  15. package/internal.d.ts +8 -0
  16. package/internal.js +9 -0
  17. package/log.d.ts +10 -11
  18. package/log.js +52 -20
  19. package/memory-storage/memory-storage.d.ts +15 -18
  20. package/memory-storage/memory-storage.js +80 -58
  21. package/memory-storage/resource-clients/dataset.d.ts +1 -6
  22. package/memory-storage/resource-clients/dataset.js +23 -31
  23. package/memory-storage/resource-clients/key-value-store.d.ts +1 -10
  24. package/memory-storage/resource-clients/key-value-store.js +43 -67
  25. package/memory-storage/resource-clients/request-queue.d.ts +1 -42
  26. package/memory-storage/resource-clients/request-queue.js +109 -117
  27. package/owned_or_injected.d.ts +1 -3
  28. package/owned_or_injected.js +17 -17
  29. package/package.json +17 -20
  30. package/proxy_configuration.d.ts +21 -26
  31. package/proxy_configuration.js +35 -25
  32. package/recoverable_state.d.ts +104 -47
  33. package/recoverable_state.js +199 -74
  34. package/request.d.ts +20 -107
  35. package/request.js +78 -244
  36. package/serialization.js +17 -16
  37. package/service_locator.d.ts +22 -10
  38. package/service_locator.js +59 -48
  39. package/storages/batched_adds.d.ts +37 -0
  40. package/storages/batched_adds.js +73 -0
  41. package/storages/dataset.d.ts +13 -8
  42. package/storages/dataset.js +149 -40
  43. package/storages/index.d.ts +4 -4
  44. package/storages/index.js +2 -4
  45. package/storages/key_value_store.d.ts +16 -35
  46. package/storages/key_value_store.js +223 -110
  47. package/storages/key_value_store_codec.js +6 -11
  48. package/storages/request_dedup_cache.d.ts +1 -4
  49. package/storages/request_dedup_cache.js +15 -15
  50. package/storages/request_list.d.ts +9 -104
  51. package/storages/request_list.js +236 -233
  52. package/storages/request_loader.d.ts +49 -18
  53. package/storages/request_loader.js +36 -1
  54. package/storages/request_manager.d.ts +86 -0
  55. package/storages/request_manager_tandem.d.ts +14 -38
  56. package/storages/request_manager_tandem.js +67 -64
  57. package/storages/request_queue.d.ts +23 -50
  58. package/storages/request_queue.js +371 -226
  59. package/storages/storage_instance_manager.d.ts +2 -4
  60. package/storages/storage_instance_manager.js +21 -21
  61. package/storages/storage_stats.d.ts +1 -1
  62. package/storages/storage_stats.js +4 -4
  63. package/storages/transaction.d.ts +270 -0
  64. package/storages/transaction.js +296 -0
  65. package/storages/utils.d.ts +6 -3
  66. package/storages/utils.js +11 -2
  67. package/system-info/runtime.js +7 -7
  68. package/url.d.ts +9 -0
  69. package/url.js +11 -0
  70. package/validators.d.ts +23 -25
  71. package/validators.js +14 -25
  72. package/autoscaling/autoscaled_pool.d.ts +0 -213
  73. package/autoscaling/autoscaled_pool.js +0 -378
  74. package/autoscaling/client_load_signal.d.ts +0 -59
  75. package/autoscaling/client_load_signal.js +0 -73
  76. package/autoscaling/concurrency_system.d.ts +0 -283
  77. package/autoscaling/concurrency_system.js +0 -350
  78. package/autoscaling/cpu_load_signal.d.ts +0 -44
  79. package/autoscaling/cpu_load_signal.js +0 -46
  80. package/autoscaling/event_loop_load_signal.d.ts +0 -54
  81. package/autoscaling/event_loop_load_signal.js +0 -60
  82. package/autoscaling/index.d.ts +0 -9
  83. package/autoscaling/index.js +0 -9
  84. package/autoscaling/load_signal.d.ts +0 -99
  85. package/autoscaling/load_signal.js +0 -103
  86. package/autoscaling/memory_load_signal.d.ts +0 -56
  87. package/autoscaling/memory_load_signal.js +0 -106
  88. package/autoscaling/snapshotter.d.ts +0 -87
  89. package/autoscaling/snapshotter.js +0 -67
  90. package/autoscaling/system_status.d.ts +0 -161
  91. package/autoscaling/system_status.js +0 -139
  92. package/autoscaling/weighted_avg.d.ts +0 -5
  93. package/autoscaling/weighted_avg.js +0 -14
  94. package/cookie_utils.d.ts +0 -44
  95. package/cookie_utils.js +0 -122
  96. package/crawlers/context_pipeline.d.ts +0 -70
  97. package/crawlers/context_pipeline.js +0 -122
  98. package/crawlers/crawler_commons.d.ts +0 -257
  99. package/crawlers/crawler_commons.js +0 -107
  100. package/crawlers/error_snapshotter.d.ts +0 -59
  101. package/crawlers/error_snapshotter.js +0 -117
  102. package/crawlers/error_tracker.d.ts +0 -54
  103. package/crawlers/error_tracker.js +0 -308
  104. package/crawlers/index.d.ts +0 -5
  105. package/crawlers/index.js +0 -5
  106. package/crawlers/internals/types.d.ts +0 -7
  107. package/crawlers/statistics.d.ts +0 -209
  108. package/crawlers/statistics.js +0 -350
  109. package/enqueue_links/enqueue_links.d.ts +0 -264
  110. package/enqueue_links/enqueue_links.js +0 -271
  111. package/enqueue_links/index.d.ts +0 -2
  112. package/enqueue_links/index.js +0 -2
  113. package/enqueue_links/shared.d.ts +0 -83
  114. package/enqueue_links/shared.js +0 -221
  115. package/router.d.ts +0 -309
  116. package/router.js +0 -309
  117. package/session_pool/consts.d.ts +0 -3
  118. package/session_pool/consts.js +0 -3
  119. package/session_pool/errors.d.ts +0 -7
  120. package/session_pool/errors.js +0 -11
  121. package/session_pool/fingerprint.d.ts +0 -9
  122. package/session_pool/fingerprint.js +0 -30
  123. package/session_pool/index.d.ts +0 -4
  124. package/session_pool/index.js +0 -4
  125. package/session_pool/session.d.ts +0 -161
  126. package/session_pool/session.js +0 -218
  127. package/session_pool/session_pool.d.ts +0 -246
  128. package/session_pool/session_pool.js +0 -386
  129. package/storages/access_checking.d.ts +0 -12
  130. package/storages/access_checking.js +0 -17
  131. package/storages/sitemap_request_loader.d.ts +0 -249
  132. package/storages/sitemap_request_loader.js +0 -432
  133. /package/{crawlers/internals/types.js → events/system_info.js} +0 -0
@@ -1,4 +1,29 @@
1
- import { KeyValueStore, serviceLocator } from '@crawlee/core';
1
+ import { Readable } from 'node:stream';
2
+ import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';
3
+ import { StateValidationError } from './errors.js';
4
+ import { EventType } from './events/event_manager.js';
5
+ import { serviceLocator } from './service_locator.js';
6
+ import { KeyValueStore } from './storages/key_value_store.js';
7
+ const DEFAULT_PERSISTENCE_TIMEOUT_MILLIS = 60_000;
8
+ /**
9
+ * Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
10
+ * the value.
11
+ *
12
+ * @internal
13
+ */
14
+ export function convertStateSync(conversion, value, persistStateKey) {
15
+ if (typeof conversion === 'function') {
16
+ return conversion(value);
17
+ }
18
+ const result = conversion['~standard'].validate(value);
19
+ if ('then' in result) {
20
+ throw new Error(`The state conversion for '${persistStateKey}' validated asynchronously, which this caller cannot await.`);
21
+ }
22
+ if (result.issues) {
23
+ throw new StateValidationError(persistStateKey, result.issues);
24
+ }
25
+ return result.value;
26
+ }
2
27
  /**
3
28
  * A class for managing persistent recoverable state using a plain JavaScript object.
4
29
  *
@@ -10,134 +35,234 @@ import { KeyValueStore, serviceLocator } from '@crawlee/core';
10
35
  * The class automatically hooks into the event system to persist state when needed.
11
36
  */
12
37
  export class RecoverableState {
13
- defaultState;
14
- state = null;
15
- persistenceEnabled;
16
- persistStateKey;
17
- persistStateKvsName;
18
- persistStateKvsId;
19
- keyValueStore = null;
20
- log;
21
- serialize;
22
- deserialize;
38
+ #defaultState;
39
+ #state = null;
40
+ #initialized = false;
41
+ #recordLoaded = false;
42
+ #listening = false;
43
+ #persistenceEnabled;
44
+ #persistStateKey;
45
+ #persistenceTimeoutMillis;
46
+ #configuration;
47
+ #keyValueStore;
48
+ #log;
49
+ #serialize;
50
+ #deserialize;
51
+ #contentType;
52
+ #persistStateQuietly;
23
53
  /**
24
54
  * Initialize a new recoverable state object.
25
55
  *
26
56
  * @param options Configuration options for the recoverable state
27
57
  */
28
58
  constructor(options) {
29
- this.defaultState = options.defaultState;
30
- this.persistStateKey = options.persistStateKey;
31
- this.persistenceEnabled = options.persistenceEnabled ?? false;
32
- this.persistStateKvsName = options.persistStateKvsName;
33
- this.persistStateKvsId = options.persistStateKvsId;
34
- this.log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
35
- this.serialize = options.serialize ?? JSON.stringify;
36
- this.deserialize = options.deserialize ?? JSON.parse;
37
- this.persistState = this.persistState.bind(this);
59
+ const { defaultState } = options;
60
+ this.#defaultState =
61
+ typeof defaultState === 'function'
62
+ ? defaultState
63
+ : () => structuredClone(defaultState);
64
+ this.#persistStateKey = options.persistStateKey;
65
+ this.#persistenceEnabled = options.persistenceEnabled ?? false;
66
+ this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
67
+ this.#configuration = options.configuration;
68
+ this.#keyValueStore = options.keyValueStore ?? null;
69
+ this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
70
+ this.#contentType = options.contentType;
71
+ if (this.#contentType !== undefined && (options.serialize === undefined || options.deserialize === undefined)) {
72
+ throw new Error(`A 'contentType' for the state persisted under key '${this.#persistStateKey}' requires both 'serialize' and 'deserialize' - the record is no longer JSON the default codec can handle.`);
73
+ }
74
+ this.#serialize = this.#toConversion(options.serialize);
75
+ this.#deserialize = this.#toConversion(options.deserialize);
76
+ // A pending open() may reject before anything here awaits it. Observe the rejection so it surfaces on
77
+ // first use rather than as an unhandled rejection - most immediately when persistence is disabled and
78
+ // nothing ever awaits the store.
79
+ if (this.#keyValueStore !== null) {
80
+ Promise.resolve(this.#keyValueStore).then(undefined, () => { });
81
+ }
82
+ // The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
83
+ // listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
84
+ this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
85
+ }
86
+ /** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
87
+ #toConversion(conversion) {
88
+ if (conversion === undefined) {
89
+ return async (value) => value;
90
+ }
91
+ if (typeof conversion === 'function') {
92
+ return async (value) => conversion(value);
93
+ }
94
+ return async (value) => {
95
+ const result = await conversion['~standard'].validate(value);
96
+ if (result.issues) {
97
+ throw new StateValidationError(this.#persistStateKey, result.issues);
98
+ }
99
+ return result.value;
100
+ };
38
101
  }
39
102
  /**
40
103
  * Initialize the recoverable state.
41
104
  *
42
- * This method must be called before using the recoverable state. It loads the saved state
43
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
105
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
106
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
107
+ * is no record to restore.
108
+ *
109
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
110
+ * listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
111
+ * reloading it would only drop whatever the deserialization leaves out.
44
112
  *
45
113
  * @returns The loaded state object
46
114
  */
47
115
  async initialize() {
48
- if (this.state !== null && this.state !== undefined) {
49
- return this.currentValue;
50
- }
51
- if (!this.persistenceEnabled) {
52
- this.state = this.deserialize(this.serialize(this.defaultState));
116
+ if (this.#initialized) {
53
117
  return this.currentValue;
54
118
  }
55
- let kvsIdentifier = null;
56
- if (this.persistStateKvsName) {
57
- kvsIdentifier = { name: this.persistStateKvsName };
119
+ if (this.#persistenceEnabled) {
120
+ await this.#openKeyValueStore();
121
+ serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
122
+ this.#listening = true;
58
123
  }
59
- else if (this.persistStateKvsId) {
60
- kvsIdentifier = { id: this.persistStateKvsId };
124
+ // Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
125
+ // fully wired object running on the default state rather than a half-initialized one.
126
+ this.#initialized = true;
127
+ this.#state ??= this.#defaultState();
128
+ if (!this.#recordLoaded) {
129
+ this.#recordLoaded = true;
130
+ await this.#loadSavedState();
61
131
  }
62
- this.keyValueStore = await KeyValueStore.open(kvsIdentifier, {
63
- configuration: serviceLocator.getConfiguration(),
64
- });
65
- await this.loadSavedState();
66
- // Register for persist state events
67
- const eventManager = serviceLocator.getEventManager();
68
- eventManager.on("persistState" /* EventType.PERSIST_STATE */, this.persistState);
69
132
  return this.currentValue;
70
133
  }
71
134
  /**
72
135
  * Clean up resources used by the recoverable state.
73
136
  *
74
137
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
75
- * and persists the current state one last time.
138
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
139
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
140
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
141
+ * persistence window.
76
142
  */
77
143
  async teardown() {
78
- if (!this.persistenceEnabled || !this.persistState) {
144
+ this.#initialized = false;
145
+ if (!this.#persistenceEnabled) {
79
146
  return;
80
147
  }
81
- const eventManager = serviceLocator.getEventManager();
82
- eventManager.off("persistState" /* EventType.PERSIST_STATE */, this.persistState);
83
- await this.persistState();
148
+ serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
149
+ this.#listening = false;
150
+ await this.#persistStateQuietly();
84
151
  }
85
152
  /**
86
153
  * Get the current state.
154
+ *
155
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
156
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
157
+ * constructor gets a usable state right away.
87
158
  */
88
159
  get currentValue() {
89
- if (this.state === null) {
90
- throw new Error('Recoverable state has not yet been loaded');
160
+ if (this.#state === null) {
161
+ throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
91
162
  }
92
- return this.state;
163
+ return this.#state;
93
164
  }
94
165
  /**
95
- * Reset the state to the default values and clear any persisted state.
166
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
96
167
  *
97
- * Resets the current state to the default state and, if persistence is enabled,
98
- * clears the persisted state from the KeyValueStore.
168
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
99
169
  */
100
- async reset() {
101
- this.state = this.deserialize(this.serialize(this.defaultState));
102
- if (this.persistenceEnabled) {
103
- if (this.keyValueStore === null) {
104
- throw new Error('Recoverable state has not yet been initialized');
105
- }
106
- await this.keyValueStore.setValue(this.persistStateKey, null);
170
+ reset() {
171
+ this.#state = this.#defaultState();
172
+ }
173
+ /**
174
+ * Clear the persisted state record, leaving the in-memory state alone.
175
+ *
176
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
177
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
178
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
179
+ * or {@link RecoverableState.teardown} before clearing the record.
180
+ *
181
+ * A no-op if persistence is disabled.
182
+ */
183
+ async resetStore() {
184
+ if (this.#listening) {
185
+ throw new Error(`Cannot clear the state persisted under key '${this.#persistStateKey}' while it is still being persisted periodically - the next PERSIST_STATE event would write it straight back. Use reset() to reset the state itself, or teardown() before clearing the record.`);
186
+ }
187
+ if (!this.#persistenceEnabled) {
188
+ return;
107
189
  }
190
+ const keyValueStore = await this.#openKeyValueStore();
191
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
108
192
  }
109
193
  /**
110
194
  * Persist the current state to the KeyValueStore.
111
195
  *
112
196
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
113
- * directly when needed.
197
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
198
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
114
199
  *
115
200
  * @param eventData Optional data associated with a PERSIST_STATE event
116
201
  */
117
202
  async persistState(eventData) {
118
- this.log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
119
- if (this.keyValueStore === null || this.state === null) {
120
- throw new Error('Recoverable state has not yet been initialized');
203
+ if (!this.#persistenceEnabled || this.#state === null) {
204
+ return;
121
205
  }
122
- if (this.persistenceEnabled) {
123
- await this.keyValueStore.setValue(this.persistStateKey, this.serialize(this.state), {
124
- contentType: 'text/plain', // HACK - the result is expected to be JSON, but we do this to avoid the implicit JSON.parse in `KeyValueStore.getValue`
125
- });
206
+ const keyValueStore = await this.#resolveKeyValueStore();
207
+ if (keyValueStore === null) {
208
+ return;
209
+ }
210
+ this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
211
+ const serializedState = await this.#serialize(this.currentValue);
212
+ await this.#withTimeout(async () => this.#contentType === undefined
213
+ ? keyValueStore.setValue(this.#persistStateKey, serializedState)
214
+ : keyValueStore.setValue(this.#persistStateKey, serializedState, {
215
+ contentType: this.#contentType,
216
+ }), 'Persisting the state');
217
+ }
218
+ /** Falls back to the default store when none was supplied - persistence has to write somewhere. */
219
+ async #openKeyValueStore() {
220
+ this.#keyValueStore ??= KeyValueStore.open(null, {
221
+ configuration: this.#configuration ?? serviceLocator.getConfiguration(),
222
+ });
223
+ return (await this.#resolveKeyValueStore());
224
+ }
225
+ /** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
226
+ async #resolveKeyValueStore() {
227
+ if (this.#keyValueStore === null) {
228
+ return null;
126
229
  }
230
+ this.#keyValueStore = await this.#keyValueStore;
231
+ return this.#keyValueStore;
127
232
  }
128
233
  /**
129
- * Load the saved state from the KeyValueStore
234
+ * Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
130
235
  */
131
- async loadSavedState() {
132
- if (this.keyValueStore === null) {
133
- throw new Error('Recoverable state has not yet been initialized');
236
+ async #loadSavedState() {
237
+ if (!this.#persistenceEnabled) {
238
+ return;
134
239
  }
135
- const storedState = await this.keyValueStore.getValue(this.persistStateKey);
136
- if (storedState === null || storedState === undefined) {
137
- this.state = this.deserialize(this.serialize(this.defaultState));
240
+ const keyValueStore = await this.#resolveKeyValueStore();
241
+ if (keyValueStore === null) {
242
+ return;
138
243
  }
139
- else {
140
- this.state = this.deserialize(storedState);
244
+ // With a content type, the record is whatever `serialize` produced, so the codec's parse is skipped and
245
+ // `deserialize` gets the bytes as a stream - the shape a streaming parser wants.
246
+ // TODO: read the record as a stream instead of buffering it and wrapping (https://github.com/apify/crawlee/issues/2929).
247
+ const storedState = await this.#withTimeout(async () => {
248
+ if (this.#contentType === undefined) {
249
+ return keyValueStore.getValue(this.#persistStateKey);
250
+ }
251
+ const record = await keyValueStore.getRecord(this.#persistStateKey);
252
+ if (record === null) {
253
+ return null;
254
+ }
255
+ return Readable.from(Buffer.isBuffer(record.value) ? record.value : Buffer.from(record.value));
256
+ }, 'Loading the persisted state');
257
+ if (storedState === null || storedState === undefined) {
258
+ return;
141
259
  }
260
+ this.#state = await this.#deserialize(storedState);
261
+ }
262
+ async #withTimeout(operation, description) {
263
+ // `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
264
+ // every operation, so a teardown-time persist running inside an already-expired request handler timeout
265
+ // would be aborted before it started. Hence a fresh timeout context.
266
+ return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
142
267
  }
143
268
  }
package/request.d.ts CHANGED
@@ -1,20 +1,12 @@
1
1
  import type { BinaryLike } from 'node:crypto';
2
- import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
3
- import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
4
- import type { SkippedRequestReason } from './enqueue_links/shared.js';
5
- export declare enum RequestState {
6
- UNPROCESSED = 0,
7
- BEFORE_NAV = 1,
8
- AFTER_NAV = 2,
9
- REQUEST_HANDLER = 3,
10
- DONE = 4,
11
- ERROR_HANDLER = 5,
12
- ERROR = 6,
13
- SKIPPED = 7
14
- }
2
+ import type { AllowedHttpMethods, Dictionary, RequestSchema } from '@crawlee/types';
3
+ import type { EnqueueStrategy } from '@crawlee/utils';
4
+ /** The `strategy` option accepted by {@link ExtractLinksOptions} and {@link EnqueueUrlsOptions}. */
5
+ export type EnqueueStrategyOption = EnqueueStrategy | 'all' | 'same-domain' | 'same-hostname' | 'same-origin';
15
6
  /**
16
- * Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.
17
- * The `Request` object also stores information about errors that occurred during processing of the request.
7
+ * Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata, together
8
+ * with the processing state a request queue keeps about it (`retryCount`, `errorMessages`, `handledAt`, ...).
9
+ * Inside a crawler, requests are {@link CrawlingRequest}s, which add the crawler's own per-request settings.
18
10
  *
19
11
  * Each `Request` instance has the `uniqueKey` property, which can be either specified
20
12
  * manually in the constructor or generated automatically from the URL. Two requests with the same `uniqueKey`
@@ -30,21 +22,16 @@ export declare enum RequestState {
30
22
  * const request = new Request({
31
23
  * url: 'http://www.example.com',
32
24
  * headers: { Accept: 'application/json' },
25
+ * userData: { foo: 'bar' },
33
26
  * });
34
27
  *
35
- * ...
36
- *
37
- * request.userData.foo = 'bar';
38
- * request.pushErrorMessage(new Error('Request failed!'));
39
- *
40
- * ...
41
- *
42
- * const foo = request.userData.foo;
28
+ * await requestQueue.addRequest(request);
43
29
  * ```
44
30
  * @category Sources
45
31
  */
46
32
  declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
47
- /** Request ID */
33
+ #private;
34
+ /** Storage-assigned request ID. Only present on requests that went through a {@link RequestQueue}. */
48
35
  id?: string;
49
36
  /** URL of the web page to crawl. */
50
37
  url: string;
@@ -74,8 +61,6 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
74
61
  errorMessages: string[];
75
62
  /** Object with HTTP headers. Key is header name, value is the value. */
76
63
  headers?: Record<string, string>;
77
- /** Private store for the custom user data assigned to the request. */
78
- private _userData;
79
64
  /**
80
65
  * Custom user data assigned to the request.
81
66
  *
@@ -90,78 +75,25 @@ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
90
75
  handledAt?: string;
91
76
  /**
92
77
  * `Request` parameters including the URL, HTTP method and headers, and others.
78
+ *
79
+ * Processing state (`retryCount`, `errorMessages`, `handledAt`, `loadedUrl`, `id`) is not an option;
80
+ * requests coming back from a storage are rebuilt with {@link Request.fromSchema}.
93
81
  */
94
82
  constructor(options: RequestOptions<UserData>);
83
+ /**
84
+ * Rebuilds a request from its stored form, including the processing state a
85
+ * {@link RequestOptions} object cannot carry. Subclasses get instances of themselves.
86
+ */
87
+ static fromSchema<UserData extends Dictionary = Dictionary>(schema: RequestSchema): CrawleeRequest<UserData>;
95
88
  /**
96
89
  * Converts the Crawlee Request object to a `fetch` API Request object.
97
90
  * @returns The native `fetch` API Request object.
98
91
  */
99
92
  intoFetchAPIRequest(): Request;
100
- /**
101
- * Tells the crawler processing this request to skip the navigation and process the request directly.
102
- *
103
- * When this is set to `true`, the crawling context will not contain the results of the navigation
104
- * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
105
- * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
106
- */
107
- get skipNavigation(): boolean;
108
- /**
109
- * Tells the crawler processing this request to skip the navigation and process the request directly.
110
- *
111
- * When this is set to `true`, the crawling context will not contain the results of the navigation
112
- * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
113
- * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
114
- */
115
- set skipNavigation(value: boolean);
116
- /**
117
- * Depth of the request in the current crawl tree.
118
- * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
119
- */
120
- get crawlDepth(): number;
121
- /**
122
- * Depth of the request in the current crawl tree.
123
- * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
124
- */
125
- set crawlDepth(value: number);
126
- /** ID of a session to use for this request. When set, the crawler will fetch this session from the session pool instead of creating a new one. */
127
- get sessionId(): string | undefined;
128
- set sessionId(value: string | undefined);
129
93
  /** shortcut for getting `request.userData.label` */
130
94
  get label(): string | undefined;
131
95
  /** shortcut for setting `request.userData.label` */
132
96
  set label(value: string | undefined);
133
- /** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
134
- get maxRetries(): number | undefined;
135
- /** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
136
- set maxRetries(value: number | undefined);
137
- /** Describes the request's current lifecycle state. */
138
- get state(): RequestState;
139
- /** Describes the request's current lifecycle state. */
140
- set state(value: RequestState);
141
- /**
142
- * Reason for skipping this request.
143
- */
144
- get skippedReason(): SkippedRequestReason | undefined;
145
- /**
146
- * Reason for skipping this request.
147
- */
148
- set skippedReason(value: SkippedRequestReason | undefined);
149
- private get enqueueStrategy();
150
- private set enqueueStrategy(value);
151
- /**
152
- * Stores information about an error that occurred during processing of this request.
153
- *
154
- * You should always use Error instances when throwing errors in JavaScript.
155
- *
156
- * Nevertheless, to improve the debugging experience when using third party libraries
157
- * that may not always throw an Error instance, the function performs a type
158
- * inspection of the passed argument and attempts to extract as much information
159
- * as possible, since just throwing a bad type error makes any debugging rather difficult.
160
- *
161
- * @param errorOrMessage Error object or error message to be stored in the request.
162
- * @param [options]
163
- */
164
- pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
165
97
  /** @internal */
166
98
  static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
167
99
  /** @internal */
@@ -265,31 +197,12 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
265
197
  * @default 0
266
198
  */
267
199
  crawlDepth?: number;
268
- /**
269
- * Reason for skipping this request.
270
- * This is used to provide more information about why the request was skipped.
271
- * @internal
272
- */
273
- skippedReason?: SkippedRequestReason;
274
200
  /**
275
201
  * Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`.
276
202
  */
277
203
  maxRetries?: number;
278
204
  /** @internal */
279
- id?: string;
280
- /** @internal */
281
- handledAt?: string;
282
- /** @internal */
283
- lockExpiresAt?: Date;
284
- /** @internal */
285
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
286
- }
287
- export interface PushErrorMessageOptions {
288
- /**
289
- * Only push the error message without stack trace when true.
290
- * @default false
291
- */
292
- omitStack?: boolean;
205
+ enqueueStrategy?: EnqueueStrategyOption;
293
206
  }
294
207
  interface ComputeUniqueKeyOptions {
295
208
  url: string;