@crawlee/core 4.0.0-beta.8 → 4.0.0-beta.81

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 (257) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +14 -15
  3. package/autoscaling/autoscaled_pool.js +37 -36
  4. package/autoscaling/client_load_signal.d.ts +25 -0
  5. package/autoscaling/client_load_signal.js +36 -0
  6. package/autoscaling/cpu_load_signal.d.ts +28 -0
  7. package/autoscaling/cpu_load_signal.js +24 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +23 -0
  9. package/autoscaling/event_loop_load_signal.js +35 -0
  10. package/autoscaling/index.d.ts +5 -1
  11. package/autoscaling/index.js +5 -1
  12. package/autoscaling/load_signal.d.ts +99 -0
  13. package/autoscaling/load_signal.js +135 -0
  14. package/autoscaling/memory_load_signal.d.ts +43 -0
  15. package/autoscaling/memory_load_signal.js +102 -0
  16. package/autoscaling/snapshotter.d.ts +29 -91
  17. package/autoscaling/snapshotter.js +65 -204
  18. package/autoscaling/system_status.d.ts +22 -37
  19. package/autoscaling/system_status.js +49 -87
  20. package/configuration.d.ts +88 -228
  21. package/configuration.js +162 -224
  22. package/cookie_utils.d.ts +4 -3
  23. package/cookie_utils.js +20 -13
  24. package/crawlers/context_pipeline.d.ts +70 -0
  25. package/crawlers/context_pipeline.js +122 -0
  26. package/crawlers/crawler_commons.d.ts +20 -30
  27. package/crawlers/crawler_commons.js +12 -21
  28. package/crawlers/crawler_utils.d.ts +2 -3
  29. package/crawlers/crawler_utils.js +1 -2
  30. package/crawlers/error_snapshotter.d.ts +3 -3
  31. package/crawlers/error_snapshotter.js +2 -3
  32. package/crawlers/error_tracker.d.ts +2 -2
  33. package/crawlers/error_tracker.js +0 -1
  34. package/crawlers/index.d.ts +1 -2
  35. package/crawlers/index.js +1 -2
  36. package/crawlers/internals/types.d.ts +7 -0
  37. package/crawlers/internals/types.js +1 -0
  38. package/crawlers/statistics.d.ts +28 -23
  39. package/crawlers/statistics.js +38 -34
  40. package/enqueue_links/enqueue_links.d.ts +44 -22
  41. package/enqueue_links/enqueue_links.js +51 -30
  42. package/enqueue_links/index.d.ts +0 -1
  43. package/enqueue_links/index.js +0 -1
  44. package/enqueue_links/shared.d.ts +25 -9
  45. package/enqueue_links/shared.js +69 -38
  46. package/errors.d.ts +53 -4
  47. package/errors.js +70 -5
  48. package/events/event_manager.d.ts +34 -8
  49. package/events/event_manager.js +8 -10
  50. package/events/index.d.ts +0 -1
  51. package/events/index.js +0 -1
  52. package/events/local_event_manager.d.ts +15 -5
  53. package/events/local_event_manager.js +37 -40
  54. package/index.d.ts +4 -3
  55. package/index.js +3 -2
  56. package/log.d.ts +82 -3
  57. package/log.js +102 -1
  58. package/memory-storage/consts.d.ts +4 -0
  59. package/memory-storage/consts.js +4 -0
  60. package/memory-storage/index.d.ts +1 -0
  61. package/memory-storage/index.js +1 -0
  62. package/memory-storage/memory-storage.d.ts +46 -0
  63. package/memory-storage/memory-storage.js +136 -0
  64. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  65. package/memory-storage/resource-clients/common/base-client.js +6 -0
  66. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  67. package/memory-storage/resource-clients/dataset.js +113 -0
  68. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  69. package/memory-storage/resource-clients/key-value-store.js +203 -0
  70. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  71. package/memory-storage/resource-clients/request-queue.js +421 -0
  72. package/memory-storage/utils.d.ts +17 -0
  73. package/memory-storage/utils.js +42 -0
  74. package/package.json +12 -10
  75. package/proxy_configuration.d.ts +29 -152
  76. package/proxy_configuration.js +21 -173
  77. package/recoverable_state.d.ts +120 -0
  78. package/recoverable_state.js +141 -0
  79. package/request.d.ts +84 -13
  80. package/request.js +107 -28
  81. package/router.d.ts +118 -16
  82. package/router.js +124 -30
  83. package/serialization.d.ts +0 -1
  84. package/serialization.js +1 -2
  85. package/service_locator.d.ts +156 -0
  86. package/service_locator.js +238 -0
  87. package/session_pool/consts.d.ts +1 -2
  88. package/session_pool/consts.js +1 -2
  89. package/session_pool/errors.d.ts +0 -1
  90. package/session_pool/errors.js +0 -1
  91. package/session_pool/fingerprint.d.ts +9 -0
  92. package/session_pool/fingerprint.js +30 -0
  93. package/session_pool/index.d.ts +0 -2
  94. package/session_pool/index.js +0 -2
  95. package/session_pool/session.d.ts +37 -75
  96. package/session_pool/session.js +49 -102
  97. package/session_pool/session_pool.d.ts +85 -90
  98. package/session_pool/session_pool.js +131 -120
  99. package/storages/access_checking.d.ts +0 -1
  100. package/storages/access_checking.js +5 -2
  101. package/storages/dataset.d.ts +101 -51
  102. package/storages/dataset.js +168 -126
  103. package/storages/index.d.ts +8 -7
  104. package/storages/index.js +6 -7
  105. package/storages/key_value_store.d.ts +165 -36
  106. package/storages/key_value_store.js +269 -122
  107. package/storages/key_value_store_codec.d.ts +32 -0
  108. package/storages/key_value_store_codec.js +113 -0
  109. package/storages/request_dedup_cache.d.ts +23 -0
  110. package/storages/request_dedup_cache.js +48 -0
  111. package/storages/request_list.d.ts +53 -97
  112. package/storages/request_list.js +99 -75
  113. package/storages/request_loader.d.ts +96 -0
  114. package/storages/request_loader.js +1 -0
  115. package/storages/request_manager.d.ts +33 -0
  116. package/storages/request_manager.js +1 -0
  117. package/storages/request_manager_tandem.d.ts +106 -0
  118. package/storages/request_manager_tandem.js +197 -0
  119. package/storages/request_queue.d.ts +290 -47
  120. package/storages/request_queue.js +628 -215
  121. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
  122. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -46
  123. package/storages/storage_instance_manager.d.ts +91 -0
  124. package/storages/storage_instance_manager.js +258 -0
  125. package/storages/storage_stats.d.ts +48 -0
  126. package/storages/storage_stats.js +29 -0
  127. package/storages/utils.d.ts +51 -6
  128. package/storages/utils.js +60 -9
  129. package/system-info/cpu-info.d.ts +67 -0
  130. package/system-info/cpu-info.js +216 -0
  131. package/system-info/memory-info.d.ts +31 -0
  132. package/system-info/memory-info.js +115 -0
  133. package/system-info/ps-tree.d.ts +17 -0
  134. package/system-info/ps-tree.js +144 -0
  135. package/system-info/runtime.d.ts +14 -0
  136. package/system-info/runtime.js +80 -0
  137. package/typedefs.d.ts +1 -2
  138. package/typedefs.js +0 -1
  139. package/validators.d.ts +8 -1
  140. package/validators.js +10 -3
  141. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  142. package/autoscaling/autoscaled_pool.js.map +0 -1
  143. package/autoscaling/index.d.ts.map +0 -1
  144. package/autoscaling/index.js.map +0 -1
  145. package/autoscaling/snapshotter.d.ts.map +0 -1
  146. package/autoscaling/snapshotter.js.map +0 -1
  147. package/autoscaling/system_status.d.ts.map +0 -1
  148. package/autoscaling/system_status.js.map +0 -1
  149. package/configuration.d.ts.map +0 -1
  150. package/configuration.js.map +0 -1
  151. package/cookie_utils.d.ts.map +0 -1
  152. package/cookie_utils.js.map +0 -1
  153. package/crawlers/crawler_commons.d.ts.map +0 -1
  154. package/crawlers/crawler_commons.js.map +0 -1
  155. package/crawlers/crawler_extension.d.ts +0 -12
  156. package/crawlers/crawler_extension.d.ts.map +0 -1
  157. package/crawlers/crawler_extension.js +0 -14
  158. package/crawlers/crawler_extension.js.map +0 -1
  159. package/crawlers/crawler_utils.d.ts.map +0 -1
  160. package/crawlers/crawler_utils.js.map +0 -1
  161. package/crawlers/error_snapshotter.d.ts.map +0 -1
  162. package/crawlers/error_snapshotter.js.map +0 -1
  163. package/crawlers/error_tracker.d.ts.map +0 -1
  164. package/crawlers/error_tracker.js.map +0 -1
  165. package/crawlers/index.d.ts.map +0 -1
  166. package/crawlers/index.js.map +0 -1
  167. package/crawlers/statistics.d.ts.map +0 -1
  168. package/crawlers/statistics.js.map +0 -1
  169. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  170. package/enqueue_links/enqueue_links.js.map +0 -1
  171. package/enqueue_links/index.d.ts.map +0 -1
  172. package/enqueue_links/index.js.map +0 -1
  173. package/enqueue_links/shared.d.ts.map +0 -1
  174. package/enqueue_links/shared.js.map +0 -1
  175. package/errors.d.ts.map +0 -1
  176. package/errors.js.map +0 -1
  177. package/events/event_manager.d.ts.map +0 -1
  178. package/events/event_manager.js.map +0 -1
  179. package/events/index.d.ts.map +0 -1
  180. package/events/index.js.map +0 -1
  181. package/events/local_event_manager.d.ts.map +0 -1
  182. package/events/local_event_manager.js.map +0 -1
  183. package/http_clients/base-http-client.d.ts +0 -134
  184. package/http_clients/base-http-client.d.ts.map +0 -1
  185. package/http_clients/base-http-client.js +0 -33
  186. package/http_clients/base-http-client.js.map +0 -1
  187. package/http_clients/form-data-like.d.ts +0 -67
  188. package/http_clients/form-data-like.d.ts.map +0 -1
  189. package/http_clients/form-data-like.js +0 -5
  190. package/http_clients/form-data-like.js.map +0 -1
  191. package/http_clients/got-scraping-http-client.d.ts +0 -15
  192. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  193. package/http_clients/got-scraping-http-client.js +0 -69
  194. package/http_clients/got-scraping-http-client.js.map +0 -1
  195. package/http_clients/index.d.ts +0 -3
  196. package/http_clients/index.d.ts.map +0 -1
  197. package/http_clients/index.js +0 -3
  198. package/http_clients/index.js.map +0 -1
  199. package/index.d.ts.map +0 -1
  200. package/index.js.map +0 -1
  201. package/log.d.ts.map +0 -1
  202. package/log.js.map +0 -1
  203. package/proxy_configuration.d.ts.map +0 -1
  204. package/proxy_configuration.js.map +0 -1
  205. package/request.d.ts.map +0 -1
  206. package/request.js.map +0 -1
  207. package/router.d.ts.map +0 -1
  208. package/router.js.map +0 -1
  209. package/serialization.d.ts.map +0 -1
  210. package/serialization.js.map +0 -1
  211. package/session_pool/consts.d.ts.map +0 -1
  212. package/session_pool/consts.js.map +0 -1
  213. package/session_pool/errors.d.ts.map +0 -1
  214. package/session_pool/errors.js.map +0 -1
  215. package/session_pool/events.d.ts +0 -3
  216. package/session_pool/events.d.ts.map +0 -1
  217. package/session_pool/events.js +0 -3
  218. package/session_pool/events.js.map +0 -1
  219. package/session_pool/index.d.ts.map +0 -1
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts.map +0 -1
  222. package/session_pool/session.js.map +0 -1
  223. package/session_pool/session_pool.d.ts.map +0 -1
  224. package/session_pool/session_pool.js.map +0 -1
  225. package/storages/access_checking.d.ts.map +0 -1
  226. package/storages/access_checking.js.map +0 -1
  227. package/storages/dataset.d.ts.map +0 -1
  228. package/storages/dataset.js.map +0 -1
  229. package/storages/index.d.ts.map +0 -1
  230. package/storages/index.js.map +0 -1
  231. package/storages/key_value_store.d.ts.map +0 -1
  232. package/storages/key_value_store.js.map +0 -1
  233. package/storages/request_list.d.ts.map +0 -1
  234. package/storages/request_list.js.map +0 -1
  235. package/storages/request_provider.d.ts +0 -307
  236. package/storages/request_provider.d.ts.map +0 -1
  237. package/storages/request_provider.js +0 -555
  238. package/storages/request_provider.js.map +0 -1
  239. package/storages/request_queue.d.ts.map +0 -1
  240. package/storages/request_queue.js.map +0 -1
  241. package/storages/request_queue_v2.d.ts +0 -87
  242. package/storages/request_queue_v2.d.ts.map +0 -1
  243. package/storages/request_queue_v2.js +0 -438
  244. package/storages/request_queue_v2.js.map +0 -1
  245. package/storages/sitemap_request_list.d.ts.map +0 -1
  246. package/storages/sitemap_request_list.js.map +0 -1
  247. package/storages/storage_manager.d.ts +0 -58
  248. package/storages/storage_manager.d.ts.map +0 -1
  249. package/storages/storage_manager.js +0 -105
  250. package/storages/storage_manager.js.map +0 -1
  251. package/storages/utils.d.ts.map +0 -1
  252. package/storages/utils.js.map +0 -1
  253. package/tsconfig.build.tsbuildinfo +0 -1
  254. package/typedefs.d.ts.map +0 -1
  255. package/typedefs.js.map +0 -1
  256. package/validators.d.ts.map +0 -1
  257. package/validators.js.map +0 -1
