@crawlee/core 4.0.0-beta.1 → 4.0.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +69 -156
  3. package/autoscaling/autoscaled_pool.js +97 -252
  4. package/autoscaling/client_load_signal.d.ts +59 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +283 -0
  7. package/autoscaling/concurrency_system.js +350 -0
  8. package/autoscaling/cpu_load_signal.d.ts +44 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +54 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +103 -0
  16. package/autoscaling/memory_load_signal.d.ts +56 -0
  17. package/autoscaling/memory_load_signal.js +106 -0
  18. package/autoscaling/snapshotter.d.ts +61 -163
  19. package/autoscaling/snapshotter.js +45 -270
  20. package/autoscaling/system_status.d.ts +63 -83
  21. package/autoscaling/system_status.js +90 -120
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -230
  27. package/configuration.js +170 -226
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +70 -0
  31. package/crawlers/context_pipeline.js +122 -0
  32. package/crawlers/crawler_commons.d.ts +96 -40
  33. package/crawlers/crawler_commons.js +15 -24
  34. package/crawlers/error_snapshotter.d.ts +3 -3
  35. package/crawlers/error_snapshotter.js +2 -3
  36. package/crawlers/error_tracker.d.ts +2 -2
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +1 -3
  40. package/crawlers/internals/types.d.ts +7 -0
  41. package/crawlers/internals/types.js +1 -0
  42. package/crawlers/statistics.d.ts +28 -23
  43. package/crawlers/statistics.js +38 -34
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +39 -26
  51. package/enqueue_links/shared.js +89 -67
  52. package/errors.d.ts +53 -4
  53. package/errors.js +70 -5
  54. package/events/event_manager.d.ts +34 -8
  55. package/events/event_manager.js +8 -10
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -5
  59. package/events/local_event_manager.js +37 -40
  60. package/index.d.ts +6 -4
  61. package/index.js +5 -3
  62. package/iterables.d.ts +79 -0
  63. package/iterables.js +134 -0
  64. package/log.d.ts +82 -3
  65. package/log.js +102 -1
  66. package/memory-storage/consts.d.ts +4 -0
  67. package/memory-storage/consts.js +4 -0
  68. package/memory-storage/index.d.ts +1 -0
  69. package/memory-storage/index.js +1 -0
  70. package/memory-storage/memory-storage.d.ts +46 -0
  71. package/memory-storage/memory-storage.js +136 -0
  72. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  73. package/memory-storage/resource-clients/common/base-client.js +6 -0
  74. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  75. package/memory-storage/resource-clients/dataset.js +113 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +203 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  79. package/memory-storage/resource-clients/request-queue.js +421 -0
  80. package/memory-storage/utils.d.ts +16 -0
  81. package/memory-storage/utils.js +41 -0
  82. package/owned_or_injected.d.ts +60 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +29 -152
  86. package/proxy_configuration.js +21 -173
  87. package/recoverable_state.d.ts +120 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +85 -17
  90. package/request.js +107 -36
  91. package/router.d.ts +194 -19
  92. package/router.js +177 -32
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +1 -2
  95. package/service_locator.d.ts +156 -0
  96. package/service_locator.js +244 -0
  97. package/session_pool/consts.d.ts +1 -2
  98. package/session_pool/consts.js +1 -2
  99. package/session_pool/errors.d.ts +0 -1
  100. package/session_pool/errors.js +0 -1
  101. package/session_pool/fingerprint.d.ts +9 -0
  102. package/session_pool/fingerprint.js +30 -0
  103. package/session_pool/index.d.ts +0 -2
  104. package/session_pool/index.js +0 -2
  105. package/session_pool/session.d.ts +37 -75
  106. package/session_pool/session.js +49 -102
  107. package/session_pool/session_pool.d.ts +85 -90
  108. package/session_pool/session_pool.js +131 -120
  109. package/storages/access_checking.d.ts +1 -2
  110. package/storages/access_checking.js +5 -2
  111. package/storages/dataset.d.ts +103 -54
  112. package/storages/dataset.js +174 -132
  113. package/storages/index.d.ts +8 -7
  114. package/storages/index.js +6 -7
  115. package/storages/key_value_store.d.ts +167 -39
  116. package/storages/key_value_store.js +274 -127
  117. package/storages/key_value_store_codec.d.ts +32 -0
  118. package/storages/key_value_store_codec.js +113 -0
  119. package/storages/request_dedup_cache.d.ts +23 -0
  120. package/storages/request_dedup_cache.js +48 -0
  121. package/storages/request_list.d.ts +54 -98
  122. package/storages/request_list.js +99 -75
  123. package/storages/request_loader.d.ts +96 -0
  124. package/storages/request_loader.js +1 -0
  125. package/storages/request_manager.d.ts +33 -0
  126. package/storages/request_manager.js +1 -0
  127. package/storages/request_manager_tandem.d.ts +106 -0
  128. package/storages/request_manager_tandem.js +197 -0
  129. package/storages/request_queue.d.ts +287 -47
  130. package/storages/request_queue.js +620 -215
  131. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +38 -46
  132. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +58 -65
  133. package/storages/storage_instance_manager.d.ts +88 -0
  134. package/storages/storage_instance_manager.js +256 -0
  135. package/storages/storage_stats.d.ts +48 -0
  136. package/storages/storage_stats.js +29 -0
  137. package/storages/utils.d.ts +54 -9
  138. package/storages/utils.js +64 -13
  139. package/system-info/cpu-info.d.ts +67 -0
  140. package/system-info/cpu-info.js +216 -0
  141. package/system-info/memory-info.d.ts +31 -0
  142. package/system-info/memory-info.js +115 -0
  143. package/system-info/ps-tree.d.ts +17 -0
  144. package/system-info/ps-tree.js +144 -0
  145. package/system-info/runtime.d.ts +14 -0
  146. package/system-info/runtime.js +80 -0
  147. package/typedefs.d.ts +0 -6
  148. package/typedefs.js +0 -1
  149. package/validators.d.ts +8 -1
  150. package/validators.js +10 -3
  151. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  152. package/autoscaling/autoscaled_pool.js.map +0 -1
  153. package/autoscaling/index.d.ts.map +0 -1
  154. package/autoscaling/index.js.map +0 -1
  155. package/autoscaling/snapshotter.d.ts.map +0 -1
  156. package/autoscaling/snapshotter.js.map +0 -1
  157. package/autoscaling/system_status.d.ts.map +0 -1
  158. package/autoscaling/system_status.js.map +0 -1
  159. package/configuration.d.ts.map +0 -1
  160. package/configuration.js.map +0 -1
  161. package/cookie_utils.d.ts.map +0 -1
  162. package/cookie_utils.js.map +0 -1
  163. package/crawlers/crawler_commons.d.ts.map +0 -1
  164. package/crawlers/crawler_commons.js.map +0 -1
  165. package/crawlers/crawler_extension.d.ts +0 -12
  166. package/crawlers/crawler_extension.d.ts.map +0 -1
  167. package/crawlers/crawler_extension.js +0 -14
  168. package/crawlers/crawler_extension.js.map +0 -1
  169. package/crawlers/crawler_utils.d.ts +0 -10
  170. package/crawlers/crawler_utils.d.ts.map +0 -1
  171. package/crawlers/crawler_utils.js +0 -12
  172. package/crawlers/crawler_utils.js.map +0 -1
  173. package/crawlers/error_snapshotter.d.ts.map +0 -1
  174. package/crawlers/error_snapshotter.js.map +0 -1
  175. package/crawlers/error_tracker.d.ts.map +0 -1
  176. package/crawlers/error_tracker.js.map +0 -1
  177. package/crawlers/index.d.ts.map +0 -1
  178. package/crawlers/index.js.map +0 -1
  179. package/crawlers/statistics.d.ts.map +0 -1
  180. package/crawlers/statistics.js.map +0 -1
  181. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  182. package/enqueue_links/enqueue_links.js.map +0 -1
  183. package/enqueue_links/index.d.ts.map +0 -1
  184. package/enqueue_links/index.js.map +0 -1
  185. package/enqueue_links/shared.d.ts.map +0 -1
  186. package/enqueue_links/shared.js.map +0 -1
  187. package/errors.d.ts.map +0 -1
  188. package/errors.js.map +0 -1
  189. package/events/event_manager.d.ts.map +0 -1
  190. package/events/event_manager.js.map +0 -1
  191. package/events/index.d.ts.map +0 -1
  192. package/events/index.js.map +0 -1
  193. package/events/local_event_manager.d.ts.map +0 -1
  194. package/events/local_event_manager.js.map +0 -1
  195. package/http_clients/base-http-client.d.ts +0 -134
  196. package/http_clients/base-http-client.d.ts.map +0 -1
  197. package/http_clients/base-http-client.js +0 -33
  198. package/http_clients/base-http-client.js.map +0 -1
  199. package/http_clients/form-data-like.d.ts +0 -67
  200. package/http_clients/form-data-like.d.ts.map +0 -1
  201. package/http_clients/form-data-like.js +0 -5
  202. package/http_clients/form-data-like.js.map +0 -1
  203. package/http_clients/got-scraping-http-client.d.ts +0 -15
  204. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  205. package/http_clients/got-scraping-http-client.js +0 -69
  206. package/http_clients/got-scraping-http-client.js.map +0 -1
  207. package/http_clients/index.d.ts +0 -3
  208. package/http_clients/index.d.ts.map +0 -1
  209. package/http_clients/index.js +0 -3
  210. package/http_clients/index.js.map +0 -1
  211. package/index.d.ts.map +0 -1
  212. package/index.js.map +0 -1
  213. package/log.d.ts.map +0 -1
  214. package/log.js.map +0 -1
  215. package/proxy_configuration.d.ts.map +0 -1
  216. package/proxy_configuration.js.map +0 -1
  217. package/request.d.ts.map +0 -1
  218. package/request.js.map +0 -1
  219. package/router.d.ts.map +0 -1
  220. package/router.js.map +0 -1
  221. package/serialization.d.ts.map +0 -1
  222. package/serialization.js.map +0 -1
  223. package/session_pool/consts.d.ts.map +0 -1
  224. package/session_pool/consts.js.map +0 -1
  225. package/session_pool/errors.d.ts.map +0 -1
  226. package/session_pool/errors.js.map +0 -1
  227. package/session_pool/events.d.ts +0 -3
  228. package/session_pool/events.d.ts.map +0 -1
  229. package/session_pool/events.js +0 -3
  230. package/session_pool/events.js.map +0 -1
  231. package/session_pool/index.d.ts.map +0 -1
  232. package/session_pool/index.js.map +0 -1
  233. package/session_pool/session.d.ts.map +0 -1
  234. package/session_pool/session.js.map +0 -1
  235. package/session_pool/session_pool.d.ts.map +0 -1
  236. package/session_pool/session_pool.js.map +0 -1
  237. package/storages/access_checking.d.ts.map +0 -1
  238. package/storages/access_checking.js.map +0 -1
  239. package/storages/dataset.d.ts.map +0 -1
  240. package/storages/dataset.js.map +0 -1
  241. package/storages/index.d.ts.map +0 -1
  242. package/storages/index.js.map +0 -1
  243. package/storages/key_value_store.d.ts.map +0 -1
  244. package/storages/key_value_store.js.map +0 -1
  245. package/storages/request_list.d.ts.map +0 -1
  246. package/storages/request_list.js.map +0 -1
  247. package/storages/request_provider.d.ts +0 -307
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -555
  250. package/storages/request_provider.js.map +0 -1
  251. package/storages/request_queue.d.ts.map +0 -1
  252. package/storages/request_queue.js.map +0 -1
  253. package/storages/request_queue_v2.d.ts +0 -87
  254. package/storages/request_queue_v2.d.ts.map +0 -1
  255. package/storages/request_queue_v2.js +0 -438
  256. package/storages/request_queue_v2.js.map +0 -1
  257. package/storages/sitemap_request_list.d.ts.map +0 -1
  258. package/storages/sitemap_request_list.js.map +0 -1
  259. package/storages/storage_manager.d.ts +0 -58
  260. package/storages/storage_manager.d.ts.map +0 -1
  261. package/storages/storage_manager.js +0 -105
  262. package/storages/storage_manager.js.map +0 -1
  263. package/storages/utils.d.ts.map +0 -1
  264. package/storages/utils.js.map +0 -1
  265. package/tsconfig.build.tsbuildinfo +0 -1
  266. package/typedefs.d.ts.map +0 -1
  267. package/typedefs.js.map +0 -1
  268. package/validators.d.ts.map +0 -1
  269. 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,19 +1,64 @@
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';
9
- import type { Request, Source } from '../request.js';
10
- import type { Session } from '../session_pool/session.js';
5
+ import type { CrawleeLogger } from '../log.js';
6
+ import type { Request, RequestOptions, Source } from '../request.js';
7
+ import type { StorageIdentifier } from '../storages/storage_instance_manager.js';
11
8
  import type { Dataset } from '../storages/dataset.js';
