@crawlee/core 4.0.0-rc.0 → 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 (122) hide show
  1. package/README.md +1 -1
  2. package/configuration.d.ts +15 -46
  3. package/configuration.js +8 -20
  4. package/errors.d.ts +12 -53
  5. package/errors.js +13 -66
  6. package/events/index.d.ts +1 -0
  7. package/events/local_event_manager.d.ts +0 -7
  8. package/events/local_event_manager.js +8 -8
  9. package/events/system_info.d.ts +38 -0
  10. package/index.d.ts +2 -8
  11. package/index.js +4 -8
  12. package/internal.d.ts +8 -0
  13. package/internal.js +9 -0
  14. package/log.d.ts +10 -11
  15. package/log.js +53 -25
  16. package/memory-storage/memory-storage.d.ts +12 -7
  17. package/memory-storage/memory-storage.js +45 -17
  18. package/memory-storage/resource-clients/dataset.d.ts +0 -5
  19. package/memory-storage/resource-clients/dataset.js +17 -20
  20. package/memory-storage/resource-clients/key-value-store.d.ts +0 -9
  21. package/memory-storage/resource-clients/key-value-store.js +11 -33
  22. package/memory-storage/resource-clients/request-queue.d.ts +0 -22
  23. package/memory-storage/resource-clients/request-queue.js +57 -53
  24. package/package.json +16 -18
  25. package/proxy_configuration.d.ts +20 -23
  26. package/proxy_configuration.js +18 -12
  27. package/recoverable_state.d.ts +28 -6
  28. package/recoverable_state.js +51 -14
  29. package/request.d.ts +18 -104
  30. package/request.js +41 -220
  31. package/serialization.js +3 -3
  32. package/service_locator.d.ts +3 -0
  33. package/service_locator.js +2 -0
  34. package/storages/dataset.d.ts +9 -15
  35. package/storages/dataset.js +22 -14
  36. package/storages/index.d.ts +3 -4
  37. package/storages/index.js +1 -4
  38. package/storages/key_value_store.d.ts +12 -46
  39. package/storages/key_value_store.js +31 -47
  40. package/storages/key_value_store_codec.js +6 -11
  41. package/storages/request_dedup_cache.d.ts +0 -2
  42. package/storages/request_dedup_cache.js +8 -8
  43. package/storages/request_list.d.ts +6 -82
  44. package/storages/request_list.js +175 -179
  45. package/storages/request_loader.d.ts +48 -22
  46. package/storages/request_loader.js +36 -1
  47. package/storages/request_manager.d.ts +86 -0
  48. package/storages/request_manager_tandem.d.ts +13 -28
  49. package/storages/request_manager_tandem.js +46 -43
  50. package/storages/request_queue.d.ts +19 -49
  51. package/storages/request_queue.js +92 -88
  52. package/storages/storage_instance_manager.d.ts +1 -2
  53. package/storages/storage_instance_manager.js +4 -4
  54. package/storages/transaction.d.ts +27 -9
  55. package/storages/transaction.js +56 -11
  56. package/storages/utils.d.ts +2 -2
  57. package/validators.d.ts +3 -2
  58. package/validators.js +3 -2
  59. package/autoscaling/autoscaled_pool.d.ts +0 -195
  60. package/autoscaling/autoscaled_pool.js +0 -386
  61. package/autoscaling/concurrency_system.d.ts +0 -268
  62. package/autoscaling/concurrency_system.js +0 -362
  63. package/autoscaling/cpu_load_signal.d.ts +0 -43
  64. package/autoscaling/cpu_load_signal.js +0 -47
  65. package/autoscaling/event_loop_load_signal.d.ts +0 -51
  66. package/autoscaling/event_loop_load_signal.js +0 -60
  67. package/autoscaling/index.d.ts +0 -9
  68. package/autoscaling/index.js +0 -9
  69. package/autoscaling/load_signal.d.ts +0 -100
  70. package/autoscaling/load_signal.js +0 -105
  71. package/autoscaling/memory_load_signal.d.ts +0 -47
  72. package/autoscaling/memory_load_signal.js +0 -106
  73. package/autoscaling/snapshotter.d.ts +0 -84
  74. package/autoscaling/snapshotter.js +0 -67
  75. package/autoscaling/storage_backend_load_signal.d.ts +0 -56
  76. package/autoscaling/storage_backend_load_signal.js +0 -73
  77. package/autoscaling/system_status.d.ts +0 -159
  78. package/autoscaling/system_status.js +0 -139
  79. package/autoscaling/weighted_avg.d.ts +0 -5
  80. package/autoscaling/weighted_avg.js +0 -14
  81. package/cookie_utils.d.ts +0 -44
  82. package/cookie_utils.js +0 -122
  83. package/crawlers/context_pipeline.d.ts +0 -70
  84. package/crawlers/context_pipeline.js +0 -122
  85. package/crawlers/crawler_commons.d.ts +0 -159
  86. package/crawlers/error_snapshotter.d.ts +0 -57
  87. package/crawlers/error_snapshotter.js +0 -117
  88. package/crawlers/error_tracker.d.ts +0 -54
  89. package/crawlers/error_tracker.js +0 -308
  90. package/crawlers/index.d.ts +0 -5
  91. package/crawlers/index.js +0 -4
  92. package/crawlers/internals/types.d.ts +0 -7
  93. package/crawlers/internals/types.js +0 -1
  94. package/crawlers/statistics.d.ts +0 -328
  95. package/crawlers/statistics.js +0 -536
  96. package/enqueue_links/enqueue_links.d.ts +0 -156
  97. package/enqueue_links/enqueue_links.js +0 -78
  98. package/enqueue_links/index.d.ts +0 -2
  99. package/enqueue_links/index.js +0 -2
  100. package/enqueue_links/shared.d.ts +0 -93
  101. package/enqueue_links/shared.js +0 -239
  102. package/http.d.ts +0 -9
  103. package/http.js +0 -28
  104. package/router.d.ts +0 -306
  105. package/router.js +0 -309
  106. package/session_pool/consts.d.ts +0 -3
  107. package/session_pool/consts.js +0 -3
  108. package/session_pool/errors.d.ts +0 -7
  109. package/session_pool/errors.js +0 -11
  110. package/session_pool/fingerprint.d.ts +0 -9
  111. package/session_pool/fingerprint.js +0 -30
  112. package/session_pool/index.d.ts +0 -4
  113. package/session_pool/index.js +0 -4
  114. package/session_pool/session.d.ts +0 -150
  115. package/session_pool/session.js +0 -220
  116. package/session_pool/session_pool.d.ts +0 -240
  117. package/session_pool/session_pool.js +0 -394
  118. package/storages/sitemap_request_loader.d.ts +0 -201
  119. package/storages/sitemap_request_loader.js +0 -438
  120. package/storages/throttling_request_manager.d.ts +0 -239
  121. package/storages/throttling_request_manager.js +0 -646
  122. /package/{crawlers/crawler_commons.js → events/system_info.js} +0 -0