@@ -0,0 +1,122 @@
1
+ import { ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, RequestHandlerError, SessionError, } from '../errors.js';
2
+ import { serviceLocator } from '../service_locator.js';
3
+ /**
4
+ * Encapsulates the logic of gradually enhancing the crawling context with additional information and utilities.
5
+ *
6
+ * The enhancement is done by a chain of middlewares that are added to the pipeline after its creation.
7
+ * This class provides a type-safe way to build a pipeline of context transformations where each step
8
+ * can enhance the context with additional properties or utilities.
9
+ *
10
+ * @template TContextBase - The base context type that serves as the starting point
11
+ * @template TCrawlingContext - The final context type after all middleware transformations
12
+ */
13
+ export class ContextPipeline {
14
+ /**
15
+ * Creates a new empty context pipeline.
16
+ *
17
+ * @template TContextBase - The base context type for the pipeline
18
+ * @returns A new ContextPipeline instance with no transformations
19
+ */
20
+ static create() {
21
+ return new ContextPipelineImpl({ action: async (context) => context });
22
+ }
23
+ }
24
+ /**
25
+ * Implementation of the `ContextPipeline` logic. This hides implementation details such as the `middleware` and `parent`
26
+ * properties from the `ContextPipeline` interface, making type checking more reliable.
27
+ */
28
+ class ContextPipelineImpl extends ContextPipeline {
29
+ middleware;
30
+ parent;
31
+ constructor(middleware, parent) {
32
+ super();
33
+ this.middleware = middleware;
34
+ this.parent = parent;
35
+ }
36
+ /**
37
+ * @inheritdoc
38
+ */
39
+ compose(middleware) {
40
+ return new ContextPipelineImpl(middleware, this);
41
+ }
42
+ chain(other) {
43
+ const otherMiddlewares = Array.from(other.middlewareChain()).reverse();
44
+ let result = this;
45
+ for (const middleware of otherMiddlewares) {
46
+ result = result.compose(middleware);
47
+ }
48
+ return result;
49
+ }
50
+ *middlewareChain() {
51
+ let step = this;
52
+ while (step !== undefined) {
53
+ yield step.middleware;
54
+ step = step.parent;
55
+ }
56
+ }
57
+ /**
58
+ * @inheritdoc
59
+ */
60
+ async call(crawlingContext, finalContextConsumer) {
61
+ const middlewares = Array.from(this.middlewareChain()).reverse();
62
+ const cleanupStack = [];
63
+ let consumerException;
64
+ try {
65
+ for (const { action, cleanup } of middlewares) {
66
+ try {
67
+ const contextExtension = await action(crawlingContext);
68
+ const extensionNames = [
69
+ ...Object.getOwnPropertyNames(contextExtension),
70
+ ...Object.getOwnPropertySymbols(contextExtension),
71
+ ];
72
+ for (const key of extensionNames) {
73
+ try {
74
+ if (Object.getOwnPropertyDescriptor(crawlingContext, key)?.configurable !== false) {
75
+ Object.defineProperty(crawlingContext, key, Object.getOwnPropertyDescriptor(contextExtension, key));
76
+ }
77
+ }
78
+ catch (error) {
79
+ serviceLocator
80
+ .getLogger()
81
+ .debug(`Context pipeline failed to define property ${key.toString()}:`, error);
82
+ }
83
+ }
84
+ if (cleanup) {
85
+ cleanupStack.push(cleanup);
86
+ }
87
+ }
88
+ catch (exception) {
89
+ if (exception instanceof SessionError) {
90
+ throw exception; // Session errors are re-thrown as-is
91
+ }
92
+ if (exception instanceof ContextPipelineInterruptedError) {
93
+ throw exception;
94
+ }
95
+ throw new ContextPipelineInitializationError(exception);
96
+ }
97
+ }
98
+ try {
99
+ await finalContextConsumer(crawlingContext);
100
+ }
101
+ catch (exception) {
102
+ if (exception instanceof SessionError) {
103
+ consumerException = exception;
104
+ throw exception; // Session errors are re-thrown as-is
105
+ }
106
+ consumerException = exception;
107
+ throw new RequestHandlerError(exception);
108
+ }
109
+ }
110
+ finally {
111
+ try {
112
+ for (const cleanup of cleanupStack.reverse()) {
113
+ await cleanup(crawlingContext, consumerException);
114
+ }
115
+ }
116
+ catch (exception) {
117
+ // eslint-disable-next-line no-unsafe-finally
118
+ throw new ContextPipelineCleanupError(exception);
119
+ }
120
+ }
121
+ }
122
+ }
@@ -1,16 +1,13 @@
1
- import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
2
- // @ts-ignore optional peer dependency or compatibility with es2022
3
- import type { OptionsInit, Response as GotResponse } from 'got-scraping';
4
- import type { ReadonlyDeep } from 'type-fest';
1
+ import type { Dictionary, HttpRequestOptions, ISession, ProxyInfo, SendRequestOptions } from '@crawlee/types';
2
+ import type { ReadonlyDeep, SetRequired } from 'type-fest';
5
3
  import type { Configuration } from '../configuration.js';