12
9
  import { KeyValueStore, type RecordOptions } from '../storages/key_value_store.js';
13
- import type { RequestQueueOperationOptions } from '../storages/request_provider.js';
10
+ import type { RequestQueueOperationOptions } from '../storages/request_queue.js';
14
11
  /** @internal */
15
12
  export type IsAny<T> = 0 extends 1 & T ? true : false;
16
- /** @internal */
13
+ /**
14
+ * A request input (URL string, request-options object, or {@link Request}) whose `userData` is typed
15
+ * according to its `label`, based on a router's route map.
16
+ *
17
+ * When the route map is open (the default `Record<string, ...>`), this is just the regular loose
18
+ * {@link Source} input. When the map declares concrete labels, providing a `label` requires the matching
19
+ * `userData` shape and rejects labels not present in the map; unlabeled requests keep loose `userData`.
20
+ */
21
+ export type LabeledSource<Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? string | Source : string | Request | ({
22
+ requestsFromUrl?: string;
23
+ regex?: RegExp;
24
+ } & ({
25
+ [Label in keyof Routes & string]: Omit<Partial<RequestOptions<Routes[Label]>>, 'label'> & {
26
+ label: Label;
27
+ };
28
+ }[keyof Routes & string] | (Omit<Partial<RequestOptions>, 'label'> & {
29
+ label?: undefined;
30
+ })));
31
+ /**
32
+ * The iterable/array of {@link LabeledSource} inputs accepted by the label-aware `addRequests`/`run`
33
+ * methods of a crawler bound to a typed router.
34
+ * @internal
35
+ */
36
+ export type TypedRequestsLike<Routes extends Record<keyof Routes, Dictionary>> = AsyncIterable<LabeledSource<Routes>> | Iterable<LabeledSource<Routes>> | LabeledSource<Routes>[];
37
+ /**
38
+ * The label-aware `addRequests` method signature exposed on a request handler's context when the crawler is
39
+ * bound to a typed router. Mirrors {@link RestrictedCrawlingContext.addRequests} with typed sources.
40
+ */
41
+ export type TypedContextAddRequests<Routes extends Record<keyof Routes, Dictionary>> = (requestsLike: ReadonlyDeep<LabeledSource<Routes>[]>, options?: ReadonlyDeep<RequestQueueOperationOptions>) => Promise<void>;
42
+ /**
43
+ * An `enqueueLinks`-options object with its `label`/`userData` retyped according to a router's route map: a
44
+ * declared `label` requires the matching `userData` shape (unknown labels are rejected), while unlabeled
45
+ * calls keep loose `userData`. Returns the options unchanged when the route map is open (the default).
46
+ */
47
+ type TypedEnqueueLinksOptions<Options, Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? Options : Omit<Options, 'label' | 'userData'> & ({
48
+ [Label in keyof Routes & string]: {
49
+ label: Label;
50
+ userData?: Routes[Label];
51
+ };
52
+ }[keyof Routes & string] | {
53
+ label?: undefined;
54
+ userData?: Dictionary;
55
+ });
56
+ /**
57
+ * Transforms a context's existing `enqueueLinks` method so that the `label`/`userData` in its options follow
58
+ * the router's route map, while preserving everything else about the signature (argument optionality and
59
+ * return type, which differ between crawler types).
60
+ */
61
+ export type TypedContextEnqueueLinks<EnqueueLinks, Routes extends Record<keyof Routes, Dictionary>> = EnqueueLinks extends (options?: infer Options) => infer Result ? (options?: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks extends (options: infer Options) => infer Result ? (options: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks;
17
62
  export type WithRequired<T, K extends keyof T> = T & {
18
63
  [P in K]-?: T[P];
19
64
  };
@@ -22,9 +67,9 @@ export type LoadedRequest<R extends Request> = WithRequired<R, 'id' | 'loadedUrl
22
67
  export type LoadedContext<Context extends RestrictedCrawlingContext> = IsAny<Context> extends true ? Context : {
23
68
  request: LoadedRequest<Context['request']>;
24
69
  } & Omit<Context, 'request'>;
25
- export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> extends Record<string & {}, unknown> {
70
+ export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> {
26
71
  id: string;
27
- session?: Session;
72
+ session: ISession;
28
73
  /**
29
74
  * An object with information about currently used proxy by the crawler
30
75
  * and configured by the {@link ProxyConfiguration} class.
@@ -41,13 +86,12 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
41
86
  *
42
87
  * @param [data] Data to be pushed to the default dataset.
43
88
  */
44
- pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdOrName?: string): Promise<void>;
89
+ pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdentifier?: string | StorageIdentifier): Promise<void>;
45
90
  /**
46
91
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
47
92
  * currently used by the crawler.
48
93
  *
49
- * Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
50
- * and override settings of the enqueued {@link Request} objects.
94
+ * Optionally, the function allows you to filter the target links' URLs using an array of glob or regexp patterns.
51
95
  *
52
96
  * Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
53
97
  * for more details regarding its usage.
@@ -57,7 +101,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
57
101
  * ```ts
58
102
  * async requestHandler({ enqueueLinks }) {
59
103
  * await enqueueLinks({
60
- * globs: [
104
+ * include: [
61
105
  * 'https://www.example.com/handbags/*',
62
106
  * ],
63
107
  * });
@@ -66,7 +110,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
66
110
  *
67
111
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
68
112
  */
69
- enqueueLinks: (options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>>) => Promise<unknown>;
113
+ enqueueLinks: (options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>>) => Promise<unknown>;
70
114
  /**
71
115
  * Add requests directly to the request queue.
72
116
  *
@@ -81,20 +125,18 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
81
125
  /**
82
126
  * Get a key-value store with given name or id, or the default one for the crawler.
83
127
  */
84
- getKeyValueStore: (idOrName?: string) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
128
+ getKeyValueStore: (identifier?: string | StorageIdentifier) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
85
129
  /**
86
130
  * A preconfigured logger for the request handler.
87
131
  */
88
- log: Log;
132
+ log: CrawleeLogger;
89
133
  }
90
- export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
91
- crawler: Crawler;
134
+ export interface CrawlingContext<UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
92
135
  /**
93
136
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
94
137
  * currently used by the crawler.
95
138
  *
96
- * Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
97
- * and override settings of the enqueued {@link Request} objects.
139
+ * Optionally, the function allows you to filter the target links' URLs using an array of glob or regexp patterns.
98
140
  *
99
141
  * Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
100
142
  * for more details regarding its usage.
@@ -104,7 +146,7 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
104
146
  * ```ts
105
147
  * async requestHandler({ enqueueLinks }) {
106
148
  * await enqueueLinks({
107
- * globs: [
149
+ * include: [
108
150
  * 'https://www.example.com/handbags/*',
109
151
  * ],
110
152
  * });
@@ -114,14 +156,9 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
114
156
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
115
157
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
116
158
  */
117
- enqueueLinks(options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>> & Pick<EnqueueLinksOptions, 'requestQueue'>): Promise<BatchAddRequestsResult>;
159
+ enqueueLinks(options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>> & Pick<EnqueueLinksOptions, 'requestManager' | 'robotsTxtFile'>): Promise<unknown>;
118
160
  /**
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.
161
+ * Fires HTTP request via the internal HTTP client, allowing to override the request options on the fly.
125
162
  *
126
163
  * This is handy when you work with a browser crawler but want to execute some requests outside it (e.g. API requests).
127
164
  * Check the [Skipping navigations for certain requests](https://crawlee.dev/js/docs/examples/skip-navigation) example for
@@ -136,7 +173,30 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
136
173
  * },
137
174
  * ```
138
175
  */
139
- sendRequest<Response = string>(overrideOptions?: Partial<OptionsInit>): Promise<GotResponse<Response>>;
176
+ sendRequest: (requestOverrides?: Partial<HttpRequestOptions>, optionsOverrides?: SendRequestOptions) => Promise<Response>;
177
+ /**
178
+ * 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.
179
+ */
180
+ registerDeferredCleanup(cleanup: () => Promise<unknown>): void;
181
+ /**
182
+ * Gives the current request `secs` more seconds to finish, for when how long it needs is only apparent
183
+ * once it is already running - a listing page that turns out to have far more to scroll through than
184
+ * usual, say. Prefer `requestHandlerTimeoutSecs`, or a per-route override via
185
+ * {@link Router.addHandler|`router.addHandler`}, whenever the time needed is known up front.
186
+ *
187
+ * ```ts
188
+ * router.addHandler('LIST', async ({ extendTimeout, page }) => {
189
+ * const pageCount = await countPages(page);
190
+ * extendTimeout(pageCount * 10);
191
+ * await scrapeAllPages(page);
192
+ * });
193
+ * ```
194
+ *
195
+ * Extends the request handler's own timeout and the crawler's internal one together, so the extension
196
+ * is not immediately undone by the latter. Calling it from a handler that has already timed out does
197
+ * nothing.
198
+ */
199
+ extendTimeout(secs: number): void;
140
200
  }