@@ -1,394 +0,0 @@
1
- import { AsyncQueue } from '@sapphire/async-queue';
2
- import { z } from 'zod';
3
- import { EventType } from '../events/event_manager.js';
4
- import { serviceLocator } from '../service_locator.js';
5
- import { KeyValueStore } from '../storages/key_value_store.js';
6
- import { parseArgument, schemas, validators } from '../validators.js';
7
- import { MAX_POOL_SIZE, PERSIST_STATE_KEY } from './consts.js';
8
- import { createDefaultSessionFingerprint } from './fingerprint.js';
9
- import { Session } from './session.js';
10
- const SESSION_REUSE_STRATEGIES = ['random', 'round-robin', 'use-until-failure'];
11
- // `schemas.anyObject` passes values through by reference (object schemas return a pruned plain
12
- // copy), so class instances like loggers keep their prototype.
13
- const sessionPoolOptionsSchema = z.strictObject({
14
- id: z.union([schemas.anyNumber, z.string()]).optional(),
15
- maxPoolSize: schemas.anyNumber.default(MAX_POOL_SIZE),
16
- persistStateKeyValueStoreId: z.string().optional(),
17
- persistStateKey: z.string().optional(),
18
- createSessionFunction: schemas.anyFunction.optional(),
19
- sessionOptions: schemas.anyObject.default(() => ({})),
20
- log: validators.logger.default(() => serviceLocator.getLogger()),
21
- persistenceOptions: schemas.anyObject.default(() => ({ enable: true })),
22
- sessionReuseStrategy: z.enum(SESSION_REUSE_STRATEGIES).default('random'),
23
- });
24
- const createSessionOptionsSchema = z.strictObject({
25
- sessionOptions: schemas.anyObject.default(() => ({})),
26
- });
27
- /**
28
- * Handles the rotation, creation and persistence of user-like sessions.
29
- * Creates a pool of {@link Session} instances, that are randomly rotated.
30
- * When some session is marked as blocked, it is removed and new one is created instead (the pool never returns an unusable session).
31
- * Learn more in the {@doclink guides/session-management | Session management guide}.
32
- *
33
- * Session pool is already integrated into crawlers and is always active.
34
- * All public methods are lazy-initialized — the pool initializes itself on first use.
35
- *
36
- * You can configure the pool with many options. See the {@link SessionPoolOptions}.
37
- * Session pool is by default persisted in default {@link KeyValueStore}.
38
- * If you want to have one pool for all runs you have to specify
39
- * {@link SessionPoolOptions.persistStateKeyValueStoreId}.
40
- *
41
- * **Advanced usage:**
42
- *
43
- * ```javascript
44
- * const sessionPool = new SessionPool({
45
- * maxPoolSize: 25,
46
- * sessionOptions:{
47
- * maxAgeSecs: 10,
48
- * maxUsageCount: 150, // for example when you know that the site blocks after 150 requests.
49
- * },
50
- * persistStateKeyValueStoreId: 'my-key-value-store-for-sessions',
51
- * persistStateKey: 'my-session-pool',
52
- * });
53
- *
54
- * // Get random session from the pool
55
- * const session1 = await sessionPool.getSession();
56
- * const session2 = await sessionPool.getSession();
57
- * const session3 = await sessionPool.getSession();
58
- *
59
- * // Now you can mark the session either failed or successful
60
- *
61
- * // Marks session as bad after unsuccessful usage -> it increases error count (soft retire)
62
- * session1.markBad()
63
- *
64
- * // Marks as successful.
65
- * session2.markGood()
66
- *
67
- * // Retires session -> session is removed from the pool
68
- * session3.retire()
69
- *
70
- * ```
71
- *
72
- * **Default session allocation flow:*
73
- * 1. Until the `SessionPool` reaches `maxPoolSize`, new sessions are created, provided to the user and added to the pool
74
- * 2. Blocked/retired sessions stay in the pool but are never provided to the user
75
- * 3. Once the pool is full (live plus blocked session count reaches `maxPoolSize`), a random session from the pool is provided.
76
- * 4. If a blocked session would be picked, instead all blocked sessions are evicted from the pool and a new session is created and provided
77
- *
78
- * @category Scaling
79
- */
80
- export class SessionPool {
81
- static #nextId = 0;
82
- id;
83
- #log;
84
- #sessions = [];
85
- // kept as TS-private: session_pool tests read/override the members below directly
86
- maxPoolSize;
87
- createSessionFunction;
88
- keyValueStore;
89
- sessionMap = new Map();
90
- sessionOptions;
91
- persistStateKeyValueStoreId;
92
- persistStateKey;
93
- #listener;
94
- #events;
95
- #persistenceOptions;
96
- #sessionReuseStrategy;
97
- #initPromise;
98
- #queue = new AsyncQueue();
99
- #roundRobinIndex = 0;
100
- constructor(options = {}) {
101
- const { id, maxPoolSize, persistStateKeyValueStoreId, persistStateKey, createSessionFunction, sessionOptions, log, persistenceOptions, sessionReuseStrategy, } = parseArgument(options, sessionPoolOptionsSchema);
102
- this.id = id != null ? String(id) : String(SessionPool.#nextId++);
103
- this.#sessionReuseStrategy = sessionReuseStrategy;
104
- this.#events = serviceLocator.getEventManager();
105
- this.#log = log.child({ prefix: 'SessionPool' });
106
- this.#persistenceOptions = persistenceOptions;
107
- // Pool Configuration
108
- this.maxPoolSize = maxPoolSize;
109
- this.createSessionFunction = createSessionFunction || this.defaultCreateSessionFunction;
110
- // Session configuration. The pool-scoped logger is merged into per-call sessionOptions inside
111
- // `invokeCreateSessionFunction`, so every Session inherits it without custom createSessionFunctions
112
- // having to know about it.
113
- this.sessionOptions = {
114
- ...sessionOptions,
115
- log: this.#log,
116
- };
117
- // Session keyValueStore
118
- this.persistStateKeyValueStoreId = persistStateKeyValueStoreId;
119
- this.persistStateKey = persistStateKey ?? `${PERSIST_STATE_KEY}_${this.id}`;
120
- }
121
- /**
122
- * Gets count of usable sessions in the pool.
123
- */
124
- async usableSessionsCount() {
125
- await this.ensureInitialized();
126
- return this.#sessions.filter((session) => session.isUsable()).length;
127
- }
128
- /**
129
- * Gets count of retired sessions in the pool.
130
- */
131
- async retiredSessionsCount() {
132
- await this.ensureInitialized();
133
- return this.#sessions.filter((session) => !session.isUsable()).length;
134
- }
135
- /**
136
- * Starts periodic state persistence and potentially loads SessionPool state from {@link KeyValueStore}.
137
- * Called automatically on first use of any public method.
138
- */
139
- async ensureInitialized() {
140
- if (!this.#initPromise) {
141
- this.#initPromise = this.setupPool();
142
- }
143
- return this.#initPromise;
144
- }
145
- async setupPool() {
146
- if (!this.#persistenceOptions.enable) {
147
- return;
148
- }
149
- this.keyValueStore = await KeyValueStore.open(this.persistStateKeyValueStoreId ? { id: this.persistStateKeyValueStoreId } : null, {
150
- configuration: serviceLocator.getConfiguration(),
151
- });
152
- if (!this.persistStateKeyValueStoreId) {
153
- this.#log.debug(`No 'persistStateKeyValueStoreId' options specified, this session pool's data has been saved in the KeyValueStore with the id: ${this.keyValueStore.id}`);
154
- }
155
- // in case of migration happened and SessionPool state should be restored from the keyValueStore.
156
- await this.maybeLoadSessionPool();
157
- this.#listener = this.persistState.bind(this);
158
- this.#events.on(EventType.PERSIST_STATE, this.#listener);
159
- }
160
- /**
161
- * Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
162
- * but this allows you to add more sessions once the max pool size is reached.
163
- * This also allows you to add session with overridden session options (e.g. with specific session id).
164
- * @param [options] The configuration options for the session being added to the session pool.
165
- */
166
- async addSession(options = {}) {
167
- await this.ensureInitialized();
168
- const { id } = options;
169
- if (id) {
170
- const sessionExists = this.sessionMap.has(id);
171
- if (sessionExists) {
172
- throw new Error(`Cannot add session with id '${id}' as it already exists in the pool`);
173
- }
174
- }
175
- if (!this.hasSpaceForSession()) {
176
- this.removeRetiredSessions();
177
- }
178
- const newSession = options instanceof Session ? options : await this.invokeCreateSessionFunction(options);
179
- this.#log.debug(`Adding new Session - ${newSession.id}`);
180
- this.registerSession(newSession);
181
- }
182
- /**
183
- * Adds a new session to the session pool. The pool automatically creates sessions up to the maximum size of the pool,
184
- * but this allows you to add more sessions once the max pool size is reached.
185
- * This also allows you to add session with overridden session options (e.g. with specific session id).
186
- * @param [options] The configuration options for the session being added to the session pool.
187
- */
188
- async newSession(sessionOptions) {
189
- await this.ensureInitialized();
190
- const newSession = await this.invokeCreateSessionFunction(sessionOptions);
191
- this.registerSession(newSession);
192
- return newSession;
193
- }
194
- /**
195
- * Gets session.
196
- * If there is space for new session, it creates and returns new session.
197
- * If the session pool is full, it picks a session from the pool,
198
- * If the picked session is usable it is returned, otherwise it creates and returns a new one.
199
- * @param [sessionId] If provided, it returns the usable session with this id, `undefined` otherwise.
200
- */
201
- async getSession(sessionId) {
202
- await this.ensureInitialized();
203
- await this.#queue.wait();
204
- try {
205
- if (sessionId) {
206
- const session = this.sessionMap.get(sessionId);
207
- if (session?.isUsable())
208
- return session;
209
- return undefined;
210
- }
211
- const pickedSession = this.pickSession();
212
- if (pickedSession)
213
- return pickedSession;
214
- if (this.hasSpaceForSession()) {
215
- return await this.createSession();
216
- }
217
- this.removeRetiredSessions();
218
- return await this.createSession();
219
- }
220
- finally {
221
- this.#queue.shift();
222
- }
223
- }
224
- /**
225
- * @param options - Override the persistence options provided in the constructor
226
- */
227
- async resetStore(options) {
228
- if (!this.#persistenceOptions.enable && !options?.enable) {
229
- return;
230
- }
231
- await this.ensureInitialized();
232
- await this.keyValueStore?.setValue(this.persistStateKey, null);
233
- }
234
- /**
235
- * Returns an object representing the internal state of the `SessionPool` instance.
236
- * Note that the object's fields can change in future releases.
237
- */
238
- async getState() {
239
- await this.ensureInitialized();
240
- return {
241
- usableSessionsCount: await this.usableSessionsCount(),
242
- retiredSessionsCount: await this.retiredSessionsCount(),
243
- sessions: this.#sessions.map((session) => session.getState()),
244
- };
245
- }
246
- /**
247
- * Persists the current state of the `SessionPool` into the default {@link KeyValueStore}.
248
- * The state is persisted automatically in regular intervals.
249
- * @param options - Override the persistence options provided in the constructor
250
- */
251
- async persistState(options) {
252
- if (!this.#persistenceOptions.enable && !options?.enable) {
253
- return;
254
- }
255
- await this.ensureInitialized();
256
- this.#log.debug('Persisting state', {
257
- persistStateKeyValueStoreId: this.persistStateKeyValueStoreId,
258
- persistStateKey: this.persistStateKey,
259
- });
260
- await this.keyValueStore
261
- ?.setValue(this.persistStateKey, await this.getState())
262
- .catch((error) => this.#log.warning(`Failed to persist the session pool stats to ${this.persistStateKey}`, { error }));
263
- }
264
- /**
265
- * Removes listener from `persistState` event.
266
- * This function should be called after you are done with using the `SessionPool` instance.
267
- * @param options - Set `persistState` to false when the final state was already persisted by the event manager.
268
- */
269
- async teardown({ persistState = true } = {}) {
270
- if (!this.#initPromise)
271
- return;
272
- await this.ensureInitialized();
273
- if (this.#listener) {
274
- this.#events.off(EventType.PERSIST_STATE, this.#listener);
275
- }
276
- if (persistState) {
277
- await this.persistState();
278
- }
279
- }
280
- /**
281
- * Removes retired `Session` instances from `SessionPool`.
282
- */
283
- removeRetiredSessions() {
284
- this.#sessions = this.#sessions.filter((storedSession) => {
285
- if (storedSession.isUsable())
286
- return true;
287
- this.sessionMap.delete(storedSession.id);
288
- this.#log.debug(`Removed Session - ${storedSession.id}`);
289
- return false;
290
- });
291
- }
292
- /**
293
- * Adds `Session` instance to `SessionPool`.
294
- * @param newSession `Session` instance to be added.
295
- */
296
- registerSession(newSession) {
297
- this.#sessions.push(newSession);
298
- this.sessionMap.set(newSession.id, newSession);
299
- }
300
- /**
301
- * Gets random index.
302
- */
303
- getRandomIndex() {
304
- return Math.floor(Math.random() * this.#sessions.length);
305
- }
306
- /**
307
- * Creates new session without any extra behavior.
308
- * @param [options]
309
- * @param [options.sessionOptions] The configuration options for the session being created.
310
- * @returns New session.
311
- */
312
- async defaultCreateSessionFunction(options = {}) {
313
- const { sessionOptions } = parseArgument(options, createSessionOptionsSchema);
314
- return new Session(sessionOptions);
315
- }
316
- /**
317
- * Invokes `createSessionFunction` with `sessionOptions` already merged from pool-wide defaults and
318
- * the supplied per-call overrides, so custom implementations don't need to spread `pool.sessionOptions` themselves.
319
- *
320
- * A default {@link SessionFingerprint} is generated up front (host OS as
321
- * `platform`, a random valid `browser`/`device` for that platform). Pool-wide
322
- * and per-call options override it, and a persisted fingerprint coming
323
- * through `maybeLoadSessionPool` naturally wins because it arrives in
324
- * `perCallOptions`.
325
- */
326
- async invokeCreateSessionFunction(perCallOptions) {
327
- const sessionOptions = {
328
- fingerprint: createDefaultSessionFingerprint(),
329
- ...this.sessionOptions,
330
- ...perCallOptions,
331
- };
332
- return this.createSessionFunction({ sessionOptions });
333
- }
334
- /**
335
- * Creates new session and adds it to the pool.
336
- * @returns Newly created `Session` instance.
337
- */
338
- async createSession() {
339
- const newSession = await this.invokeCreateSessionFunction();
340
- this.registerSession(newSession);
341
- this.#log.debug(`Created new Session - ${newSession.id}`);
342
- return newSession;
343
- }
344
- /**
345
- * Decides whether there is enough space for creating new session.
346
- */
347
- hasSpaceForSession() {
348
- return this.#sessions.length < this.maxPoolSize;
349
- }
350
- /**
351
- * Picks a session from the `SessionPool` according to the configured `sessionReuseStrategy`.
352
- * Returns `undefined` when no session should be reused and a new one should be created instead.
353
- */
354
- pickSession() {
355
- if (this.#sessionReuseStrategy !== 'use-until-failure' && this.hasSpaceForSession())
356
- return undefined;
357
- if (this.#sessionReuseStrategy === 'use-until-failure') {
358
- return this.#sessions.find((session) => session.isUsable());
359
- }
360
- let picked;
361
- if (this.#sessionReuseStrategy === 'round-robin') {
362
- const index = this.#roundRobinIndex % this.#sessions.length;
363
- this.#roundRobinIndex = index + 1;
364
- picked = this.#sessions[index];
365
- }
366
- else {
367
- picked = this.#sessions[this.getRandomIndex()];
368
- }
369
- return picked.isUsable() ? picked : undefined;
370
- }
371
- /**
372
- * Potentially loads `SessionPool`.
373
- * If the state was persisted it loads the `SessionPool` from the persisted state.
374
- */
375
- async maybeLoadSessionPool() {
376
- const loadedSessionPool = await this.keyValueStore?.getValue(this.persistStateKey);
377
- if (!loadedSessionPool)
378
- return;
379
- // Invalidate old sessions and load active sessions only
380
- this.#log.debug('Recreating state from KeyValueStore', {
381
- persistStateKeyValueStoreId: this.persistStateKeyValueStoreId,
382
- persistStateKey: this.persistStateKey,
383
- });
384
- for (const sessionObject of loadedSessionPool.sessions) {
385
- sessionObject.createdAt = new Date(sessionObject.createdAt);
386
- sessionObject.expiresAt = new Date(sessionObject.expiresAt);
387
- const recreatedSession = await this.invokeCreateSessionFunction(sessionObject);
388
- if (recreatedSession.isUsable()) {
389
- this.registerSession(recreatedSession);
390
- }
391
- }
392
- this.#log.debug(`${this.#sessions.length} active sessions loaded from KeyValueStore`);
393
- }
394
- }
@@ -1,201 +0,0 @@
1
- import type { BaseHttpClient } from '@crawlee/http-client';
2
- import { EnqueueStrategy, type ParseSitemapOptions } from '@crawlee/utils';
3
- import type { UrlPatternInput } from '../enqueue_links/shared.js';
4
- import { Request } from '../request.js';
5
- import type { IRequestLoader } from './request_loader.js';
6
- import type { IRequestManager } from './request_manager.js';
7
- interface UrlConstraints {
8
- /**
9
- * An array of URL patterns that URLs must match to be included.
10
- *
11
- * Accepts glob pattern strings, `{ glob: string }` objects, `RegExp` instances, or `{ regexp: RegExp }` objects.
12
- *
13
- * Glob matching is always case-insensitive.
14
- * If you need case-sensitive matching, use a `RegExp`.
15
- *
16
- * If `include` is an empty array or `undefined`, then the `SitemapRequestLoader`
17
- * includes all the URLs from the sitemap.
18
- */
19
- include?: readonly UrlPatternInput[];
20
- /**
21
- * An array of URL patterns. Matching URLs will **not** be included.
22
- *
23
- * Accepts glob pattern strings, `{ glob: string }` objects, `RegExp` instances, or `{ regexp: RegExp }` objects.
24
- *
25
- * Glob matching is always case-insensitive.
26
- * If you need case-sensitive matching, use a `RegExp`.
27
- */
28
- exclude?: readonly UrlPatternInput[];
29
- }
30
- export interface SitemapRequestLoaderOptions extends UrlConstraints {
31
- /**
32
- * List of sitemap URLs to parse.
33
- */
34
- sitemapUrls: string[];
35
- /**
36
- * Proxy URL to be used for sitemap loading.
37
- */
38
- proxyUrl?: string;
39
- /**
40
- * Key for persisting the state of the request list in the `KeyValueStore`.
41
- */
42
- persistStateKey?: string;
43
- /**
44
- * Persistence-related options to control how and when crawler's data gets persisted.
45
- */
46
- persistenceOptions?: {
47
- /**
48
- * Use this flag to disable or enable periodic persistence to key value store.
49
- * @default true
50
- */
51
- enable?: boolean;
52
- };
53
- /**
54
- * Abort signal to be used for sitemap loading.
55
- */
56
- signal?: AbortSignal;
57
- /**
58
- * Timeout for sitemap loading in milliseconds. If both `signal` and `timeoutMillis` are provided, either of them can abort the loading.
59
- */
60
- timeoutMillis?: number;
61
- /**
62
- * Maximum number of buffered URLs for the sitemap loading stream.
63
- * If the buffer is full, the stream will pause until the buffer is drained.
64
- *
65
- * @default 200
66
- */
67
- maxBufferSize?: number;
68
- /**
69
- * Keep only sitemap-derived URLs matching this strategy relative to the parent sitemap URL; non-`http(s)`
70
- * schemes are always dropped. The filtering stays enforced after navigation (e.g. across redirects).
71
- * Pass `'all'` to disable host filtering.
72
- * @default EnqueueStrategy.SameHostname
73
- */
74
- enqueueStrategy?: EnqueueStrategy | `${EnqueueStrategy}`;
75
- /**
76
- * Advanced options for the underlying `parseSitemap` call.
77
- */
78
- parseSitemapOptions?: Omit<ParseSitemapOptions, 'emitNestedSitemaps' | 'maxDepth'>;
79
- /**
80
- * Custom HTTP client to be used for sitemap loading.
81
- */
82
- httpClient?: BaseHttpClient;
83
- }
84
- /**
85
- * A list of URLs to crawl parsed from a sitemap.
86
- *
87
- * The loading of the sitemap is performed in the background so that crawling can start before the sitemap is fully loaded.
88
- */
89
- export declare class SitemapRequestLoader implements IRequestLoader {
90
- #private;
91
- /**
92
- * Set of URLs that were returned by `fetchNextRequest()` and not marked as handled yet.
93
- * @internal
94
- */
95
- inProgress: Set<string>;
96
- /** @internal */
97
- private constructor();
98
- /**
99
- * Creates a new object stream with the specified highWaterMark.
100
- * @param highWaterMark High water mark for the stream (the maximum number of objects the stream will buffer).
101
- * @returns A new object stream.
102
- */
103
- private createNewStream;
104
- /**
105
- * Returns a function that checks whether the provided pattern matches the closure URL.
106
- * @param url URL to be checked.
107
- * @returns A matcher function that checks whether the pattern matches the closure URL.
108
- */
109
- private matchesUrl;
110
- /**
111
- * Checks whether the URL matches the `include` / `exclude` patterns provided in the `options`.
112
- * @param url URL to be checked.
113
- * @returns `true` if the URL matches the patterns, `false` otherwise.
114
- */
115
- private isUrlMatchingPatterns;
116
- /**
117
- * Adds a URL to the queue of parsed URLs.
118
- *
119
- * Blocks if the stream is full until it is drained.
120
- */
121
- private pushNextUrl;
122
- /**
123
- * Reads the next URL from the queue of parsed URLs.
124
- *
125
- * If the stream is empty, blocks until a new URL is pushed.
126
- * @returns The next URL from the queue or `null` if we have read all URLs.
127
- */
128
- private readNextUrl;
129
- /**
130
- * Indicates whether the background processing of sitemap contents has successfully finished.
131
- *
132
- * If this is `false`, the background processing is either still in progress or was aborted.
133
- */
134
- isSitemapFullyLoaded(): boolean;
135
- /**
136
- * Start processing the sitemaps and loading the URLs.
137
- *
138
- * Resolves once all the sitemaps URLs have been fully loaded (sets `isSitemapFullyLoaded` to `true`).
139
- */
140
- private load;
141
- /**
142
- * Open a sitemap and start processing it.
143
- *
144
- * Resolves to a new instance of `SitemapRequestLoader`, which **might not be fully loaded yet** - i.e. the sitemap might still be loading in the background.
145
- *
146
- * Track the loading progress using the `isSitemapFullyLoaded` property.
147
- */
148
- static open(options: SitemapRequestLoaderOptions): Promise<SitemapRequestLoader>;
149
- /**
150
- * @inheritDoc
151
- */
152
- getTotalCount(): Promise<number>;
153
- /**
154
- * @inheritDoc
155
- */
156
- getPendingCount(): Promise<number>;
157
- /**
158
- * Combines this list with a request manager (a {@link RequestQueue} by default) into a
159
- * {@link RequestManagerTandem}, allowing requests to be added and reclaimed while still
160
- * being read from this list first.
161
- */
162
- toTandem(requestManager?: IRequestManager): Promise<IRequestManager>;
163
- /**
164
- * @inheritDoc
165
- */
166
- isFinished(): Promise<boolean>;
167
- /**
168
- * @inheritDoc
169
- */
170
- isEmpty(): Promise<boolean>;
171
- /**
172
- * @inheritDoc
173
- */
174
- getHandledCount(): Promise<number>;
175
- /**
176
- * @inheritDoc
177
- */
178
- persistState(): Promise<void>;
179
- private restoreState;
180
- /**
181
- * @inheritDoc
182
- */
183
- fetchNextRequest(): Promise<Request | null>;
184
- /**
185
- * @inheritDoc
186
- */
187
- // @ts-ignore optional peer dependency or compatibility with es2022
188
- [Symbol.asyncIterator](): AsyncGenerator<Request<import("@crawlee/types").Dictionary>, void, unknown>;
189
- /**
190
- * Aborts the internal sitemap loading, stops the processing of the sitemap contents and drops all the pending URLs.
191
- *
192
- * Calling `fetchNextRequest()` after this method will always return `null`.
193
- */
194
- teardown(): Promise<void>;
195
- /**
196
- * @inheritDoc
197
- */
198
- markRequestAsHandled(request: Request): Promise<void>;
199
- private ensureInProgress;
200
- }
201
- export {};