6
4
  import type { EnqueueLinksOptions } from '../enqueue_links/enqueue_links.js';
7
- import type { Log } from '../log.js';
8
- import type { ProxyInfo } from '../proxy_configuration.js';
5
+ import type { CrawleeLogger } from '../log.js';
9
6
  import type { Request, Source } from '../request.js';
10
- import type { Session } from '../session_pool/session.js';
11
7
  import type { Dataset } from '../storages/dataset.js';
12
8
  import { KeyValueStore, type RecordOptions } from '../storages/key_value_store.js';
13
- import type { RequestQueueOperationOptions } from '../storages/request_provider.js';
9
+ import type { RequestQueueOperationOptions } from '../storages/request_queue.js';
10
+ import type { StorageIdentifier } from '../storages/storage_instance_manager.js';
14
11
  /** @internal */
15
12
  export type IsAny<T> = 0 extends 1 & T ? true : false;
16
13
  /** @internal */
@@ -22,9 +19,9 @@ export type LoadedRequest<R extends Request> = WithRequired<R, 'id' | 'loadedUrl
22
19
  export type LoadedContext<Context extends RestrictedCrawlingContext> = IsAny<Context> extends true ? Context : {
23
20
  request: LoadedRequest<Context['request']>;
24
21
  } & Omit<Context, 'request'>;