141
201
  /**
142
202
  * A partial implementation of {@link RestrictedCrawlingContext} that stores parameters of calls to context methods for later inspection.
@@ -144,20 +204,18 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
144
204
  * @experimental
145
205
  */
146
206
  export declare class RequestHandlerResult {
147
- private config;
207
+ private configuration;
148
208
  private crawleeStateKey;
149
209
  private _keyValueStoreChanges;
150
210
  private pushDataCalls;
151
211
  private addRequestsCalls;
152
- private enqueueLinksCalls;
153
- constructor(config: Configuration, crawleeStateKey: string);
212
+ constructor(configuration: Configuration, crawleeStateKey: string);
154
213
  /**
155
214
  * A record of calls to {@link RestrictedCrawlingContext.pushData}, {@link RestrictedCrawlingContext.addRequests}, {@link RestrictedCrawlingContext.enqueueLinks} made by a request handler.
156
215
  */
157
216
  get calls(): ReadonlyDeep<{
158
217
  pushData: Parameters<RestrictedCrawlingContext['pushData']>[];
159
218
  addRequests: Parameters<RestrictedCrawlingContext['addRequests']>[];
160
- enqueueLinks: Parameters<RestrictedCrawlingContext['enqueueLinks']>[];
161
219
  }>;
162
220
  /**
163
221
  * A record of changes made to key-value stores by a request handler.
@@ -171,7 +229,7 @@ export declare class RequestHandlerResult {
171
229
  */
172
230
  get datasetItems(): ReadonlyDeep<{
173
231
  item: Dictionary;
174
- datasetIdOrName?: string;
232
+ datasetIdentifier?: string | StorageIdentifier;
175
233
  }[]>;
176
234
  /**
177
235
  * URLs enqueued to the request queue by a request handler, either via {@link RestrictedCrawlingContext.addRequests} or {@link RestrictedCrawlingContext.enqueueLinks}
@@ -188,12 +246,10 @@ export declare class RequestHandlerResult {
188
246
  label?: string;
189
247
  }[]>;
190
248
  pushData: RestrictedCrawlingContext['pushData'];
191
- enqueueLinks: RestrictedCrawlingContext['enqueueLinks'];
192
249
  addRequests: RestrictedCrawlingContext['addRequests'];
193
250
  useState: RestrictedCrawlingContext['useState'];
194
251
  getKeyValueStore: RestrictedCrawlingContext['getKeyValueStore'];
195
- private idOrDefault;
196
252
  private getKeyValueStoreChangedValue;
197
253
  private setKeyValueStoreChangedValue;
198
254
  }
199
- //# sourceMappingURL=crawler_commons.d.ts.map
255
+ export {};
@@ -5,14 +5,13 @@ import { KeyValueStore } from '../storages/key_value_store.js';
5
5
  * @experimental
6
6
  */
7
7
  export class RequestHandlerResult {
8
- config;
8
+ configuration;
9
9
  crawleeStateKey;
10
10
  _keyValueStoreChanges = {};
11
11
  pushDataCalls = [];
12
12
  addRequestsCalls = [];
13
- enqueueLinksCalls = [];
14
- constructor(config, crawleeStateKey) {
15
- this.config = config;
13
+ constructor(configuration, crawleeStateKey) {
14
+ this.configuration = configuration;
16
15
  this.crawleeStateKey = crawleeStateKey;
17
16
  }
18
17
  /**
@@ -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, { configuration: this.configuration });
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.configuration.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.configuration.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.configuration.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,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,5 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
- export * from './crawler_utils.js';
4
3
  export * from './statistics.js';
5
4
  export * from './error_tracker.js';
6
5
  export * from './error_snapshotter.js';
7
- //# sourceMappingURL=index.d.ts.map
package/crawlers/index.js CHANGED
@@ -1,7 +1,5 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
- export * from './crawler_utils.js';
4
3
  export * from './statistics.js';
5
4
  export * from './error_tracker.js';
6
5
  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 {};