25
- export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> extends Record<string & {}, unknown> {
22
+ export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> {
26
23
  id: string;
27
- session?: Session;
24
+ session: ISession;
28
25
  /**
29
26
  * An object with information about currently used proxy by the crawler
30
27
  * and configured by the {@link ProxyConfiguration} class.
@@ -41,7 +38,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
41
38
  *
42
39
  * @param [data] Data to be pushed to the default dataset.
43
40
  */
44
- pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdOrName?: string): Promise<void>;
41
+ pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdentifier?: string | StorageIdentifier): Promise<void>;
45
42
  /**
46
43
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
47
44
  * currently used by the crawler.
@@ -66,7 +63,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
66
63
  *
67
64
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
68
65
  */
69
- enqueueLinks: (options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>>) => Promise<unknown>;
66
+ enqueueLinks: (options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>>) => Promise<unknown>;
70
67
  /**
71
68
  * Add requests directly to the request queue.
72
69
  *
@@ -81,14 +78,13 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
81
78
  /**
82
79
  * Get a key-value store with given name or id, or the default one for the crawler.
83
80
  */
84
- getKeyValueStore: (idOrName?: string) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
81
+ getKeyValueStore: (identifier?: string | StorageIdentifier) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
85
82
  /**
86
83
  * A preconfigured logger for the request handler.
87
84
  */
88
- log: Log;
85
+ log: CrawleeLogger;
89
86
  }
90
- export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
91
- crawler: Crawler;
87
+ export interface CrawlingContext<UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
92
88
  /**
93
89
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
94
90
  * currently used by the crawler.
@@ -114,14 +110,9 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
114
110
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
115
111
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
116
112
  */
117
- enqueueLinks(options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>> & Pick<EnqueueLinksOptions, 'requestQueue'>): Promise<BatchAddRequestsResult>;
113
+ enqueueLinks(options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>> & Pick<EnqueueLinksOptions, 'requestManager' | 'robotsTxtFile'>): Promise<unknown>;
118
114
  /**
119
- * Get a key-value store with given name or id, or the default one for the crawler.
120
- */
121
- getKeyValueStore: (idOrName?: string) => Promise<KeyValueStore>;
122
- /**
123
- * Fires HTTP request via [`got-scraping`](https://crawlee.dev/js/docs/guides/got-scraping), allowing to override the request
124
- * options on the fly.
115
+ * Fires HTTP request via the internal HTTP client, allowing to override the request options on the fly.
125
116
  *
126
117
  * This is handy when you work with a browser crawler but want to execute some requests outside it (e.g. API requests).
127
118
  * Check the [Skipping navigations for certain requests](https://crawlee.dev/js/docs/examples/skip-navigation) example for
@@ -136,7 +127,11 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
136
127
  * },
137
128
  * ```
138
129
  */
139
- sendRequest<Response = string>(overrideOptions?: Partial<OptionsInit>): Promise<GotResponse<Response>>;
130
+ sendRequest: (requestOverrides?: Partial<HttpRequestOptions>, optionsOverrides?: SendRequestOptions) => Promise<Response>;
131
+ /**
132
+ * Register a function to be called at the very end of the request handling process. This is useful for resources that should be accessible to error handlers, for instance.
133
+ */
134
+ registerDeferredCleanup(cleanup: () => Promise<unknown>): void;
140
135
  }
141
136
  /**
142
137
  * A partial implementation of {@link RestrictedCrawlingContext} that stores parameters of calls to context methods for later inspection.
@@ -149,7 +144,6 @@ export declare class RequestHandlerResult {
149
144
  private _keyValueStoreChanges;
150
145
  private pushDataCalls;
151
146
  private addRequestsCalls;
152
- private enqueueLinksCalls;
153
147
  constructor(config: Configuration, crawleeStateKey: string);
154
148
  /**
155
149
  * A record of calls to {@link RestrictedCrawlingContext.pushData}, {@link RestrictedCrawlingContext.addRequests}, {@link RestrictedCrawlingContext.enqueueLinks} made by a request handler.
@@ -157,7 +151,6 @@ export declare class RequestHandlerResult {
157
151
  get calls(): ReadonlyDeep<{
158
152
  pushData: Parameters<RestrictedCrawlingContext['pushData']>[];
159
153
  addRequests: Parameters<RestrictedCrawlingContext['addRequests']>[];
160
- enqueueLinks: Parameters<RestrictedCrawlingContext['enqueueLinks']>[];
161
154
  }>;
162
155
  /**
163
156
  * A record of changes made to key-value stores by a request handler.
@@ -171,7 +164,7 @@ export declare class RequestHandlerResult {
171
164
  */
172
165
  get datasetItems(): ReadonlyDeep<{
173
166
  item: Dictionary;
174
- datasetIdOrName?: string;
167
+ datasetIdentifier?: string | StorageIdentifier;
175
168
  }[]>;
176
169
  /**
177
170
  * URLs enqueued to the request queue by a request handler, either via {@link RestrictedCrawlingContext.addRequests} or {@link RestrictedCrawlingContext.enqueueLinks}
@@ -188,12 +181,9 @@ export declare class RequestHandlerResult {
188
181
  label?: string;
189
182
  }[]>;
190
183
  pushData: RestrictedCrawlingContext['pushData'];
191
- enqueueLinks: RestrictedCrawlingContext['enqueueLinks'];
192
184
  addRequests: RestrictedCrawlingContext['addRequests'];
193
185
  useState: RestrictedCrawlingContext['useState'];
194
186
  getKeyValueStore: RestrictedCrawlingContext['getKeyValueStore'];
195
- private idOrDefault;
196
187
  private getKeyValueStoreChangedValue;
197
188
  private setKeyValueStoreChangedValue;
198
189
  }
199
- //# sourceMappingURL=crawler_commons.d.ts.map
@@ -10,7 +10,6 @@ export class RequestHandlerResult {
10
10
  _keyValueStoreChanges = {};
11
11
  pushDataCalls = [];
12
12
  addRequestsCalls = [];
13
- enqueueLinksCalls = [];
14
13
  constructor(config, crawleeStateKey) {
15
14
  this.config = config;
16
15
  this.crawleeStateKey = crawleeStateKey;
@@ -22,7 +21,6 @@ export class RequestHandlerResult {
22
21
  return {
23
22
  pushData: this.pushDataCalls,
24
23
  addRequests: this.addRequestsCalls,
25
- enqueueLinks: this.enqueueLinksCalls,
26
24
  };
27
25
  }
28
26
  /**
@@ -35,16 +33,13 @@ export class RequestHandlerResult {
35
33
  * Items added to datasets by a request handler.
36
34
  */
37
35
  get datasetItems() {
38
- return this.pushDataCalls.flatMap(([data, datasetIdOrName]) => (Array.isArray(data) ? data : [data]).map((item) => ({ item, datasetIdOrName })));
36
+ return this.pushDataCalls.flatMap(([data, datasetIdentifier]) => (Array.isArray(data) ? data : [data]).map((item) => ({ item, datasetIdentifier })));
39
37
  }
40
38
  /**
41
39
  * URLs enqueued to the request queue by a request handler, either via {@link RestrictedCrawlingContext.addRequests} or {@link RestrictedCrawlingContext.enqueueLinks}
42
40
  */
43
41
  get enqueuedUrls() {
44
42
  const result = [];
45
- for (const [options] of this.enqueueLinksCalls) {
46
- result.push(...(options?.urls?.map((url) => ({ url, label: options?.label })) ?? []));
47
- }
48
43
  for (const [requests] of this.addRequestsCalls) {
49
44
  for (const request of requests) {
50
45
  if (typeof request === 'object' &&
@@ -78,9 +73,6 @@ export class RequestHandlerResult {
78
73
  pushData = async (data, datasetIdOrName) => {
79
74
  this.pushDataCalls.push([data, datasetIdOrName]);
80
75
  };
81
- enqueueLinks = async (options) => {
82
- this.enqueueLinksCalls.push([options]);
83
- };
84
76
  addRequests = async (requests, options = {}) => {
85
77
  this.addRequestsCalls.push([requests, options]);
86
78
  };
@@ -88,29 +80,28 @@ export class RequestHandlerResult {
88
80
  const store = await this.getKeyValueStore(undefined);
89
81
  return await store.getAutoSavedValue(this.crawleeStateKey, defaultValue);
90
82
  };
91
- getKeyValueStore = async (idOrName) => {
92
- const store = await KeyValueStore.open(idOrName, { config: this.config });
83
+ getKeyValueStore = async (identifier) => {
84
+ const store = await KeyValueStore.open(identifier, { config: this.config });
85
+ const storeId = store.id;
93
86
  return {
94
- id: this.idOrDefault(idOrName),
95
- name: idOrName,
96
- getValue: async (key) => this.getKeyValueStoreChangedValue(idOrName, key) ?? (await store.getValue(key)),
87
+ id: storeId ?? this.config.defaultKeyValueStoreId,
88
+ name: store.name,
89
+ getValue: async (key) => this.getKeyValueStoreChangedValue(storeId, key) ?? (await store.getValue(key)),
97
90
  setValue: async (key, value, options) => {
98
- this.setKeyValueStoreChangedValue(idOrName, key, value, options);
91
+ this.setKeyValueStoreChangedValue(storeId, key, value, options);
99
92
  },
100
93
  getAutoSavedValue: store.getAutoSavedValue.bind(store),
101
94
  getPublicUrl: store.getPublicUrl.bind(store),
102
95
  };
103
96
  };
104
- idOrDefault = (idOrName) => idOrName ?? this.config.get('defaultKeyValueStoreId');
105
- getKeyValueStoreChangedValue = (idOrName, key) => {
106
- const id = this.idOrDefault(idOrName);
97
+ getKeyValueStoreChangedValue = (storeKey, key) => {
98
+ const id = storeKey ?? this.config.defaultKeyValueStoreId;
107
99
  this._keyValueStoreChanges[id] ??= {};
108
100
  return this.keyValueStoreChanges[id][key]?.changedValue ?? null;
109
101
  };
110
- setKeyValueStoreChangedValue = (idOrName, key, changedValue, options) => {
111
- const id = this.idOrDefault(idOrName);
102
+ setKeyValueStoreChangedValue = (storeKey, key, changedValue, options) => {
103
+ const id = storeKey ?? this.config.defaultKeyValueStoreId;
112
104
  this._keyValueStoreChanges[id] ??= {};
113
105
  this._keyValueStoreChanges[id][key] = { changedValue, options };
114
106
  };
115
107
  }
116
- //# sourceMappingURL=crawler_commons.js.map
@@ -1,10 +1,9 @@
1
- import type { Session } from '../session_pool/session.js';
1
+ import type { ISession } from '@crawlee/types';
2
2
  /**
3
3
  * Handles timeout request
4
4
  * @internal
5
5
  */
6
6
  export declare function handleRequestTimeout({ session, errorMessage }: {
7
- session?: Session;
7
+ session?: ISession;
8
8
  errorMessage: string;
9
9
  }): void;
10
- //# sourceMappingURL=crawler_utils.d.ts.map
@@ -5,8 +5,7 @@ import { TimeoutError } from '@apify/timeout';
5
5
  */
6
6
  export function handleRequestTimeout({ session, errorMessage }) {
7
7
  session?.markBad();
8
- const timeoutMillis = errorMessage.match(/(\d+)\s?ms/)?.[1]; // first capturing group
8
+ const timeoutMillis = /(\d+)\s?ms/.exec(errorMessage)?.[1]; // first capturing group
9
9
  const timeoutSecs = Number(timeoutMillis) / 1000;
10
10
  throw new TimeoutError(`Navigation timed out after ${timeoutSecs} seconds.`);
11
11
  }
12
- //# sourceMappingURL=crawler_utils.js.map
@@ -1,6 +1,7 @@
1
1
  import type { CrawlingContext } from '../crawlers/crawler_commons.js';
2
2
  import type { KeyValueStore } from '../storages/key_value_store.js';
3
3
  import type { ErrnoException } from './error_tracker.js';
4
+ import type { SnapshottableProperties } from './internals/types.js';
4
5
  interface BrowserCrawlingContext {
5
6
  saveSnapshot: (options: {
6
7
  key: string;
@@ -39,7 +40,7 @@ export declare class ErrorSnapshotter {
39
40
  /**
40
41
  * Capture a snapshot of the error context.
41
42
  */
42
- captureSnapshot(error: ErrnoException, context: CrawlingContext): Promise<ErrorSnapshot>;
43
+ captureSnapshot(error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<ErrorSnapshot>;
43
44
  /**
44
45
  * Captures a snapshot of the current page using the context.saveSnapshot function.
45
46
  * This function is applicable for browser contexts only.
@@ -49,11 +50,10 @@ export declare class ErrorSnapshotter {
49
50
  /**
50
51
  * Save the HTML snapshot of the page, and return the fileName with the extension.
51
52
  */
52
- saveHTMLSnapshot(html: string, keyValueStore: KeyValueStore, fileName: string): Promise<string | undefined>;
53
+ saveHTMLSnapshot(html: string, keyValueStore: Pick<KeyValueStore, 'setValue'>, fileName: string): Promise<string | undefined>;
53
54
  /**
54
55
  * Generate a unique fileName for each error snapshot.
55
56
  */
56
57
  generateFilename(error: ErrnoException): string;
57
58
  }
58
59
  export {};
59
- //# sourceMappingURL=error_snapshotter.d.ts.map
@@ -52,9 +52,9 @@ export class ErrorSnapshotter {
52
52
  }
53
53
  return {
54
54
  screenshotFileName,
55
- screenshotFileUrl: screenshotFileName && keyValueStore.getPublicUrl(screenshotFileName),
55
+ screenshotFileUrl: screenshotFileName && (await keyValueStore.getPublicUrl(screenshotFileName)),
56
56
  htmlFileName,
57
- htmlFileUrl: htmlFileName && keyValueStore.getPublicUrl(htmlFileName),
57
+ htmlFileUrl: htmlFileName && (await keyValueStore.getPublicUrl(htmlFileName)),
58
58
  };
59
59
  }
60
60
  catch {
@@ -115,4 +115,3 @@ export class ErrorSnapshotter {
115
115
  return fileName;
116
116
  }
117
117
  }
118
- //# sourceMappingURL=error_snapshotter.js.map
@@ -1,5 +1,6 @@
1
1
  import type { CrawlingContext } from '../crawlers/crawler_commons.js';
2
2
  import { ErrorSnapshotter } from './error_snapshotter.js';
3
+ import type { SnapshottableProperties } from './internals/types.js';
3
4
  /**
4
5
  * Node.js Error interface
5
6
  */
@@ -48,7 +49,6 @@ export declare class ErrorTracker {
48
49
  addAsync(error: ErrnoException, context?: CrawlingContext): Promise<void>;
49
50
  getUniqueErrorCount(): number;
50
51
  getMostPopularErrors(count: number): [number, string[]][];
51
- captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext): Promise<void>;
52
+ captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<void>;
52
53
  reset(): void;
53
54
  }
54
- //# sourceMappingURL=error_tracker.d.ts.map
@@ -306,4 +306,3 @@ export class ErrorTracker {
306
306
  }
307
307
  }
308
308
  }
309
- //# sourceMappingURL=error_tracker.js.map
@@ -1,7 +1,6 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
3
  export * from './crawler_utils.js';
4
4
  export * from './statistics.js';
5
5
  export * from './error_tracker.js';
6
6
  export * from './error_snapshotter.js';
7
- //# sourceMappingURL=index.d.ts.map
package/crawlers/index.js CHANGED
@@ -1,7 +1,6 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
3
  export * from './crawler_utils.js';
4
4
  export * from './statistics.js';
5
5
  export * from './error_tracker.js';
6
6
  export * from './error_snapshotter.js';
7
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ export interface BrowserPage {
2
+ content: () => Promise<string>;
3
+ }
4
+ export interface SnapshottableProperties {
5
+ body?: unknown;
6
+ page?: BrowserPage;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,4 @@
1
- import type { Log } from '@apify/log';
2
- import { Configuration } from '../configuration.js';
1
+ import type { CrawleeLogger } from '../log.js';
3
2
  import { KeyValueStore } from '../storages/key_value_store.js';
4
3
  import { ErrorTracker } from './error_tracker.js';
5
4
  /**
@@ -17,7 +16,7 @@ export interface PersistenceOptions {
17
16
  * statistics for requests.
18
17
  *
19
18
  * All statistic information is saved on key value store
20
- * under the key `SDK_CRAWLER_STATISTICS_*`, persists between
19
+ * under the key `CRAWLEE_CRAWLER_STATISTICS_*`, persists between
21
20
  * migrations and abort/resurrect
22
21
  *
23
22
  * @category Crawlers
@@ -27,15 +26,15 @@ export declare class Statistics {
27
26
  /**
28
27
  * An error tracker for final retry errors.
29
28
  */
30
- errorTracker: ErrorTracker;
29
+ readonly errorTracker: ErrorTracker;
31
30
  /**
32
31
  * An error tracker for retry errors prior to the final retry.
33
32
  */
34
- errorTrackerRetry: ErrorTracker;
33
+ readonly errorTrackerRetry: ErrorTracker;
35
34
  /**
36
35
  * Statistic instance id.
37
36
  */
38
- readonly id: number;
37
+ readonly id: string;
39
38
  /**
40
39
  * Current statistic state used for doing calculations on {@link Statistics.calculate} calls
41
40
  */
@@ -44,12 +43,8 @@ export declare class Statistics {
44
43
  * Contains the current retries histogram. Index 0 means 0 retries, index 2, 2 retries, and so on
45
44
  */
46
45
  readonly requestRetryHistogram: number[];
47
- /**
48
- * Contains the associated Configuration instance
49
- */
50
- private readonly config;
51
46
  protected keyValueStore?: KeyValueStore;
52
- protected persistStateKey: string;
47
+ protected readonly persistStateKey: string;
53
48
  private logIntervalMillis;
54
49
  private logMessage;
55
50
  private listener;
@@ -57,8 +52,9 @@ export declare class Statistics {
57
52
  private readonly log;
58
53
  private instanceStart;
59
54
  private logInterval;
60
- private events;
55
+ private _events?;
61
56
  private persistenceOptions;
57
+ private get events();
62
58
  /**
63
59
  * @internal
64
60
  */
@@ -90,6 +86,12 @@ export declare class Statistics {
90
86
  * @ignore
91
87
  */
92
88
  failJob(id: number | string, retryCount: number): void;
89
+ /**
90
+ * Discards a started job without affecting the finished/failed counters, e.g. when a request
91
+ * turns out to be skipped (robots.txt, enqueue strategy) after `startJob` was already called for it.
92
+ * @ignore
93
+ */
94
+ discardJob(id: number | string): void;
93
95
  /**
94
96
  * Calculate the current statistics
95
97
  */
@@ -111,7 +113,7 @@ export declare class Statistics {
111
113
  * Stops logging and remove event listeners, then persist
112
114
  */
113
115
  stopCapturing(): Promise<void>;
114
- protected _saveRetryCountForJob(retryCount: number): void;
116
+ private saveRetryCountForJob;
115
117
  /**
116
118
  * Persist internal state to the key value store
117
119
  * @param options - Override the persistence options provided in the constructor
@@ -120,8 +122,8 @@ export declare class Statistics {
120
122
  /**
121
123
  * Loads the current statistic from the key value store if any
122
124
  */
123
- protected _maybeLoadStatistics(): Promise<void>;
124
- protected _teardown(): void;
125
+ protected maybeLoadStatistics(): Promise<void>;
126
+ private teardown;
125
127
  /**
126
128
  * Make this class serializable when called with `JSON.stringify(statsInstance)` directly
127
129
  * or through `keyValueStore.setValue('KEY', statsInstance)`
@@ -146,17 +148,12 @@ export interface StatisticsOptions {
146
148
  * Parent logger instance, the statistics will create a child logger from this.
147
149
  * @default crawler.log
148
150
  */
149
- log?: Log;
151
+ log?: CrawleeLogger;
150
152
  /**
151
153
  * Key value store instance to persist the statistics.
152
154
  * If not provided, the default one will be used when capturing starts
153
155
  */
154
156
  keyValueStore?: KeyValueStore;
155
- /**
156
- * Configuration instance to use
157
- * @default Configuration.getGlobalConfig()
158
- */
159
- config?: Configuration;
160
157
  /**
161
158
  * Control how and when to persist the statistics.
162
159
  */
@@ -166,13 +163,22 @@ export interface StatisticsOptions {
166
163
  * @default false
167
164
  */
168
165
  saveErrorSnapshots?: boolean;
166
+ /**
167
+ * A unique identifier for this statistics instance. This ID is used for persistence
168
+ * to the key value store, ensuring the same statistics can be loaded after script restarts.
169
+ *
170
+ * If not provided, an auto-incremented ID will be used for backward compatibility.
171
+ * This means statistics may not persist correctly across script restarts
172
+ * if crawler creation order changes.
173
+ */
174
+ id?: string;
169
175
  }
170
176
  /**
171
177
  * Format of the persisted stats
172
178
  */
173
179
  export interface StatisticPersistedState extends Omit<StatisticState, 'statsPersistedAt'> {
174
180
  requestRetryHistogram: number[];
175
- statsId: number;
181
+ statsId: string;
176
182
  requestAvgFailedDurationMillis: number;
177
183
  requestAvgFinishedDurationMillis: number;
178
184
  requestTotalDurationMillis: number;
@@ -201,4 +207,3 @@ export interface StatisticState {
201
207
  retryErrors: Record<string, unknown>;
202
208
  requestsWithStatusCode: Record<string, number>;
203
209
  }
204
- //# sourceMappingURL=statistics.d.ts.map